Bug fixes - Sync database.js schema with actual production DB (tarifoptionen shape was wrong; new installs would have broken). - Fix SQL syntax error `SELECT to.*` (reserved keyword) in single- schaltung provision endpoint, plus the dead fallback hierarchy that selected columns that were never in the query. - Fix PUT /api/tarifoptionen/:id writing to non-existent column provision_betrag (should be provision_euro). - Fix race condition in PUT /api/schaltungen/:id where forEach with async db.run inside a transaction could send duplicate responses. - Delete dokumente rows explicitly before deleting schaltung (existing DBs lack ON DELETE CASCADE on dokumente FK). - Replace hardcoded basisBetrag=100 for percent rules; basis is now configurable per rule via the new basis_euro column. Security - Multi-user authentication: users table, bcryptjs, express-session with SQLite store, login/logout/me/setup/change-password endpoints. - Auth gate on all /api/* except /api/auth/*. - CLI to create users: npm run create-user -- <user> <pass> [--admin]. - helmet for security headers. - CORS restricted to ALLOWED_ORIGINS env (default same-origin). - Rate limits: 300/min global, 20/15min on login. - Path-traversal validation on document download/delete. - XSS hardening in frontend: escapeHtml helper applied to all DB-derived innerHTML interpolations; inline onclick handlers that embedded user-controlled strings replaced with data-* attrs + addEventListener. Architecture - Provision calculation centralised in provisionService.js as the single source of truth (was duplicated and inconsistent). - server.js cut from 2138 to ~140 lines; routes split into per- resource modules under routes/. - Promise wrapper db.js for sqlite3 callbacks; async/await in routes. - middleware/ for auth and async error handling. Tests - 14 unit tests for provisionService covering fallback hierarchy, percent calculation, tarifoptionen, hardware logic, employee commission. All green. Config - dotenv loads .env.local at startup (gitignored). - .gitignore extended for sessions.db and .env*. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
124 lines
4.5 KiB
JavaScript
124 lines
4.5 KiB
JavaScript
const express = require('express');
|
|
const db = require('../db');
|
|
const asyncHandler = require('../middleware/asyncHandler');
|
|
|
|
const router = express.Router();
|
|
|
|
function validateAmount(amount) {
|
|
return amount === null || amount === undefined || (Number.isFinite(parseFloat(amount)) && parseFloat(amount) >= 0);
|
|
}
|
|
|
|
router.get('/', asyncHandler(async (req, res) => {
|
|
const rows = await db.all(
|
|
`SELECT t.*, a.name AS anbieter_name
|
|
FROM tarife t
|
|
JOIN anbieter a ON t.anbieter_id = a.id
|
|
ORDER BY a.name, t.name`
|
|
);
|
|
res.json(rows);
|
|
}));
|
|
|
|
router.get('/:anbieter_id', asyncHandler(async (req, res) => {
|
|
const { anbieter_id } = req.params;
|
|
const rows = await db.all('SELECT * FROM tarife WHERE anbieter_id = ? ORDER BY name', [anbieter_id]);
|
|
res.json(rows);
|
|
}));
|
|
|
|
router.post('/', asyncHandler(async (req, res) => {
|
|
const { name, anbieter_id, provision_euro, beschreibung } = req.body || {};
|
|
|
|
if (!name || !name.trim()) {
|
|
return res.status(400).json({ error: 'Tarifname ist erforderlich' });
|
|
}
|
|
if (!anbieter_id) {
|
|
return res.status(400).json({ error: 'Anbieter ist erforderlich' });
|
|
}
|
|
if (!validateAmount(provision_euro)) {
|
|
return res.status(400).json({ error: 'Provision muss eine positive Zahl sein' });
|
|
}
|
|
|
|
try {
|
|
const result = await db.run(
|
|
`INSERT INTO tarife (name, anbieter_id, provision_euro, beschreibung) VALUES (?, ?, ?, ?)`,
|
|
[name.trim(), anbieter_id, provision_euro || 0, beschreibung || null]
|
|
);
|
|
res.json({
|
|
id: result.lastID,
|
|
name: name.trim(),
|
|
anbieter_id,
|
|
provision_euro: provision_euro || 0,
|
|
beschreibung: beschreibung || null,
|
|
});
|
|
} catch (err) {
|
|
if (/UNIQUE/.test(err.message)) {
|
|
return res.status(400).json({ error: 'Tarif mit diesem Namen existiert bereits für diesen Anbieter' });
|
|
}
|
|
throw err;
|
|
}
|
|
}));
|
|
|
|
router.put('/:id', asyncHandler(async (req, res) => {
|
|
const { id } = req.params;
|
|
const { name, provision_euro, beschreibung } = req.body || {};
|
|
if (!name) return res.status(400).json({ error: 'Tarif-Name ist erforderlich' });
|
|
if (!validateAmount(provision_euro)) {
|
|
return res.status(400).json({ error: 'Provision muss eine positive Zahl sein' });
|
|
}
|
|
const result = await db.run(
|
|
`UPDATE tarife SET name = ?, provision_euro = ?, beschreibung = ? WHERE id = ?`,
|
|
[name, provision_euro || 0, beschreibung || null, id]
|
|
);
|
|
if (result.changes === 0) return res.status(404).json({ error: 'Tarif nicht gefunden' });
|
|
res.json({ message: 'Tarif erfolgreich aktualisiert' });
|
|
}));
|
|
|
|
router.delete('/:id', asyncHandler(async (req, res) => {
|
|
const { id } = req.params;
|
|
const used = await db.get(
|
|
'SELECT EXISTS(SELECT 1 FROM schaltungen WHERE tarif_id = ?) AS has_schaltungen',
|
|
[id]
|
|
);
|
|
if (used.has_schaltungen) {
|
|
return res.status(400).json({ error: 'Tarif kann nicht gelöscht werden: Tarif wird in Schaltungen verwendet' });
|
|
}
|
|
const result = await db.run('DELETE FROM tarife WHERE id = ?', [id]);
|
|
if (result.changes === 0) return res.status(404).json({ error: 'Tarif nicht gefunden' });
|
|
res.json({ message: 'Tarif erfolgreich gelöscht' });
|
|
}));
|
|
|
|
router.get('/:tarif_id/tarifoptionen', asyncHandler(async (req, res) => {
|
|
const { tarif_id } = req.params;
|
|
const rows = await db.all(
|
|
'SELECT * FROM tarifoptionen WHERE tarif_id = ? AND aktiv = 1 ORDER BY name',
|
|
[tarif_id]
|
|
);
|
|
res.json(rows);
|
|
}));
|
|
|
|
router.get('/:id/provisionsregeln', asyncHandler(async (req, res) => {
|
|
const { id } = req.params;
|
|
const rows = await db.all(
|
|
`SELECT pr.*, t.name AS tarif_name, a.name AS anbieter_name
|
|
FROM provisionsregeln pr
|
|
JOIN tarife t ON pr.tarif_id = t.id
|
|
JOIN anbieter a ON t.anbieter_id = a.id
|
|
WHERE pr.tarif_id = ? AND pr.aktiv = 1
|
|
ORDER BY pr.gueltig_ab DESC`,
|
|
[id]
|
|
);
|
|
res.json(rows);
|
|
}));
|
|
|
|
router.put('/:id/mitarbeiter-provision', asyncHandler(async (req, res) => {
|
|
const { id } = req.params;
|
|
const { mitarbeiter_provision } = req.body || {};
|
|
const result = await db.run(
|
|
'UPDATE tarife SET mitarbeiter_provision = ? WHERE id = ?',
|
|
[mitarbeiter_provision || 0, id]
|
|
);
|
|
if (result.changes === 0) return res.status(404).json({ error: 'Tarif nicht gefunden' });
|
|
res.json({ message: 'Mitarbeiter-Provision erfolgreich aktualisiert' });
|
|
}));
|
|
|
|
module.exports = router;
|