Add VO management, tariff-option assignment, and 2-step schaltung wizard

VOs (Vertriebspartner-Nummern)
- New vos table (one row per VO, scoped to a provider). Migrations
  add tarife.vo_id and schaltungen.vo_id columns (nullable so legacy
  rows survive).
- New /api/vos CRUD (list, create, update, delete with use-checks).
- Admin: new "VOs (Vertriebspartner)" sub-tab. List/create with
  provider dropdown; edit via prompt; delete refuses while used.
- /api/tarife?vo_id=X filter for fetching tariffs of a specific VO.

Tariff editor
- Add-tariff form requires a VO; new dependent VO dropdown that
  populates after the provider is chosen.
- Edit-tariff modal now shows the VO dropdown and a checkbox grid of
  all anbieter-wide tarifoptionen. Saving the dialog applies the
  selection via the existing tarifoptionen_tarife table.
- New GET /api/tarife/:id/tarifoptionen-multi returns the option set
  scoped to the tariff's provider, each annotated with whether it is
  currently assigned to this tariff.
- POST/PUT /api/tarife accept vo_id (required for create, validated
  against the provider) and an optional tarifoption_ids array.

Schaltung wizard
- The Schaltung-erfassen tab is now a 2-step wizard:
  step 1 picks a provider from a button row (mirrors the screenshot
  the user shared); step 2 shows a 2-column form mirroring the
  Aktivierungs-/Vertragsdaten layout.
- Step 2 cascades: VO -> tariffs filtered by VO -> tarifoptionen
  filtered by tariff. Erfasser is autofilled from the logged-in user
  (read-only).
- Removed customer fields that the user does not need (Kundennummer,
  Kennwort/Service-PIN never existed; Rufnummer is now optional both
  in the form and in the API validation).
- After saving, the wizard resets to step 1 ready for the next entry.

Schema
- tarife: vo_id added.
- schaltungen: vo_id added; rufnummer is nullable in new DBs.
  Existing DBs may still have NOT NULL on rufnummer; the schaltungen
  route now sends an empty string instead of NULL to remain
  compatible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kerimatilganandClaude Opus 4.7 committed 2026-05-15 16:36:22 +02:00
1 parent ea3a3fc12c
commit f2ab23f261
7 files changed
+736 -180

No files matched your search

+22 -2
View File
@@ -74,19 +74,35 @@ function initDatabase() {
UNIQUE(anbieter_id, gueltig_ab)
)`);
// Vertriebspartner-Nummern (VOs) per Anbieter. Each tariff is assigned to
// exactly one VO (nullable for legacy rows that pre-date this column).
db.run(`CREATE TABLE IF NOT EXISTS vos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
anbieter_id INTEGER NOT NULL,
nummer TEXT NOT NULL,
bezeichnung TEXT,
aktiv INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (anbieter_id) REFERENCES anbieter (id),
UNIQUE(anbieter_id, nummer)
)`);
// Tarife
db.run(`CREATE TABLE IF NOT EXISTS tarife (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
anbieter_id INTEGER,
vo_id INTEGER,
provision_euro DECIMAL(10,2) DEFAULT 0,
mitarbeiter_provision DECIMAL(10,2) DEFAULT 0,
beschreibung TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (anbieter_id) REFERENCES anbieter (id),
FOREIGN KEY (vo_id) REFERENCES vos (id),
UNIQUE(name, anbieter_id)
)`);
addColumnIfMissing(db, 'tarife', 'mitarbeiter_provision DECIMAL(10,2) DEFAULT 0');
addColumnIfMissing(db, 'tarife', 'vo_id INTEGER');
// Tariff-specific commission rules. basis_euro: base amount for percent calculation.
db.run(`CREATE TABLE IF NOT EXISTS provisionsregeln (
@@ -124,7 +140,9 @@ function initDatabase() {
)`);
addColumnIfMissing(db, 'anbieter_provisionsregeln', 'basis_euro DECIMAL(10,2)');
// Schaltungen
// Schaltungen. rufnummer is nullable on new installs (the application
// also accepts NULL on existing DBs with NOT NULL columns since we just
// pass empty string when missing). vo_id captures which VO was used.
db.run(`CREATE TABLE IF NOT EXISTS schaltungen (
id INTEGER PRIMARY KEY AUTOINCREMENT,
schaltungs_id TEXT NOT NULL UNIQUE,
@@ -133,8 +151,9 @@ function initDatabase() {
vorname TEXT NOT NULL,
nachname TEXT NOT NULL,
firma TEXT,
rufnummer TEXT NOT NULL,
rufnummer TEXT,
anbieter_id INTEGER NOT NULL,
vo_id INTEGER,
tarif_id INTEGER NOT NULL,
hardware TEXT,
hardware_ek DECIMAL(10,2),
@@ -145,6 +164,7 @@ function initDatabase() {
)`);
addColumnIfMissing(db, 'schaltungen', 'hardware_ek DECIMAL(10,2)');
addColumnIfMissing(db, 'schaltungen', 'kundenverkaufspreis_netto DECIMAL(10,2)');
addColumnIfMissing(db, 'schaltungen', 'vo_id INTEGER');
// Dokumente (note: ON DELETE CASCADE only applied to new DBs - existing DBs
// handled via explicit DELETE in server.js)
+173 -89
View File
@@ -881,105 +881,130 @@
<button class="nav-tab admin-only" onclick="showTab('users')" style="display:none">Benutzer</button>
</div>
<!-- Schaltung erfassen Tab -->
<!-- Schaltung erfassen Tab (2-step wizard) -->
<div id="schaltung" class="tab-content active">
<h2>Neue Schaltung erfassen</h2>
<form id="schaltungForm">
<div class="form-row">
<div class="form-group">
<label for="schaltungsId">Schaltungs-ID <span class="required">*</span></label>
<input type="text" id="schaltungsId" name="schaltungs_id" required>
</div>
<div class="form-group">
<label for="eingabeDatum">Eingabe-Datum <span class="required">*</span></label>
<input type="date" id="eingabeDatum" name="eingabe_datum" required>
</div>
<!-- Step 1: Anbieter wählen -->
<div id="wizardStep1">
<h2>Neue Schaltung — Schritt 1 von 2</h2>
<p style="color:#666; margin-bottom:20px;">Wählen Sie einen Anbieter.</p>
<div id="wizardAnbieterButtons" style="display:flex; flex-wrap:wrap; gap:10px;"></div>
</div>
<!-- Step 2: VO + Tarif + Tarifoptionen + Kundendaten -->
<div id="wizardStep2" style="display:none;">
<div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;">
<h2 style="margin:0;">Neue Schaltung — Schritt 2 von 2 <small id="wizardAnbieterLabel" style="color:#3498db; font-weight:normal;"></small></h2>
<button type="button" onclick="wizardBackToStep1()" style="padding:6px 12px;">&larr; Anbieter ändern</button>
</div>
<div class="form-group">
<label for="schaltungsDatum">Schaltungs-/Aktivierungsdatum <span class="required">*</span></label>
<input type="date" id="schaltungsDatum" name="schaltungs_datum" required>
</div>
<form id="schaltungForm">
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:30px;">
<!-- Linke Spalte: Aktivierungsdaten -->
<div>
<h3 style="margin-top:0; margin-bottom:15px;">Aktivierungsdaten</h3>
<div class="form-row-thirds">
<div class="form-group">
<label for="vorname">Vorname <span class="required">*</span></label>
<input type="text" id="vorname" name="vorname" required>
</div>
<div class="form-group">
<label for="nachname">Nachname <span class="required">*</span></label>
<input type="text" id="nachname" name="nachname" required>
</div>
<div class="form-group">
<label for="firma">Firma (optional)</label>
<input type="text" id="firma" name="firma">
</div>
</div>
<div class="form-group">
<label for="wizardVo">VO-Auswahl <span class="required">*</span></label>
<select id="wizardVo" required onchange="loadTarifeForWizard()">
<option value="">VO wählen...</option>
</select>
</div>
<div class="form-group">
<label for="rufnummer">Rufnummer/Kundennummer <span class="required">*</span></label>
<input type="text" id="rufnummer" name="rufnummer" required>
</div>
<div class="form-group">
<label for="wizardTarif">Tarif <span class="required">*</span></label>
<select id="wizardTarif" name="tarif_id" required onchange="loadTarifoptionenForWizard()">
<option value="">Erst VO wählen...</option>
</select>
</div>
<div class="form-row">
<div class="form-group">
<label for="anbieter">Anbieter <span class="required">*</span></label>
<select id="anbieter" name="anbieter_id" required onchange="loadTarife()">
<option value="">Bitte wählen...</option>
</select>
</div>
<div class="form-group">
<label for="tarif">Tarif <span class="required">*</span></label>
<select id="tarif" name="tarif_id" required onchange="loadTarifoptionen()">
<option value="">Erst Anbieter wählen...</option>
</select>
</div>
</div>
<div class="form-group" id="tarifoptionenSection" style="display:none;">
<label>Tarifoptionen</label>
<div id="tarifoptionenList" style="display:grid; grid-template-columns:repeat(auto-fit, minmax(220px, 1fr)); gap:8px; margin-top:8px;"></div>
<div id="noTarifoptionen" style="display:none; color:#666; font-style:italic; margin-top:8px;">Keine Tarifoptionen verfügbar</div>
</div>
<!-- Tarifoptionen/Aktionscodes -->
<div class="form-group" id="tarifoptionenSection" style="display: none;">
<label>Tarifoptionen/Aktionscodes (optional)</label>
<div id="tarifoptionenList" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 10px; margin-top: 10px;">
<!-- Optionen werden hier dynamisch eingefügt -->
</div>
<div id="noTarifoptionen" style="display: none; color: #666; font-style: italic; margin-top: 10px;">
Keine Tarifoptionen für diesen Tarif verfügbar
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="eingabeDatum">Erfassung <span class="required">*</span></label>
<input type="date" id="eingabeDatum" name="eingabe_datum" required>
</div>
<div class="form-group">
<label for="schaltungsDatum">Vertragsbeginn <span class="required">*</span></label>
<input type="date" id="schaltungsDatum" name="schaltungs_datum" required>
</div>
</div>
<div class="form-group">
<label for="hardware">Hardware (optional)</label>
<input type="text" id="hardware" name="hardware"
title="Hardware optional" onchange="toggleHardwarePricing()">
</div>
<!-- Hardware Pricing Fields -->
<div id="hardwarePricingFields" style="display: none;">
<div class="form-row">
<div class="form-group">
<label for="hardwareEk">Hardware-EK (Einkaufspreis) <span class="required">*</span></label>
<input type="number" id="hardwareEk" name="hardware_ek" step="0.01" min="0"
placeholder="0.00" title="Hardware-Einkaufspreis in Euro">
<div class="form-group">
<label>Erfasser</label>
<input type="text" id="wizardErfasser" readonly style="background:#f5f5f5;">
</div>
</div>
<div class="form-group">
<label for="kundenverkaufspreis">Kundenverkaufspreis (netto) <span class="required">*</span></label>
<input type="number" id="kundenverkaufspreis" name="kundenverkaufspreis_netto" step="0.01" min="0"
placeholder="0.00" title="Kundenverkaufspreis netto in Euro">
<!-- Rechte Spalte: Vertrags-/Kundendaten -->
<div>
<h3 style="margin-top:0; margin-bottom:15px;">Vertragsdaten</h3>
<div class="form-group">
<label for="schaltungsId">Schaltungs-ID <span class="required">*</span></label>
<input type="text" id="schaltungsId" name="schaltungs_id" required>
</div>
<div class="form-row-thirds">
<div class="form-group">
<label for="firma">Firma (optional)</label>
<input type="text" id="firma" name="firma">
</div>
<div class="form-group">
<label for="vorname">Vorname <span class="required">*</span></label>
<input type="text" id="vorname" name="vorname" required>
</div>
<div class="form-group">
<label for="nachname">Nachname <span class="required">*</span></label>
<input type="text" id="nachname" name="nachname" required>
</div>
</div>
<div class="form-group">
<label for="rufnummer">Rufnummer (optional)</label>
<input type="text" id="rufnummer" name="rufnummer">
</div>
<div class="form-group">
<label for="hardware">Hardware (optional, 15 Zeichen)</label>
<input type="text" id="hardware" name="hardware" onchange="toggleHardwarePricing()">
</div>
<div id="hardwarePricingFields" style="display:none;">
<div class="form-row">
<div class="form-group">
<label for="hardwareEk">Hardware-EK</label>
<input type="number" id="hardwareEk" name="hardware_ek" step="0.01" min="0" placeholder="0.00">
</div>
<div class="form-group">
<label for="kundenverkaufspreis">Kundenverkaufspreis</label>
<input type="number" id="kundenverkaufspreis" name="kundenverkaufspreis_netto" step="0.01" min="0" placeholder="0.00">
</div>
</div>
</div>
<div class="form-group">
<label>Dokumente hochladen</label>
<div class="file-upload-area" id="fileUploadArea">
<p>Dateien hier hineinziehen oder klicken zum Auswählen</p>
<input type="file" id="documentUpload" multiple accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" style="display:none;">
</div>
<div id="uploadedFiles" class="documents-list"></div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label>Dokumente hochladen</label>
<div class="file-upload-area" id="fileUploadArea">
<p>Dateien hier hineinziehen oder klicken zum Auswählen</p>
<input type="file" id="documentUpload" multiple accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" style="display: none;">
<input type="hidden" id="anbieter" name="anbieter_id">
<div style="margin-top:25px;">
<button type="submit" class="btn-success">Schaltung speichern</button>
</div>
<div id="uploadedFiles" class="documents-list"></div>
</div>
<button type="submit" class="btn-success">Schaltung speichern</button>
</form>
</form>
</div>
</div>
<!-- Übersicht Tab -->
@@ -1158,6 +1183,10 @@
<span class="admin-icon">🏢</span>
<span>Anbieter</span>
</button>
<button class="admin-cat-btn" onclick="showAdminCategory('vos')">
<span class="admin-icon">🔢</span>
<span>VOs (Vertriebspartner)</span>
</button>
<button class="admin-cat-btn" onclick="showAdminCategory('tarife')">
<span class="admin-icon">📋</span>
<span>Tarife</span>
@@ -1222,6 +1251,46 @@
</div>
</div>
<!-- VOs Management -->
<div id="admin-vos" class="admin-category">
<div class="admin-page">
<div class="admin-header">
<h3>VOs (Vertriebspartner-Nummern) verwalten</h3>
<p>Pro Anbieter können beliebig viele VOs angelegt werden. Jeder Tarif wird genau einer VO zugeordnet.</p>
</div>
<div class="admin-form-section">
<h4>Neue VO hinzufügen</h4>
<div class="add-form">
<select id="voAnbieter" style="margin-right:8px;">
<option value="">Anbieter wählen...</option>
</select>
<input type="text" id="voNummer" placeholder="VO-Nummer (z.B. 27518900)" style="margin-right:8px;">
<input type="text" id="voBezeichnung" placeholder="Bezeichnung (z.B. Fachhandel)" style="margin-right:8px;">
<button onclick="addVo()" class="btn-success">Hinzufügen</button>
</div>
</div>
<div class="admin-content-section">
<h4>Bestehende VOs</h4>
<div class="table-container">
<table class="admin-table">
<thead>
<tr>
<th>Anbieter</th>
<th>Nummer</th>
<th>Bezeichnung</th>
<th>Aktiv</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody id="vosList"></tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Tarife Management -->
<div id="admin-tarife" class="admin-category">
<div class="admin-page">
@@ -1234,9 +1303,12 @@
<h4>Neuen Tarif hinzufügen</h4>
<div class="tarif-form">
<div class="form-row">
<select id="tarifAnbieter">
<select id="tarifAnbieter" onchange="loadVosForTarifForm()">
<option value="">Anbieter wählen...</option>
</select>
<select id="tarifVo">
<option value="">VO wählen...</option>
</select>
<input type="text" id="newTarif" placeholder="Name des Tarifs">
</div>
<div class="form-row">
@@ -1259,6 +1331,7 @@
<tr>
<th>ID</th>
<th>Anbieter</th>
<th>VO</th>
<th>Tarif-Name</th>
<th>Provision (€)</th>
<th>Beschreibung</th>
@@ -1572,7 +1645,7 @@
<!-- Edit Tariff Modal -->
<div id="editTariffModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; width: 500px; max-width: 90%;">
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; width: 600px; max-width: 90%; max-height: 90vh; overflow-y: auto;">
<h3>Tarif bearbeiten</h3>
<form id="editTariffForm">
<input type="hidden" id="editTariffId">
@@ -1580,11 +1653,22 @@
<label>Tarif-Name:</label>
<input type="text" id="editTariffName" required>
</div>
<div class="form-group">
<label>VO:</label>
<select id="editTariffVo">
<option value="">VO wählen...</option>
</select>
</div>
<div class="form-group">
<label>Shop-Provision (€):</label>
<input type="number" id="editTariffProvisionBetrag" step="0.01" min="0" placeholder="Betrag in Euro">
</div>
<div class="form-group">
<label>Tarifoptionen (Anbieter-weit):</label>
<div id="editTariffOptionenContainer" style="border:1px solid #ddd; border-radius:6px; padding:10px; max-height:200px; overflow-y:auto; background:#fafafa;">
<small style="color:#666;">Keine Tarifoptionen für diesen Anbieter vorhanden</small>
</div>
</div>
<div style="display: flex; gap: 10px; margin-top: 20px;">
<button type="submit" class="btn-success">Speichern</button>
+321 -58
View File
@@ -34,18 +34,129 @@ document.addEventListener('DOMContentLoaded', async function() {
loadAnbieter();
loadSchaltungen();
setupFileUpload();
renderWizardAnbieterButtons();
// Set today's date as default
const today = new Date().toISOString().split('T')[0];
document.getElementById('eingabeDatum').value = today;
document.getElementById('schaltungsDatum').value = today;
// Erfasser autofill
const erfasser = document.getElementById('wizardErfasser');
if (erfasser) erfasser.value = currentUser.displayName || currentUser.username;
// Setup form submission
document.getElementById('schaltungForm').addEventListener('submit', handleSchaltungSubmit);
// Load all data in background for faster tab switching
preloadAllData();
});
// --- Schaltung Wizard ---
async function renderWizardAnbieterButtons() {
const container = document.getElementById('wizardAnbieterButtons');
if (!container) return;
container.innerHTML = '<div style="color:#666;">Lade...</div>';
try {
const anbieter = await apiRequest('/api/anbieter');
container.innerHTML = '';
if (!anbieter.length) {
container.innerHTML = '<div style="color:#666;">Keine Anbieter vorhanden. Bitte zuerst unter Administration einen Anbieter anlegen.</div>';
return;
}
anbieter.forEach(a => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'btn-success';
btn.style.cssText = 'padding:14px 22px; font-size:15px; min-width:140px;';
btn.textContent = a.name;
btn.addEventListener('click', () => wizardSelectAnbieter(a.id, a.name));
container.appendChild(btn);
});
} catch (e) {
container.innerHTML = '<div style="color:#c0392b;">Fehler beim Laden der Anbieter</div>';
}
}
async function wizardSelectAnbieter(anbieterId, anbieterName) {
document.getElementById('anbieter').value = anbieterId;
document.getElementById('wizardAnbieterLabel').textContent = '· ' + anbieterName;
document.getElementById('wizardStep1').style.display = 'none';
document.getElementById('wizardStep2').style.display = 'block';
// Load VOs for this provider
const voSelect = document.getElementById('wizardVo');
voSelect.innerHTML = '<option value="">VO wählen...</option>';
try {
const vos = await apiRequest(`/api/vos?anbieter_id=${encodeURIComponent(anbieterId)}`);
vos.forEach(v => {
const label = `${v.nummer}${v.bezeichnung ? ' (' + v.bezeichnung + ')' : ''}`;
voSelect.innerHTML += `<option value="${v.id}">${escapeHtml(label)}</option>`;
});
if (vos.length === 0) {
showMessage('Für diesen Anbieter wurden noch keine VOs angelegt. Bitte in der Administration → VOs eine VO anlegen.', 'error');
}
} catch (e) { /* error shown */ }
// Reset Tarif + Tarifoptionen
document.getElementById('wizardTarif').innerHTML = '<option value="">Erst VO wählen...</option>';
document.getElementById('tarifoptionenSection').style.display = 'none';
}
function wizardBackToStep1() {
document.getElementById('wizardStep2').style.display = 'none';
document.getElementById('wizardStep1').style.display = 'block';
}
async function loadTarifeForWizard() {
const voId = document.getElementById('wizardVo').value;
const tarifSelect = document.getElementById('wizardTarif');
tarifSelect.innerHTML = '<option value="">Tarif wählen...</option>';
document.getElementById('tarifoptionenSection').style.display = 'none';
if (!voId) return;
try {
const tarife = await apiRequest(`/api/tarife?vo_id=${encodeURIComponent(voId)}`);
tarife.forEach(t => {
tarifSelect.innerHTML += `<option value="${t.id}">${escapeHtml(t.name)}</option>`;
});
} catch (e) { /* error shown */ }
}
async function loadTarifoptionenForWizard() {
const tarifId = document.getElementById('wizardTarif').value;
const section = document.getElementById('tarifoptionenSection');
const list = document.getElementById('tarifoptionenList');
const noOptions = document.getElementById('noTarifoptionen');
list.innerHTML = '';
noOptions.style.display = 'none';
if (!tarifId) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
try {
const options = await apiRequest(`/api/tarife/${tarifId}/tarifoptionen`);
if (!options || options.length === 0) {
noOptions.style.display = 'block';
return;
}
options.forEach(opt => {
const wrapper = document.createElement('label');
wrapper.style.cssText = 'display:flex; align-items:flex-start; gap:8px; padding:8px; border:1px solid #ddd; border-radius:5px; background:#f9f9f9; cursor:pointer;';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.name = 'tarifoptionen';
cb.value = opt.id;
wrapper.appendChild(cb);
const text = document.createElement('div');
const price = (opt.provision_euro >= 0 ? '+' : '') + opt.provision_euro + '€';
text.innerHTML = `<div style="font-weight:bold;">${escapeHtml(opt.name)} <span style="color:#666; font-weight:normal;">(${escapeHtml(price)})</span></div>
${opt.code ? `<div style="font-size:0.85em; color:#666;">Code: ${escapeHtml(opt.code)}</div>` : ''}
${opt.beschreibung ? `<div style="font-size:0.85em; color:#555;">${escapeHtml(opt.beschreibung)}</div>` : ''}`;
wrapper.appendChild(text);
list.appendChild(wrapper);
});
} catch (e) { /* error shown */ }
}
function renderUserBadge() {
if (!currentUser) return;
// Show admin-only navigation elements (e.g. the Benutzer tab) once we know the role.
@@ -273,18 +384,17 @@ async function loadAnbieter() {
try {
const anbieter = await apiRequest('/api/anbieter');
const anbieterSelect = document.getElementById('anbieter');
// Note: #anbieter is now a hidden input populated by the wizard;
// we keep the helper only for selects that still exist (admin form).
const tarifAnbieterSelect = document.getElementById('tarifAnbieter');
// Clear existing options
anbieterSelect.innerHTML = '<option value="">Bitte wählen...</option>';
tarifAnbieterSelect.innerHTML = '<option value="">Anbieter wählen...</option>';
anbieter.forEach(a => {
anbieterSelect.innerHTML += `<option value="${a.id}">${escapeHtml(a.name)}</option>`;
tarifAnbieterSelect.innerHTML += `<option value="${a.id}">${escapeHtml(a.name)}</option>`;
});
if (tarifAnbieterSelect) {
tarifAnbieterSelect.innerHTML = '<option value="">Anbieter wählen...</option>';
anbieter.forEach(a => {
tarifAnbieterSelect.innerHTML += `<option value="${a.id}">${escapeHtml(a.name)}</option>`;
});
}
// Refresh wizard buttons in case anbieters changed
renderWizardAnbieterButtons();
} catch (error) {
console.error('Fehler beim Laden der Anbieter:', error);
}
@@ -385,11 +495,15 @@ async function handleSchaltungSubmit(e) {
const formData = new FormData(e.target);
const schaltungData = Object.fromEntries(formData.entries());
// Collect selected tarifoptionen
// Wizard fields not part of FormData (hidden input has it but vo is on a non-named select).
schaltungData.vo_id = document.getElementById('wizardVo').value || null;
const selectedTarifoptionen = Array.from(document.querySelectorAll('input[name="tarifoptionen"]:checked'))
.map(checkbox => parseInt(checkbox.value));
if (selectedTarifoptionen.length) {
schaltungData.tarifoptionen = selectedTarifoptionen;
}
// Validate hardware length if provided
if (schaltungData.hardware && schaltungData.hardware.length !== 15) {
showMessage('Hardware muss genau 15 Zeichen haben (oder leer lassen)', 'error');
return;
@@ -398,36 +512,34 @@ async function handleSchaltungSubmit(e) {
try {
const response = await apiRequest('/api/schaltungen', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(schaltungData)
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(schaltungData),
});
currentSchaltungId = response.id;
// Add selected tarifoptionen to the schaltung
if (selectedTarifoptionen.length > 0) {
await addTarifoptionenToSchaltung(currentSchaltungId, selectedTarifoptionen);
}
// Upload files if any
if (uploadedFiles.length > 0) {
await uploadDocuments(currentSchaltungId);
}
showMessage('Schaltung erfolgreich gespeichert!');
// Reset form
e.target.reset();
uploadedFiles = [];
document.getElementById('uploadedFiles').innerHTML = '';
hideTarifoptionen(); // Hide tarifoptionen section
hideTarifoptionen();
const today = new Date().toISOString().split('T')[0];
document.getElementById('eingabeDatum').value = today;
document.getElementById('schaltungsDatum').value = today;
// Erfasser wieder befüllen (reset löscht's nicht da readonly, aber safety)
const erfasser = document.getElementById('wizardErfasser');
if (erfasser) erfasser.value = currentUser.displayName || currentUser.username;
// Zurück zu Schritt 1 für die nächste Schaltung
wizardBackToStep1();
// Reload overview and provisions if needed
await refreshDataAfterSchaltungChange();
} catch (error) {
@@ -824,6 +936,10 @@ function showAdminCategory(category) {
case 'anbieter':
loadAnbieterAdmin();
break;
case 'vos':
loadVosAdmin();
loadAnbieterForVoForm();
break;
case 'tarife':
loadTarifeAdmin();
loadAnbieterForTarife();
@@ -897,17 +1013,21 @@ async function loadTarifeAdmin() {
tbody.innerHTML = '';
if (tarife.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #666;">Keine Tarife vorhanden</td></tr>';
tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #666;">Keine Tarife vorhanden</td></tr>';
return;
}
tarife.forEach(t => {
const provision = `${(t.provision_euro || 0).toFixed(2).replace('.', ',')}€`;
const voLabel = t.vo_nummer
? `${t.vo_nummer}${t.vo_bezeichnung ? ' (' + t.vo_bezeichnung + ')' : ''}`
: '—';
const tr = document.createElement('tr');
tr.id = `tarif-item-${t.id}`;
tr.innerHTML = `
<td>${t.id}</td>
<td>${escapeHtml(t.anbieter_name || 'Unbekannt')}</td>
<td>${escapeHtml(voLabel)}</td>
<td>${escapeHtml(t.name)}</td>
<td>${escapeHtml(provision)}</td>
<td>${escapeHtml(t.beschreibung || '-')}</td>
@@ -930,7 +1050,7 @@ async function loadTarifeAdmin() {
} catch (error) {
console.error('Fehler beim Laden der Tarif-Administration:', error);
const tbody = document.getElementById('tarifeList');
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #666;">Fehler beim Laden der Daten</td></tr>';
tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #666;">Fehler beim Laden der Daten</td></tr>';
} finally {
isLoadingTarifeAdmin = false;
}
@@ -1013,6 +1133,7 @@ async function loadTarifoptionAnbieter() {
async function addTarif() {
const name = document.getElementById('newTarif').value.trim();
const anbieterId = document.getElementById('tarifAnbieter').value;
const voId = document.getElementById('tarifVo').value;
const provisionEuro = document.getElementById('tarifProvisionBetrag').value;
const beschreibung = document.getElementById('tarifBeschreibung').value.trim();
@@ -1020,8 +1141,11 @@ async function addTarif() {
showMessage('Bitte Tarif-Name und Anbieter auswählen', 'error');
return;
}
if (!voId) {
showMessage('Bitte VO auswählen', 'error');
return;
}
// Validation for provision euro
if (provisionEuro && parseFloat(provisionEuro) < 0) {
showMessage('Provision kann nicht negativ sein', 'error');
return;
@@ -1031,36 +1155,47 @@ async function addTarif() {
const requestData = {
name,
anbieter_id: anbieterId,
vo_id: voId,
provision_euro: provisionEuro ? parseFloat(provisionEuro) : 0,
beschreibung: beschreibung || null
beschreibung: beschreibung || null,
};
await apiRequest('/api/tarife', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData),
});
// Reset form
document.getElementById('newTarif').value = '';
document.getElementById('tarifAnbieter').value = '';
document.getElementById('tarifVo').innerHTML = '<option value="">VO wählen...</option>';
document.getElementById('tarifProvisionBetrag').value = '';
document.getElementById('tarifBeschreibung').value = '';
showMessage('Tarif erfolgreich hinzugefügt');
// Reload data
await loadTarifeAdmin();
await loadTarifeForProvision();
} catch (error) {
console.error('Fehler beim Hinzufügen des Tarifs:', error);
showMessage('Fehler beim Hinzufügen des Tarifs', 'error');
}
}
// Populates the VO dropdown in the add-tariff form based on the selected provider.
async function loadVosForTarifForm() {
const anbieterId = document.getElementById('tarifAnbieter').value;
const select = document.getElementById('tarifVo');
select.innerHTML = '<option value="">VO wählen...</option>';
if (!anbieterId) return;
try {
const vos = await apiRequest(`/api/vos?anbieter_id=${encodeURIComponent(anbieterId)}`);
vos.forEach(v => {
const label = `${v.nummer}${v.bezeichnung ? ' (' + v.bezeichnung + ')' : ''}`;
select.innerHTML += `<option value="${v.id}">${escapeHtml(label)}</option>`;
});
} catch (e) { /* error already shown */ }
}
// Commission management functions
async function loadProvisionen() {
@@ -1412,46 +1547,74 @@ function closeModal(modalId) {
// Tariff Edit/Delete Functions
async function editTariff(id) {
try {
// Get all tariffs from the provider
const anbieter = await apiRequest('/api/anbieter');
let tariff = null;
for (const a of anbieter) {
const tarife = await apiRequest(`/api/tarife/${a.id}`);
tariff = tarife.find(t => t.id == id);
if (tariff) break;
}
const tariff = await apiRequest(`/api/tarif/${id}`);
if (!tariff) {
showMessage('Tarif nicht gefunden', 'error');
return;
}
// Fill modal with tariff data
document.getElementById('editTariffId').value = tariff.id;
document.getElementById('editTariffName').value = tariff.name;
document.getElementById('editTariffProvisionBetrag').value = tariff.provision_euro || '';
// Populate VO dropdown with the tariff's provider VOs and preselect.
const voSelect = document.getElementById('editTariffVo');
voSelect.innerHTML = '<option value="">VO wählen...</option>';
const vos = await apiRequest(`/api/vos?anbieter_id=${tariff.anbieter_id}`);
vos.forEach(v => {
const label = `${v.nummer}${v.bezeichnung ? ' (' + v.bezeichnung + ')' : ''}`;
const opt = document.createElement('option');
opt.value = v.id;
opt.textContent = label;
if (tariff.vo_id == v.id) opt.selected = true;
voSelect.appendChild(opt);
});
// Populate tarifoptionen checkbox grid (anbieter-wide options, with assigned flag)
const container = document.getElementById('editTariffOptionenContainer');
container.innerHTML = '';
const options = await apiRequest(`/api/tarife/${id}/tarifoptionen-multi`);
if (!options || options.length === 0) {
container.innerHTML = '<small style="color:#666;">Keine Tarifoptionen für diesen Anbieter vorhanden</small>';
} else {
options.forEach(o => {
const wrapper = document.createElement('label');
wrapper.style.cssText = 'display:flex; align-items:center; gap:8px; padding:4px 0; cursor:pointer;';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.value = o.id;
cb.checked = !!o.assigned;
cb.className = 'edit-tariff-option-checkbox';
wrapper.appendChild(cb);
const span = document.createElement('span');
const price = (o.provision_euro >= 0 ? '+' : '') + o.provision_euro + '€';
span.textContent = `${o.name}${o.code ? ' [' + o.code + ']' : ''} (${price})`;
wrapper.appendChild(span);
container.appendChild(wrapper);
});
}
// Show modal
document.getElementById('editTariffModal').style.display = 'block';
// Setup form submission
document.getElementById('editTariffForm').onsubmit = async (e) => {
e.preventDefault();
const checked = Array.from(container.querySelectorAll('.edit-tariff-option-checkbox:checked'))
.map(cb => parseInt(cb.value, 10));
const formData = {
name: document.getElementById('editTariffName').value.trim(),
provision_euro: document.getElementById('editTariffProvisionBetrag').value ? parseFloat(document.getElementById('editTariffProvisionBetrag').value) : 0
vo_id: document.getElementById('editTariffVo').value || null,
provision_euro: document.getElementById('editTariffProvisionBetrag').value
? parseFloat(document.getElementById('editTariffProvisionBetrag').value)
: 0,
tarifoption_ids: checked,
};
try {
await apiRequest(`/api/tarife/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
body: JSON.stringify(formData),
});
closeModal('editTariffModal');
showMessage('Tarif erfolgreich aktualisiert');
await loadTarifeAdmin();
@@ -1460,7 +1623,6 @@ async function editTariff(id) {
console.error('Fehler beim Aktualisieren des Tarifs:', error);
}
};
} catch (error) {
console.error('Fehler beim Laden der Tarif-Daten:', error);
}
@@ -3885,3 +4047,104 @@ async function deleteUser(uuid, username) {
// apiRequest already shows the error message
}
}
// ============================================================================
// VO-Verwaltung (Vertriebspartner-Nummern). Backend: /api/vos
// ============================================================================
async function loadAnbieterForVoForm() {
try {
const anbieter = await apiRequest('/api/anbieter');
const select = document.getElementById('voAnbieter');
if (!select) return;
select.innerHTML = '<option value="">Anbieter wählen...</option>';
anbieter.forEach(a => {
select.innerHTML += `<option value="${a.id}">${escapeHtml(a.name)}</option>`;
});
} catch (e) { /* error already shown */ }
}
async function loadVosAdmin() {
const tbody = document.getElementById('vosList');
if (!tbody) return;
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#666;">Lade...</td></tr>';
try {
const vos = await apiRequest('/api/vos');
tbody.innerHTML = '';
if (!vos.length) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#666;">Keine VOs vorhanden</td></tr>';
return;
}
vos.forEach(v => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${escapeHtml(v.anbieter_name)}</td>
<td>${escapeHtml(v.nummer)}</td>
<td>${escapeHtml(v.bezeichnung || '')}</td>
<td>${v.aktiv ? '<span style="color:#27ae60;">Ja</span>' : '<span style="color:#c0392b;">Nein</span>'}</td>
<td>
<button data-vo-action="edit" data-id="${v.id}" data-nummer="${escapeHtml(v.nummer)}" data-bezeichnung="${escapeHtml(v.bezeichnung || '')}" data-aktiv="${v.aktiv}" class="btn-success" style="margin-right:5px;">Bearbeiten</button>
<button data-vo-action="delete" data-id="${v.id}" data-label="${escapeHtml(v.nummer + (v.bezeichnung ? ' (' + v.bezeichnung + ')' : ''))}" class="btn-danger">Löschen</button>
</td>
`;
tr.querySelectorAll('button[data-vo-action]').forEach(btn => {
btn.addEventListener('click', () => {
const action = btn.dataset.voAction;
const id = parseInt(btn.dataset.id, 10);
if (action === 'edit') editVo(id, btn.dataset.nummer, btn.dataset.bezeichnung, btn.dataset.aktiv === '1');
else if (action === 'delete') deleteVo(id, btn.dataset.label);
});
});
tbody.appendChild(tr);
});
} catch (e) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#c0392b;">Fehler beim Laden</td></tr>';
}
}
async function addVo() {
const anbieter_id = document.getElementById('voAnbieter').value;
const nummer = document.getElementById('voNummer').value.trim();
const bezeichnung = document.getElementById('voBezeichnung').value.trim();
if (!anbieter_id || !nummer) {
showMessage('Anbieter und VO-Nummer sind erforderlich', 'error');
return;
}
try {
await apiRequest('/api/vos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ anbieter_id, nummer, bezeichnung }),
});
document.getElementById('voAnbieter').value = '';
document.getElementById('voNummer').value = '';
document.getElementById('voBezeichnung').value = '';
showMessage('VO erfolgreich hinzugefügt');
loadVosAdmin();
} catch (e) { /* already shown */ }
}
async function editVo(id, nummer, bezeichnung, aktiv) {
const newNummer = prompt('VO-Nummer:', nummer);
if (newNummer === null) return;
const newBezeichnung = prompt('Bezeichnung (leer = keine):', bezeichnung || '');
if (newBezeichnung === null) return;
try {
await apiRequest(`/api/vos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nummer: newNummer.trim(), bezeichnung: newBezeichnung.trim() || null }),
});
showMessage('VO aktualisiert');
loadVosAdmin();
} catch (e) { /* already shown */ }
}
async function deleteVo(id, label) {
if (!confirm(`VO "${label}" wirklich löschen?`)) return;
try {
await apiRequest(`/api/vos/${id}`, { method: 'DELETE' });
showMessage('VO gelöscht');
loadVosAdmin();
} catch (e) { /* already shown */ }
}
+29 -16
View File
@@ -18,13 +18,12 @@ function validateAmount(a) {
function validateSchaltungBody(body) {
const { schaltungs_id, eingabe_datum, schaltungs_datum, vorname, nachname,
rufnummer, anbieter_id, tarif_id, hardware, hardware_ek, kundenverkaufspreis_netto } = body || {};
anbieter_id, tarif_id, hardware, hardware_ek, kundenverkaufspreis_netto } = body || {};
if (!schaltungs_id || !schaltungs_id.trim()) return 'Schaltungs-ID ist erforderlich';
if (!validateDate(eingabe_datum)) return 'Ungültiges Eingabe-Datum (Format: YYYY-MM-DD)';
if (!validateDate(schaltungs_datum)) return 'Ungültiges Schaltungs-Datum (Format: YYYY-MM-DD)';
if (!vorname || !vorname.trim()) return 'Vorname ist erforderlich';
if (!nachname || !nachname.trim()) return 'Nachname ist erforderlich';
if (!rufnummer || !rufnummer.trim()) return 'Rufnummer ist erforderlich';
if (!anbieter_id) return 'Anbieter ist erforderlich';
if (!tarif_id) return 'Tarif ist erforderlich';
if (!validateHardware(hardware)) return 'Hardware muss genau 15 Zeichen lang sein';
@@ -51,19 +50,32 @@ router.post('/', asyncHandler(async (req, res) => {
if (err) return res.status(400).json({ error: err });
const b = req.body;
// rufnummer may be empty - existing DBs may have a NOT NULL constraint, so
// we pass an empty string rather than NULL.
const rufnummerValue = b.rufnummer && String(b.rufnummer).trim() ? String(b.rufnummer).trim() : '';
const tarifoptionen = Array.isArray(b.tarifoptionen) ? b.tarifoptionen : [];
try {
const result = await db.run(
`INSERT INTO schaltungen
(schaltungs_id, eingabe_datum, schaltungs_datum, vorname, nachname, firma, rufnummer,
anbieter_id, tarif_id, hardware, hardware_ek, kundenverkaufspreis_netto)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
b.schaltungs_id, b.eingabe_datum, b.schaltungs_datum, b.vorname, b.nachname,
b.firma || null, b.rufnummer, b.anbieter_id, b.tarif_id, b.hardware || null,
b.hardware_ek || null, b.kundenverkaufspreis_netto || null,
]
);
res.json({ id: result.lastID, message: 'Schaltung erfolgreich erstellt' });
const newId = await db.transaction(async () => {
const result = await db.run(
`INSERT INTO schaltungen
(schaltungs_id, eingabe_datum, schaltungs_datum, vorname, nachname, firma, rufnummer,
anbieter_id, vo_id, tarif_id, hardware, hardware_ek, kundenverkaufspreis_netto)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
b.schaltungs_id, b.eingabe_datum, b.schaltungs_datum, b.vorname, b.nachname,
b.firma || null, rufnummerValue, b.anbieter_id, b.vo_id || null, b.tarif_id, b.hardware || null,
b.hardware_ek || null, b.kundenverkaufspreis_netto || null,
]
);
for (const tarifoptionId of tarifoptionen) {
await db.run(
'INSERT OR IGNORE INTO schaltungen_tarifoptionen (schaltung_id, tarifoption_id) VALUES (?, ?)',
[result.lastID, tarifoptionId]
);
}
return result.lastID;
});
res.json({ id: newId, message: 'Schaltung erfolgreich erstellt' });
} catch (e) {
if (/UNIQUE/.test(e.message)) {
return res.status(400).json({ error: 'Schaltungs-ID existiert bereits' });
@@ -79,17 +91,18 @@ router.put('/:id', asyncHandler(async (req, res) => {
const b = req.body;
const tarifoptionen = Array.isArray(b.tarifoptionen) ? b.tarifoptionen : [];
const rufnummerValue = b.rufnummer && String(b.rufnummer).trim() ? String(b.rufnummer).trim() : '';
await db.transaction(async () => {
const upd = await db.run(
`UPDATE schaltungen
SET schaltungs_id = ?, eingabe_datum = ?, schaltungs_datum = ?, vorname = ?, nachname = ?,
firma = ?, rufnummer = ?, anbieter_id = ?, tarif_id = ?, hardware = ?,
firma = ?, rufnummer = ?, anbieter_id = ?, vo_id = ?, tarif_id = ?, hardware = ?,
hardware_ek = ?, kundenverkaufspreis_netto = ?
WHERE id = ?`,
[
b.schaltungs_id, b.eingabe_datum, b.schaltungs_datum, b.vorname, b.nachname,
b.firma || null, b.rufnummer, b.anbieter_id, b.tarif_id, b.hardware || null,
b.firma || null, rufnummerValue, b.anbieter_id, b.vo_id || null, b.tarif_id, b.hardware || null,
b.hardware_ek || null, b.kundenverkaufspreis_netto || null, id,
]
);
+97 -15
View File
@@ -9,23 +9,38 @@ function validateAmount(amount) {
}
router.get('/', asyncHandler(async (req, res) => {
const { vo_id } = req.query;
const params = [];
let where = '';
if (vo_id) {
where = 'WHERE t.vo_id = ?';
params.push(vo_id);
}
const rows = await db.all(
`SELECT t.*, a.name AS anbieter_name
`SELECT t.*, a.name AS anbieter_name, v.nummer AS vo_nummer, v.bezeichnung AS vo_bezeichnung
FROM tarife t
JOIN anbieter a ON t.anbieter_id = a.id
ORDER BY a.name, t.name`
LEFT JOIN vos v ON t.vo_id = v.id
${where}
ORDER BY a.name, t.name`,
params
);
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]);
const rows = await db.all(
`SELECT t.*, v.nummer AS vo_nummer, v.bezeichnung AS vo_bezeichnung
FROM tarife t LEFT JOIN vos v ON t.vo_id = v.id
WHERE t.anbieter_id = ? ORDER BY t.name`,
[anbieter_id]
);
res.json(rows);
}));
router.post('/', asyncHandler(async (req, res) => {
const { name, anbieter_id, provision_euro, beschreibung } = req.body || {};
const { name, anbieter_id, vo_id, provision_euro, beschreibung, tarifoption_ids } = req.body || {};
if (!name || !name.trim()) {
return res.status(400).json({ error: 'Tarifname ist erforderlich' });
@@ -33,19 +48,40 @@ router.post('/', asyncHandler(async (req, res) => {
if (!anbieter_id) {
return res.status(400).json({ error: 'Anbieter ist erforderlich' });
}
if (!vo_id) {
return res.status(400).json({ error: 'VO ist erforderlich' });
}
// Make sure the VO actually belongs to the same provider.
const vo = await db.get('SELECT anbieter_id FROM vos WHERE id = ?', [vo_id]);
if (!vo) return res.status(400).json({ error: 'VO nicht gefunden' });
if (vo.anbieter_id !== Number(anbieter_id)) {
return res.status(400).json({ error: 'VO gehört nicht zum gewählten Anbieter' });
}
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]
);
const tarifId = await db.transaction(async () => {
const result = await db.run(
`INSERT INTO tarife (name, anbieter_id, vo_id, provision_euro, beschreibung) VALUES (?, ?, ?, ?, ?)`,
[name.trim(), anbieter_id, vo_id, provision_euro || 0, beschreibung || null]
);
if (Array.isArray(tarifoption_ids)) {
for (const optId of tarifoption_ids) {
await db.run(
'INSERT OR IGNORE INTO tarifoptionen_tarife (tarifoption_id, tarif_id) VALUES (?, ?)',
[optId, result.lastID]
);
}
}
return result.lastID;
});
res.json({
id: result.lastID,
id: tarifId,
name: name.trim(),
anbieter_id,
vo_id,
provision_euro: provision_euro || 0,
beschreibung: beschreibung || null,
});
@@ -59,19 +95,65 @@ router.post('/', asyncHandler(async (req, res) => {
router.put('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const { name, provision_euro, beschreibung } = req.body || {};
const { name, vo_id, provision_euro, beschreibung, tarifoption_ids } = 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' });
const current = await db.get('SELECT anbieter_id FROM tarife WHERE id = ?', [id]);
if (!current) return res.status(404).json({ error: 'Tarif nicht gefunden' });
if (vo_id) {
const vo = await db.get('SELECT anbieter_id FROM vos WHERE id = ?', [vo_id]);
if (!vo) return res.status(400).json({ error: 'VO nicht gefunden' });
if (vo.anbieter_id !== current.anbieter_id) {
return res.status(400).json({ error: 'VO gehört nicht zum Anbieter des Tarifs' });
}
}
await db.transaction(async () => {
await db.run(
`UPDATE tarife SET name = ?, vo_id = ?, provision_euro = ?, beschreibung = ? WHERE id = ?`,
[name, vo_id || null, provision_euro || 0, beschreibung || null, id]
);
if (Array.isArray(tarifoption_ids)) {
await db.run('DELETE FROM tarifoptionen_tarife WHERE tarif_id = ?', [id]);
for (const optId of tarifoption_ids) {
await db.run(
'INSERT OR IGNORE INTO tarifoptionen_tarife (tarifoption_id, tarif_id) VALUES (?, ?)',
[optId, id]
);
}
}
});
res.json({ message: 'Tarif erfolgreich aktualisiert' });
}));
// All tarifoptionen of this tariff's provider, each annotated with whether it
// is currently assigned to this tariff. Frontend uses this to render the
// checkbox grid in the tariff editor.
router.get('/:id/tarifoptionen-multi', asyncHandler(async (req, res) => {
const { id } = req.params;
const tarif = await db.get('SELECT anbieter_id FROM tarife WHERE id = ?', [id]);
if (!tarif) return res.status(404).json({ error: 'Tarif nicht gefunden' });
const rows = await db.all(
`SELECT tn.id, tn.name, tn.code, tn.provision_euro, tn.beschreibung,
CASE WHEN tt.tarifoption_id IS NULL THEN 0 ELSE 1 END AS assigned
FROM tarifoptionen_new tn
LEFT JOIN tarifoptionen_tarife tt
ON tt.tarifoption_id = tn.id AND tt.tarif_id = ?
WHERE tn.aktiv = 1
AND EXISTS (
SELECT 1 FROM tarifoptionen_tarife tt2
JOIN tarife t2 ON tt2.tarif_id = t2.id
WHERE tt2.tarifoption_id = tn.id AND t2.anbieter_id = ?
)
ORDER BY tn.name`,
[id, tarif.anbieter_id]
);
res.json(rows);
}));
router.delete('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const used = await db.get(
+92
View File
@@ -0,0 +1,92 @@
const express = require('express');
const db = require('../db');
const asyncHandler = require('../middleware/asyncHandler');
const router = express.Router();
// List all VOs (optionally filtered by anbieter via ?anbieter_id=)
router.get('/', asyncHandler(async (req, res) => {
const { anbieter_id } = req.query;
if (anbieter_id) {
const rows = await db.all(
`SELECT v.*, a.name AS anbieter_name
FROM vos v JOIN anbieter a ON v.anbieter_id = a.id
WHERE v.anbieter_id = ? AND v.aktiv = 1
ORDER BY v.nummer`,
[anbieter_id]
);
return res.json(rows);
}
const rows = await db.all(
`SELECT v.*, a.name AS anbieter_name
FROM vos v JOIN anbieter a ON v.anbieter_id = a.id
ORDER BY a.name, v.nummer`
);
res.json(rows);
}));
router.post('/', asyncHandler(async (req, res) => {
const { anbieter_id, nummer, bezeichnung } = req.body || {};
if (!anbieter_id) return res.status(400).json({ error: 'Anbieter ist erforderlich' });
if (!nummer || !String(nummer).trim()) return res.status(400).json({ error: 'VO-Nummer ist erforderlich' });
try {
const result = await db.run(
'INSERT INTO vos (anbieter_id, nummer, bezeichnung) VALUES (?, ?, ?)',
[anbieter_id, String(nummer).trim(), bezeichnung ? String(bezeichnung).trim() : null]
);
res.json({ id: result.lastID, anbieter_id, nummer: String(nummer).trim(), bezeichnung: bezeichnung || null });
} catch (err) {
if (/UNIQUE/.test(err.message)) {
return res.status(400).json({ error: 'VO mit dieser Nummer existiert bereits für diesen Anbieter' });
}
throw err;
}
}));
router.put('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const { nummer, bezeichnung, aktiv } = req.body || {};
const current = await db.get('SELECT * FROM vos WHERE id = ?', [id]);
if (!current) return res.status(404).json({ error: 'VO nicht gefunden' });
const nextNummer = nummer !== undefined ? String(nummer).trim() : current.nummer;
if (!nextNummer) return res.status(400).json({ error: 'VO-Nummer darf nicht leer sein' });
try {
await db.run(
'UPDATE vos SET nummer = ?, bezeichnung = ?, aktiv = ? WHERE id = ?',
[
nextNummer,
bezeichnung !== undefined ? (bezeichnung ? String(bezeichnung).trim() : null) : current.bezeichnung,
aktiv !== undefined ? (aktiv ? 1 : 0) : current.aktiv,
id,
]
);
res.json({ message: 'VO erfolgreich aktualisiert' });
} catch (err) {
if (/UNIQUE/.test(err.message)) {
return res.status(400).json({ error: 'VO mit dieser Nummer existiert bereits für diesen Anbieter' });
}
throw err;
}
}));
router.delete('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
// Prevent deletion if any tariff or schaltung references it.
const used = await db.get(
`SELECT
(SELECT COUNT(*) FROM tarife WHERE vo_id = ?) AS n_tarife,
(SELECT COUNT(*) FROM schaltungen WHERE vo_id = ?) AS n_schaltungen`,
[id, id]
);
if (used.n_tarife + used.n_schaltungen > 0) {
const parts = [];
if (used.n_tarife > 0) parts.push(`${used.n_tarife} Tarif(e)`);
if (used.n_schaltungen > 0) parts.push(`${used.n_schaltungen} Schaltung(en)`);
return res.status(400).json({ error: `VO kann nicht gelöscht werden: ${parts.join(', ')} verwenden diese VO` });
}
const result = await db.run('DELETE FROM vos WHERE id = ?', [id]);
if (result.changes === 0) return res.status(404).json({ error: 'VO nicht gefunden' });
res.json({ message: 'VO erfolgreich gelöscht' });
}));
module.exports = router;
+2
View File
@@ -130,6 +130,7 @@ const provisionenRouter = require('./routes/provisionen');
const provisionsregelnRouter = require('./routes/provisionsregeln');
const mitarbeiterRouter = require('./routes/mitarbeiter');
const usersRouter = require('./routes/users');
const vosRouter = require('./routes/vos');
app.use('/api/anbieter', anbieterRouter);
app.use('/api/tarife', tarifeRouter);
@@ -137,6 +138,7 @@ app.use('/api/schaltungen', schaltungenRouter);
app.use('/api/tarifoptionen', tarifoptionenRouter);
app.use('/api/mitarbeiter-prozentsaetze', mitarbeiterRouter);
app.use('/api/users', usersRouter);
app.use('/api/vos', vosRouter);
app.use('/api', dokumenteRouter); // /api/schaltungen/:id/dokumente, /api/dokumente/:id/*
app.use('/api', provisionenRouter); // /api/provisionen, /api/schaltungen/:id/provision, /api/geloeschte-schaltungen
app.use('/api', provisionsregelnRouter); // /api/provisionsregeln, /api/anbieter-provisionsregeln