Files
prov/routes/provisionen.js
T
kerimatilganandClaude Opus 4.7 4303b00b9b Major refactor: auth, bug fixes, security hardening, modular routes
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>
2026-05-14 21:43:19 +02:00

152 lines
5.6 KiB
JavaScript

const express = require('express');
const db = require('../db');
const asyncHandler = require('../middleware/asyncHandler');
const provisionService = require('../provisionService');
const router = express.Router();
// Load all inputs needed by provisionService.calculate for one schaltung.
async function loadProvisionContext(schaltungId) {
const schaltung = await db.get(
`SELECT s.*,
t.name AS tarif_name, t.provision_euro AS tarif_provision_euro,
t.mitarbeiter_provision AS tarif_mitarbeiter_provision,
t.beschreibung AS tarif_beschreibung,
a.name AS anbieter_name
FROM schaltungen s
JOIN tarife t ON s.tarif_id = t.id
JOIN anbieter a ON s.anbieter_id = a.id
WHERE s.id = ?`,
[schaltungId]
);
if (!schaltung) return null;
const tarif = {
id: schaltung.tarif_id,
name: schaltung.tarif_name,
provision_euro: schaltung.tarif_provision_euro,
mitarbeiter_provision: schaltung.tarif_mitarbeiter_provision,
beschreibung: schaltung.tarif_beschreibung,
};
const tarifRule = await db.get(
`SELECT * FROM provisionsregeln
WHERE tarif_id = ? AND aktiv = 1 AND gueltig_ab <= ?
ORDER BY gueltig_ab DESC LIMIT 1`,
[schaltung.tarif_id, schaltung.schaltungs_datum]
);
const anbieterRule = await db.get(
`SELECT * FROM anbieter_provisionsregeln
WHERE anbieter_id = ? AND aktiv = 1 AND gueltig_ab <= ?
ORDER BY gueltig_ab DESC LIMIT 1`,
[schaltung.anbieter_id, schaltung.schaltungs_datum]
);
const tarifoptionen = await db.all(
`SELECT t.*
FROM tarifoptionen t
JOIN schaltungen_tarifoptionen st ON t.id = st.tarifoption_id
WHERE st.schaltung_id = ?`,
[schaltungId]
);
const mp = await db.get(
`SELECT prozentsatz FROM mitarbeiter_prozentsaetze
WHERE anbieter_id = ? AND gueltig_ab <= ?
ORDER BY gueltig_ab DESC LIMIT 1`,
[schaltung.anbieter_id, schaltung.schaltungs_datum]
);
return {
schaltung,
tarif,
tarifRule: tarifRule || null,
anbieterRule: anbieterRule || null,
tarifoptionen,
mitarbeiterProzentsatz: mp ? mp.prozentsatz : 0,
};
}
// Provision for a single schaltung
router.get('/schaltungen/:id/provision', asyncHandler(async (req, res) => {
const ctx = await loadProvisionContext(req.params.id);
if (!ctx) return res.status(404).json({ error: 'Schaltung nicht gefunden' });
const result = provisionService.calculate(ctx);
res.json({
id: ctx.schaltung.id,
schaltungs_id: ctx.schaltung.schaltungs_id,
schaltungs_datum: ctx.schaltung.schaltungs_datum,
vorname: ctx.schaltung.vorname,
nachname: ctx.schaltung.nachname,
firma: ctx.schaltung.firma,
tarif_name: ctx.tarif.name,
anbieter_name: ctx.schaltung.anbieter_name,
shop_provision: result.shop,
mitarbeiter_provision: result.mitarbeiter,
tarifoptionen: result.tarifoptionen,
hardware_gewinn: result.hardware_gewinn,
// Legacy flat fields for older frontend code
berechnete_shop_provision: result.shop.betrag.toFixed(2),
berechnete_mitarbeiter_provision: result.mitarbeiter.betrag.toFixed(2),
shop_quelle: result.shop.quelle,
mitarbeiter_quelle: result.mitarbeiter.quelle,
});
}));
// Aggregated commission overview across all schaltungen
router.get('/provisionen', asyncHandler(async (req, res) => {
const schaltungen = await db.all('SELECT id FROM schaltungen ORDER BY schaltungs_datum DESC');
const processed = [];
let totalShop = 0;
let totalMitarbeiter = 0;
for (const { id } of schaltungen) {
const ctx = await loadProvisionContext(id);
if (!ctx) continue;
const result = provisionService.calculate(ctx);
totalShop += result.shop.betrag;
totalMitarbeiter += result.mitarbeiter.betrag;
processed.push({
id: ctx.schaltung.id,
schaltungs_id: ctx.schaltung.schaltungs_id,
eingabe_datum: ctx.schaltung.eingabe_datum,
schaltungs_datum: ctx.schaltung.schaltungs_datum,
vorname: ctx.schaltung.vorname,
nachname: ctx.schaltung.nachname,
firma: ctx.schaltung.firma,
hardware: ctx.schaltung.hardware,
hardware_ek: ctx.schaltung.hardware_ek,
kundenverkaufspreis_netto: ctx.schaltung.kundenverkaufspreis_netto,
tarif_name: ctx.tarif.name,
anbieter_name: ctx.schaltung.anbieter_name,
shop_provision_euro: result.shop.betrag,
berechnete_shop_provision: result.shop.betrag.toFixed(2),
mitarbeiter_prozentsatz: result.mitarbeiter.prozentsatz,
berechnete_mitarbeiter_provision: result.mitarbeiter.betrag.toFixed(2),
shop_quelle: result.shop.quelle,
mitarbeiter_quelle: result.mitarbeiter.quelle,
tarifoptionen_provision: result.tarifoptionen.betrag,
hardware_gewinn: result.hardware_gewinn,
});
}
res.json({
schaltungen: processed,
total_provision: totalShop.toFixed(2),
total_shop_provision: totalShop.toFixed(2),
total_mitarbeiter_provision: totalMitarbeiter.toFixed(2),
total_gesamt_provision: (totalShop + totalMitarbeiter).toFixed(2),
});
}));
// Deleted schaltungen list
router.get('/geloeschte-schaltungen', asyncHandler(async (req, res) => {
const rows = await db.all('SELECT * FROM geloeschte_schaltungen ORDER BY geloescht_am DESC');
res.json(rows);
}));
module.exports = router;