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
+768 -212

No files matched your search

+180 -96
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>
</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>
<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="rufnummer">Rufnummer/Kundennummer <span class="required">*</span></label>
<input type="text" id="rufnummer" name="rufnummer" required>
</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>
<!-- 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-group">
<label for="hardware">Hardware (optional)</label>
<input type="text" id="hardware" name="hardware"
title="Hardware optional" onchange="toggleHardwarePricing()">
<!-- 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>
<!-- 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">
<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-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="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-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>
<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>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,12 +1653,23 @@
<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>
<button type="button" onclick="closeModal('editTariffModal')">Abbrechen</button>
+346 -83
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.
@@ -272,19 +383,18 @@ function showMessage(message, type = 'success') {
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);
}
@@ -381,55 +491,57 @@ function hideTarifoptionen() {
// Handle Schaltung form submission
async function handleSchaltungSubmit(e) {
e.preventDefault();
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));
// Validate hardware length if provided
if (selectedTarifoptionen.length) {
schaltungData.tarifoptionen = selectedTarifoptionen;
}
if (schaltungData.hardware && schaltungData.hardware.length !== 15) {
showMessage('Hardware muss genau 15 Zeichen haben (oder leer lassen)', 'error');
return;
}
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;
// Reload overview and provisions if needed
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();
await refreshDataAfterSchaltungChange();
} catch (error) {
console.error('Fehler beim Speichern der Schaltung:', 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,54 +1133,69 @@ 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();
if (!name || !anbieterId) {
showMessage('Bitte Tarif-Name und Anbieter auswählen', 'error');
return;
}
// Validation for provision euro
if (!voId) {
showMessage('Bitte VO auswählen', 'error');
return;
}
if (provisionEuro && parseFloat(provisionEuro) < 0) {
showMessage('Provision kann nicht negativ sein', 'error');
return;
}
try {
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 || '';
// Show modal
// 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);
});
}
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 */ }
}