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>
This commit is contained in:
kerimatilganandClaude Opus 4.7 committed 2026-05-14 21:43:19 +02:00
1 parent 55ec916f35
commit 4303b00b9b
23 files changed
+2427 -2575

No files matched your search

+135 -167
View File
@@ -1,184 +1,152 @@
/**
* Commission Calculation Service
*
* This service handles all commission calculations for schaltungen.
* It implements a fallback hierarchy for determining commission rates:
* 1. Direct tariff commission (highest priority)
* 2. Tariff-specific rules
* 3. Global provider rules (fallback)
* 4. Tariff options (additive)
*/
// Commission calculation service. Single source of truth used by all provision endpoints.
//
// Hierarchy for shop commission (highest priority wins):
// 1. Tariff-specific rule (provisionsregeln, active, gueltig_ab <= schaltungs_datum)
// 2. Global provider rule (anbieter_provisionsregeln, active, gueltig_ab <= schaltungs_datum)
// 3. Direct tariff amount (tarife.provision_euro)
//
// For type='prozent' the rule's basis_euro field is the base amount the percentage
// applies to. If basis_euro is missing on a percent rule, the contribution is 0
// (rule is effectively unusable - caller should validate at write time).
//
// Tarifoptionen are added on top (signed: rebates are negative).
// Hardware logic: when hardware is set, shop = shop - hardware_ek + kundenverkaufspreis_netto.
//
// Employee commission follows the same hierarchy but uses verkaeufer_* fields.
// For type='prozent' the base is the computed shop commission.
/**
* Calculate shop commission based on hierarchy
* @param {Object} schaltungData - Data from database including tariff and provider info
* @param {Array} tarifoptionen - Selected tariff options for this schaltung
* @returns {Object} Calculation result with amount, type, description, and source
*/
function calculateShopProvision(schaltungData, tarifoptionen) {
let provision_typ = null;
let provision_betrag = null;
let provision_beschreibung = null;
let berechnete_provision = 0;
let quelle = 'Keine Shop-Provision definiert';
// Priority 1: Direct tariff commission
if (schaltungData.tarif_provision_typ && schaltungData.tarif_provision_betrag) {
provision_typ = schaltungData.tarif_provision_typ;
provision_betrag = schaltungData.tarif_provision_betrag;
provision_beschreibung = schaltungData.tarif_provision_beschreibung;
quelle = 'Direkte Tarif-Provision';
}
// Priority 2: Tariff-specific rule
else if (schaltungData.regel_provision_typ && schaltungData.regel_provision_betrag) {
provision_typ = schaltungData.regel_provision_typ;
provision_betrag = schaltungData.regel_provision_betrag;
provision_beschreibung = schaltungData.regel_provision_beschreibung;
quelle = 'Tarif-spezifische Regel';
}
// Priority 3: Global provider rule as fallback
else if (schaltungData.global_provision_typ && schaltungData.global_provision_betrag) {
provision_typ = schaltungData.global_provision_typ;
provision_betrag = schaltungData.global_provision_betrag;
provision_beschreibung = schaltungData.global_provision_beschreibung;
quelle = 'Globale Anbieter-Regel';
}
// Calculate base commission
if (provision_typ && provision_betrag) {
if (provision_typ === 'fix') {
berechnete_provision = parseFloat(provision_betrag);
} else if (provision_typ === 'prozent') {
const basisBetrag = 100; // This could come from tariff table
berechnete_provision = (parseFloat(provision_betrag) / 100) * basisBetrag;
}
}
// Add tarifoptionen to commission
let tarifoptionen_provision = 0;
let verwendete_tarifoptionen = [];
if (tarifoptionen && tarifoptionen.length > 0) {
tarifoptionen.forEach(option => {
if (option.provision_betrag && option.provision_betrag > 0) {
tarifoptionen_provision += parseFloat(option.provision_betrag);
verwendete_tarifoptionen.push(option.name);
}
});
}
berechnete_provision += tarifoptionen_provision;
// Update description if tarifoptionen were added
if (tarifoptionen_provision > 0) {
const tarifoptionen_text = verwendete_tarifoptionen.join(', ');
provision_beschreibung = provision_beschreibung
? `${provision_beschreibung} + Tarifoptionen: ${tarifoptionen_text}`
: `Tarifoptionen: ${tarifoptionen_text}`;
}
return {
typ: provision_typ,
betrag: provision_betrag,
beschreibung: provision_beschreibung,
berechnete_provision: berechnete_provision,
quelle: quelle,
tarifoptionen_provision: tarifoptionen_provision
};
function num(value) {
const n = parseFloat(value);
return Number.isFinite(n) ? n : 0;
}
/**
* Calculate employee commission based on hierarchy
* @param {Object} schaltungData - Data from database including tariff and provider info
* @param {number} shopProvision - Calculated shop commission (for percentage calculations)
* @returns {Object} Calculation result with amount, type, description, and source
*/
function calculateMitarbeiterProvision(schaltungData, shopProvision) {
let provision_typ = null;
let provision_betrag = null;
let provision_beschreibung = null;
let berechnete_provision = 0;
let quelle = 'Keine Mitarbeiter-Provision definiert';
function pickRule(context) {
// Returns the active rule that should apply, or null.
// context: { tarifRule, anbieterRule, tarif }
if (context.tarifRule) {
return { source: 'Tarif-spezifische Regel', rule: context.tarifRule };
}
if (context.anbieterRule) {
return { source: 'Globale Anbieter-Regel', rule: context.anbieterRule };
}
if (context.tarif && context.tarif.provision_euro != null && num(context.tarif.provision_euro) !== 0) {
return {
source: 'Direkte Tarif-Provision',
rule: {
provision_typ: 'fix',
betrag: num(context.tarif.provision_euro),
basis_euro: null,
beschreibung: context.tarif.beschreibung || null,
verkaeufer_provision_typ: null,
verkaeufer_provision_betrag: null,
verkaeufer_provision_beschreibung: null,
},
};
}
return null;
}
// Priority 1: Direct tariff employee commission
if (schaltungData.tarif_verkaeufer_provision_typ && schaltungData.tarif_verkaeufer_provision_betrag) {
provision_typ = schaltungData.tarif_verkaeufer_provision_typ;
provision_betrag = schaltungData.tarif_verkaeufer_provision_betrag;
provision_beschreibung = schaltungData.tarif_verkaeufer_provision_beschreibung;
quelle = 'Direkte Tarif-Verkäufer-Provision';
function applyShopRule(rule) {
if (!rule) return 0;
if (rule.provision_typ === 'fix') {
return num(rule.betrag);
}
// Priority 2: Tariff-specific rule employee commission
else if (schaltungData.regel_verkaeufer_provision_typ && schaltungData.regel_verkaeufer_provision_betrag) {
provision_typ = schaltungData.regel_verkaeufer_provision_typ;
provision_betrag = schaltungData.regel_verkaeufer_provision_betrag;
provision_beschreibung = schaltungData.regel_verkaeufer_provision_beschreibung;
quelle = 'Tarif-spezifische Verkäufer-Regel';
if (rule.provision_typ === 'prozent') {
const basis = num(rule.basis_euro);
return (num(rule.betrag) / 100) * basis;
}
// Priority 3: Global provider rule employee commission
else if (schaltungData.global_verkaeufer_provision_typ && schaltungData.global_verkaeufer_provision_betrag) {
provision_typ = schaltungData.global_verkaeufer_provision_typ;
provision_betrag = schaltungData.global_verkaeufer_provision_betrag;
provision_beschreibung = schaltungData.global_verkaeufer_provision_beschreibung;
quelle = 'Globale Anbieter-Verkäufer-Regel';
return 0;
}
function applyEmployeeRule(rule, shopProvision) {
if (!rule) return 0;
if (rule.verkaeufer_provision_typ === 'fix') {
return num(rule.verkaeufer_provision_betrag);
}
if (rule.verkaeufer_provision_typ === 'prozent') {
return (num(rule.verkaeufer_provision_betrag) / 100) * shopProvision;
}
return 0;
}
function sumTarifoptionen(tarifoptionen) {
if (!Array.isArray(tarifoptionen)) return { sum: 0, names: [] };
let sum = 0;
const names = [];
for (const opt of tarifoptionen) {
const v = num(opt.provision_euro);
if (v !== 0) {
sum += v;
names.push(opt.name);
}
}
return { sum, names };
}
// Main entry. Inputs are plain data (already loaded from DB by the route).
// `schaltung` is the schaltungen row (joined with tarif basics).
// `tarif` is the full tarif row.
// `tarifRule` is the active provisionsregeln row (or null).
// `anbieterRule` is the active anbieter_provisionsregeln row (or null).
// `tarifoptionen` is an array of tarifoption rows linked to this schaltung.
// `mitarbeiterProzentsatz` is a number (0-100) — used only when there is no
// employee-specific rule and the tariff defines mitarbeiter_provision.
function calculate({ schaltung, tarif, tarifRule, anbieterRule, tarifoptionen, mitarbeiterProzentsatz }) {
const picked = pickRule({ tarifRule, anbieterRule, tarif });
const ruleSource = picked ? picked.source : 'Keine Shop-Provision definiert';
const rule = picked ? picked.rule : null;
let shopProvision = applyShopRule(rule);
const { sum: tarifoptionenSum, names: tarifoptionenNames } = sumTarifoptionen(tarifoptionen);
shopProvision += tarifoptionenSum;
let hardwareGewinn = 0;
if (schaltung && schaltung.hardware && String(schaltung.hardware).trim() !== '') {
hardwareGewinn = num(schaltung.kundenverkaufspreis_netto) - num(schaltung.hardware_ek);
shopProvision += hardwareGewinn;
}
// Calculate employee commission
if (provision_typ && provision_betrag) {
if (provision_typ === 'fix') {
berechnete_provision = parseFloat(provision_betrag);
} else if (provision_typ === 'prozent') {
// If percentage, calculate based on shop commission
berechnete_provision = (parseFloat(provision_betrag) / 100) * shopProvision;
let employeeProvision = applyEmployeeRule(rule, shopProvision);
let employeeSource = picked ? `${picked.source} (Verkäufer)` : 'Keine Mitarbeiter-Provision definiert';
// Fallback: if no rule defines an employee commission, use the per-anbieter
// mitarbeiter_prozentsatz against the computed shop commission.
if (employeeProvision === 0 && (!rule || !rule.verkaeufer_provision_typ)) {
const p = num(mitarbeiterProzentsatz);
if (p !== 0) {
employeeProvision = (p / 100) * shopProvision;
employeeSource = `${p}% Mitarbeiter-Anteil von ${shopProvision.toFixed(2)}€`;
}
}
return {
typ: provision_typ,
betrag: provision_betrag,
beschreibung: provision_beschreibung,
berechnete_provision: berechnete_provision,
quelle: quelle
shop: {
betrag: round2(shopProvision),
quelle: ruleSource,
typ: rule ? rule.provision_typ : null,
regel_betrag: rule ? num(rule.betrag) : null,
basis_euro: rule ? (rule.basis_euro != null ? num(rule.basis_euro) : null) : null,
beschreibung: rule ? rule.beschreibung : null,
},
mitarbeiter: {
betrag: round2(employeeProvision),
quelle: employeeSource,
typ: rule ? rule.verkaeufer_provision_typ : null,
regel_betrag: rule ? (rule.verkaeufer_provision_betrag != null ? num(rule.verkaeufer_provision_betrag) : null) : null,
beschreibung: rule ? rule.verkaeufer_provision_beschreibung : null,
prozentsatz: num(mitarbeiterProzentsatz),
},
tarifoptionen: {
betrag: round2(tarifoptionenSum),
namen: tarifoptionenNames,
},
hardware_gewinn: round2(hardwareGewinn),
};
}
/**
* Main function to calculate all commissions for a schaltung
* @param {Object} schaltungData - Complete schaltung data with tariff and provider info
* @param {Array} tarifoptionen - Selected tariff options
* @returns {Object} Complete commission calculation result
*/
function calculateProvision(schaltungData, tarifoptionen) {
const shopResult = calculateShopProvision(schaltungData, tarifoptionen);
const mitarbeiterResult = calculateMitarbeiterProvision(schaltungData, shopResult.berechnete_provision);
return {
schaltung: {
id: schaltungData.id,
schaltungs_id: schaltungData.schaltungs_id,
tarif: schaltungData.tarif_name,
anbieter: schaltungData.anbieter_name
},
shop_provision: {
typ: shopResult.typ,
betrag: shopResult.betrag,
beschreibung: shopResult.beschreibung,
berechnete_provision: shopResult.berechnete_provision,
quelle: shopResult.quelle
},
mitarbeiter_provision: {
typ: mitarbeiterResult.typ,
betrag: mitarbeiterResult.betrag,
beschreibung: mitarbeiterResult.beschreibung,
berechnete_provision: mitarbeiterResult.berechnete_provision,
quelle: mitarbeiterResult.quelle,
prozentsatz: schaltungData.mitarbeiter_prozentsatz || 0
},
tarifoptionen: tarifoptionen || [],
tarifoptionen_provision: shopResult.tarifoptionen_provision
};
function round2(n) {
return Math.round(n * 100) / 100;
}
module.exports = {
calculateProvision,
calculateShopProvision,
calculateMitarbeiterProvision
};
module.exports = { calculate, num, round2 };