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

+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 */ }
}