feat(admin): Anzahlungskonten in der Verwaltung pflegen (zwei IBANs)

- Migration 016_deposit_accounts.sql: Tabelle deposit_accounts (label, holder,
  bank, iban, sort_order), gefüllt mit Postbank (DE12 …1261 30) und Sparkasse
  (DE83 3206 0362 3303 2140 10); bookings.deposit_account -> deposit_account_id
  mit Fremdschlüssel (ON DELETE SET NULL), Altbestand wird aufs erste Konto
  gemappt; schema.sql nachgezogen
- Neue Seite Verwaltung → Konten (/admin/accounts): anlegen, ändern, löschen
  (Löschen nur ohne Buchungsbezug), Anzeige der Verwendung je Konto
- Buchungsformular wählt aus dieser Liste (Anzeige mit IBAN-Ende), Validierung
  prüft IBAN-Format, Auftragsbestätigung druckt das gewählte Konto
- deposit_accounts()/deposit_account() lesen aus der DB (Cache wird nach
  Änderungen verworfen); Konfigurations-Override entfällt
- Anleitung (Abschnitt 3 und 15), README, config.example.php und ROADMAP
  (Feature 25) aktualisiert
This commit is contained in:
torsten 2026-11-30 17:10:24 +01:00
parent bf85a64a79
commit cc8d7330f8
15 changed files with 478 additions and 76 deletions

View file

@ -46,6 +46,10 @@ function admin_handle(string $path, array $user): void
admin_mailings($user);
return;
}
if ($path === '/admin/accounts') {
admin_accounts();
return;
}
if ($path === '/admin/backups') {
admin_backups($user);
return;
@ -836,3 +840,79 @@ function admin_backup_download(string $name): void
readfile($path);
exit;
}
/* -------------------------------------------------- Anzahlungskonten */
function admin_accounts(): void
{
$errors = [];
$createErrors = [];
$createValues = ['label' => '', 'holder' => '', 'bank' => '', 'iban' => '', 'sort_order' => ''];
$rowValues = [];
if (is_post()) {
require_post();
$action = post_string('action');
try {
if ($action === 'create') {
$createValues = deposit_account_input($_POST);
$createErrors = deposit_account_validate($createValues);
if ($createErrors === []) {
$id = deposit_account_create($createValues);
flash('success', 'Konto „' . $createValues['label'] . '“ angelegt (ID ' . $id . ').');
redirect('/admin/accounts');
}
} elseif ($action === 'update') {
$id = (int) post_string('id');
$account = deposit_account($id);
if ($account === null) {
throw new RuntimeException('Dieses Konto gibt es nicht (mehr).');
}
$rowValues[$id] = deposit_account_input($_POST);
$rowErrors = deposit_account_validate($rowValues[$id]);
if ($rowErrors !== []) {
throw new InvalidArgumentException(implode(' ', $rowErrors));
}
deposit_account_update($id, $rowValues[$id]);
flash('success', 'Konto „' . $rowValues[$id]['label'] . '“ gespeichert.');
redirect('/admin/accounts');
} elseif ($action === 'delete') {
$id = (int) post_string('id');
$account = deposit_account($id);
if ($account === null) {
throw new RuntimeException('Dieses Konto gibt es nicht (mehr).');
}
if (!deposit_account_delete($id)) {
$used = deposit_account_usage($id);
throw new RuntimeException('Das Konto wird in ' . $used . ' Buchung' . ($used === 1 ? '' : 'en')
. ' verwendet und kann deshalb nicht gelöscht werden. Bitte nur umbenennen oder die '
. 'Buchungen auf ein anderes Konto umstellen.');
}
flash('success', 'Konto „' . (string) $account['label'] . '“ gelöscht.');
redirect('/admin/accounts');
}
} catch (InvalidArgumentException $error) {
$decoded = json_decode($error->getMessage(), true);
$errors = is_array($decoded) ? $decoded : ['general' => $error->getMessage()];
} catch (Throwable $error) {
error_log('Anzahlungskonten: ' . $error->getMessage());
$errors['general'] = $error->getMessage();
}
http_response_code(422);
}
$accounts = deposit_accounts();
$usage = [];
foreach ($accounts as $account) {
$usage[(int) $account['id']] = deposit_account_usage((int) $account['id']);
}
render_page('admin_accounts', [
'accounts' => $accounts,
'usage' => $usage,
'errors' => $errors,
'createErrors' => $createErrors,
'createValues' => $createValues,
'rowValues' => $rowValues,
], 'Konten');
}

View file

@ -56,16 +56,9 @@ return [
// Maximale Größe einer hochgeladenen Sicherung (MB).
'backup_max_mb' => 200,
// Anzahlung in der Auftragsbestätigung: Frist in Werktagen (Mo–Sa ohne
// gesetzliche Feiertage). Die Konten stehen als Standard in
// app/documents.php (deposit_accounts()) und lassen sich hier
// überschreiben: Schlüssel => ['label', 'holder', 'bank', 'iban'].
// gesetzliche Feiertage). Die Konten selbst pflegt der Administrator
// unter Verwaltung → Konten (Tabelle deposit_accounts).
'deposit_due_working_days' => 7,
// 'deposit_accounts' => [
// 'postbank' => ['label' => 'Postbank – Michael Schmitz', 'holder' => 'Michael Schmitz',
// 'bank' => 'Postbank', 'iban' => 'DE…'],
// 'sparkasse' => ['label' => 'Sparkasse – Drink it cold', 'holder' => '…',
// 'bank' => '…', 'iban' => 'DE…'],
// ],
],
// Optional: Angaben für Impressum und Datenschutz überschreiben. Die
// Standardwerte stehen in app/legal.php. Hinweis: tools/deploy.sh erzeugt

View file

@ -190,7 +190,7 @@ function booking_input(array $source): array
'end_time' => normalize_time($source['end_time'] ?? ''),
'deposit_cents' => $depositRequired ? parse_money((string) ($source['deposit'] ?? '0')) : 0,
'deposit_required' => $depositRequired,
'deposit_account' => trim((string) ($source['deposit_account'] ?? '')),
'deposit_account_id' => (int) ($source['deposit_account_id'] ?? 0),
'rent_cents' => $rent,
'delivery_cents' => $delivery,
'total_cents' => $rent + $delivery,
@ -219,7 +219,7 @@ function booking_to_input(array $booking): array
'end_time' => normalize_time($booking['end_time'] ?? ''),
'deposit_cents' => (int) $booking['deposit_cents'],
'deposit_required' => (int) ($booking['deposit_required'] ?? 0),
'deposit_account' => (string) ($booking['deposit_account'] ?? ''),
'deposit_account_id' => (int) ($booking['deposit_account_id'] ?? 0),
'rent_cents' => (int) ($booking['rent_cents'] ?? $booking['total_cents']),
'delivery_cents' => (int) ($booking['delivery_cents'] ?? 0),
'total_cents' => (int) $booking['total_cents'],
@ -326,7 +326,7 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
} elseif ((int) ($data['deposit_required'] ?? 0) === 1 && $data['deposit_cents'] <= 0) {
$errors['deposit'] = 'Bitte den Betrag der Anzahlung angeben oder „Anzahlung: NEIN“ wählen.';
}
if ((int) ($data['deposit_required'] ?? 0) === 1 && !deposit_account((string) ($data['deposit_account'] ?? ''))) {
if ((int) ($data['deposit_required'] ?? 0) === 1 && !deposit_account((int) ($data['deposit_account_id'] ?? 0))) {
$errors['deposit_account'] = 'Bitte das Konto für die Anzahlung auswählen.';
}
@ -525,7 +525,7 @@ function booking_create(array $data, int $userId): int
$stmt = $pdo->prepare(
'INSERT INTO bookings
(trailer_id, employee_id, return_employee_id, start_date, end_date, start_time, end_time, deposit_cents,
deposit_required, deposit_account,
deposit_required, deposit_account_id,
rent_cents, delivery_cents, total_cents, invoice, invoice_no, kind,
customer_name, street, city, mobile, email, note, status, created_at, updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
@ -534,7 +534,8 @@ function booking_create(array $data, int $userId): int
$data['trailer_id'], $data['employee_id'], $data['return_employee_id'] ?: null,
$data['start_date'], $data['end_date'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0), (string) ($data['deposit_account'] ?? ''),
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0),
((int) ($data['deposit_account_id'] ?? 0)) > 0 ? (int) $data['deposit_account_id'] : null,
$data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
@ -567,7 +568,7 @@ function booking_update(int $id, array $data, int $userId): void
}
$stmt = $pdo->prepare(
'UPDATE bookings SET trailer_id = ?, employee_id = ?, return_employee_id = ?, start_date = ?, end_date = ?,
start_time = ?, end_time = ?, deposit_cents = ?, deposit_required = ?, deposit_account = ?,
start_time = ?, end_time = ?, deposit_cents = ?, deposit_required = ?, deposit_account_id = ?,
rent_cents = ?, delivery_cents = ?, total_cents = ?, invoice = ?, invoice_no = ?, kind = ?,
customer_name = ?, street = ?, city = ?, mobile = ?, email = ?, note = ?, updated_at = ?,
updated_by = ? WHERE id = ?'
@ -576,7 +577,8 @@ function booking_update(int $id, array $data, int $userId): void
$data['trailer_id'], $data['employee_id'], $data['return_employee_id'] ?: null,
$data['start_date'], $data['end_date'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0), (string) ($data['deposit_account'] ?? ''),
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0),
((int) ($data['deposit_account_id'] ?? 0)) > 0 ? (int) $data['deposit_account_id'] : null,
$data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],

View file

@ -419,56 +419,149 @@ function document_pdf_rows(PdfDoc $pdf, float $top, array $rows, float $valueX =
}
/**
* Konten, auf die eine Anzahlung überwiesen werden kann.
* Anzahlungskonten (Verwaltung → Konten), sortiert.
*
* Standard steht in dieser Funktion, damit sie auch dann greift, wenn die
* app/config.local.php beim Deployment neu erzeugt wird (dort wird kein
* `app.deposit_accounts` geschrieben). Weitere Konten lassen sich hier
* ergänzen oder per `app.deposit_accounts` in der lokalen Konfiguration
* überschreiben (Schlüssel => label/holder/bank/iban).
* Der Stamm liegt in der Tabelle deposit_accounts und wird vom Administrator
* gepflegt; die Auftragsbestätigung druckt das in der Buchung gewählte Konto.
*
* @return array<string, array{label: string, holder: string, bank: string, iban: string}>
* @return list<array{id: int, label: string, holder: string, bank: string, iban: string, sort_order: int}>
*/
function deposit_accounts(): array
function deposit_accounts(bool $refresh = false): array
{
$defaults = [
'postbank' => [
'label' => 'Postbank – Michael Schmitz',
'holder' => 'Michael Schmitz',
'bank' => 'Postbank',
'iban' => 'DE12 1001 0010 0464 1261 30',
],
];
$configured = config('app.deposit_accounts', null);
if (!is_array($configured) || $configured === []) {
return $defaults;
static $cache = null;
if ($refresh) {
$cache = null;
}
$accounts = [];
foreach ($configured as $key => $account) {
if (!is_array($account)) {
continue;
}
$accounts[(string) $key] = [
'label' => (string) ($account['label'] ?? $key),
'holder' => (string) ($account['holder'] ?? ''),
'bank' => (string) ($account['bank'] ?? ''),
'iban' => (string) ($account['iban'] ?? ''),
if (is_array($cache)) {
return $cache;
}
$cache = [];
try {
$rows = db()->query('SELECT id, label, holder, bank, iban, sort_order FROM deposit_accounts ORDER BY sort_order, id')
->fetchAll();
} catch (Throwable) {
return $cache; // Tabelle fehlt noch (Migration ausstehend)
}
foreach ($rows as $row) {
$cache[] = [
'id' => (int) $row['id'],
'label' => (string) $row['label'],
'holder' => (string) $row['holder'],
'bank' => (string) $row['bank'],
'iban' => (string) $row['iban'],
'sort_order' => (int) $row['sort_order'],
];
}
return $accounts !== [] ? $accounts : $defaults;
return $cache;
}
/** Konto zur Kennung; ohne gültige Kennung das erste Konto (oder null). */
function deposit_account(string $key): ?array
/** Einzelnes Konto; ohne gültige Kennung null. */
function deposit_account(int $id): ?array
{
$accounts = deposit_accounts();
if ($key !== '' && isset($accounts[$key])) {
return $accounts[$key];
foreach (deposit_accounts() as $account) {
if ((int) $account['id'] === $id) {
return $account;
}
}
$first = reset($accounts);
return $first === false ? null : $first;
return null;
}
/** Anzeigename inklusive IBAN-Ende, damit zwei Konten unterscheidbar sind. */
function deposit_account_label(array $account): string
{
$iban = preg_replace('/\s+/', '', (string) $account['iban']) ?? '';
return (string) $account['label'] . ($iban !== '' ? ' (…' . substr($iban, -4) . ')' : '');
}
/** Eingabewerte eines Anzahlungskontos normalisieren. */
function deposit_account_input(array $source): array
{
return [
'label' => trim((string) ($source['label'] ?? '')),
'holder' => trim((string) ($source['holder'] ?? '')),
'bank' => trim((string) ($source['bank'] ?? '')),
'iban' => mb_strtoupper(trim((string) ($source['iban'] ?? ''))),
'sort_order' => (int) ($source['sort_order'] ?? 0),
];
}
/** @return array<string, string> */
function deposit_account_validate(array $data): array
{
$errors = [];
if ($data['label'] === '') {
$errors['label'] = 'Bitte eine Bezeichnung angeben (z. B. „Postbank – Michael Schmitz“).';
} elseif (mb_strlen($data['label']) > 80) {
$errors['label'] = 'Die Bezeichnung ist zu lang (max. 80 Zeichen).';
}
if ($data['holder'] === '') {
$errors['holder'] = 'Bitte den Kontoinhaber angeben.';
} elseif (mb_strlen($data['holder']) > 120) {
$errors['holder'] = 'Der Kontoinhaber ist zu lang (max. 120 Zeichen).';
}
if (mb_strlen($data['bank']) > 80) {
$errors['bank'] = 'Der Bankname ist zu lang (max. 80 Zeichen).';
}
$iban = preg_replace('/\s+/', '', $data['iban']) ?? '';
if ($iban === '') {
$errors['iban'] = 'Bitte die IBAN angeben.';
} elseif (mb_strlen($iban) < 15 || mb_strlen($iban) > 34 || preg_match('/^[A-Z]{2}[0-9A-Z]+$/', $iban) !== 1) {
$errors['iban'] = 'Die IBAN sieht nicht gültig aus (z. B. DE12 1001 0010 0464 1261 30).';
}
return $errors;
}
function deposit_account_create(array $data): int
{
$errors = deposit_account_validate($data);
if ($errors !== []) {
throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE));
}
$stmt = db()->prepare(
'INSERT INTO deposit_accounts (label, holder, bank, iban, sort_order, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'],
utc_now(), utc_now(),
]);
$id = (int) db()->lastInsertId(); // vor dem Neuladen der Liste lesen
deposit_accounts(true);
return $id;
}
function deposit_account_update(int $id, array $data): void
{
$errors = deposit_account_validate($data);
if ($errors !== []) {
throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE));
}
db()->prepare(
'UPDATE deposit_accounts SET label = ?, holder = ?, bank = ?, iban = ?, sort_order = ?, updated_at = ?
WHERE id = ?'
)->execute([
$data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'], utc_now(), $id,
]);
deposit_accounts(true);
}
/** Anzahl der Buchungen, die dieses Konto verwenden. */
function deposit_account_usage(int $id): int
{
$stmt = db()->prepare('SELECT COUNT(*) FROM bookings WHERE deposit_account_id = ?');
$stmt->execute([$id]);
return (int) $stmt->fetchColumn();
}
/** Löscht ein Konto – nur solange keine Buchung darauf verweist. */
function deposit_account_delete(int $id): bool
{
if (deposit_account_usage($id) > 0) {
return false;
}
db()->prepare('DELETE FROM deposit_accounts WHERE id = ?')->execute([$id]);
deposit_accounts(true);
return true;
}
/** Frist für die Anzahlung in Werktagen (Mo–Sa, ohne gesetzliche Feiertage). */
@ -750,12 +843,12 @@ function document_confirmation_pdf(array $booking, string $variant): string
}
// Anzahlung: vereinbart (Häkchen in der Buchung) und Betrag > 0.
$depositRequired = (int) ($booking['deposit_required'] ?? 0) === 1;
$account = $depositRequired && $paid > 0 ? deposit_account((string) ($booking['deposit_account'] ?? '')) : null;
$account = $depositRequired && $paid > 0 ? deposit_account((int) ($booking['deposit_account_id'] ?? 0)) : null;
$dueDate = $account !== null ? deposit_due_date() : null;
$workingDays = deposit_due_working_days();
if ($paid > 0) {
$priceRows[] = [
$depositRequired ? 'Anzahlung (bis ' . fmt_date((string) $dueDate) . ')' : 'Anzahlung',
$account !== null ? 'Anzahlung (bis ' . fmt_date((string) $dueDate) . ')' : 'Anzahlung',
'− ' . fmt_money($paid),
];
}

View file

@ -823,7 +823,7 @@ function form_values_from_input(array $data): array
'end_time' => (string) ($data['end_time'] ?? ''),
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
'deposit_required' => (int) ($data['deposit_required'] ?? 0),
'deposit_account' => (string) ($data['deposit_account'] ?? ''),
'deposit_account_id' => (int) ($data['deposit_account_id'] ?? 0),
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $data['invoice'],
@ -877,7 +877,7 @@ function page_booking_new(array $user, string $method): void
'end_time' => '',
'deposit' => '',
'deposit_required' => 0,
'deposit_account' => '',
'deposit_account_id' => (int) (deposit_accounts()[0]['id'] ?? 0),
'rent' => '',
'delivery' => '',
'invoice' => 0,
@ -933,7 +933,7 @@ function page_booking_edit(array $user, int $id, string $method): void
'end_time' => (string) ($booking['end_time'] ?? ''),
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
'deposit_required' => (int) ($booking['deposit_required'] ?? 0),
'deposit_account' => (string) ($booking['deposit_account'] ?? ''),
'deposit_account_id' => (int) ($booking['deposit_account_id'] ?? 0) ?: (int) (deposit_accounts()[0]['id'] ?? 0),
'rent' => number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $booking['invoice'],
@ -959,7 +959,7 @@ function page_booking_edit(array $user, int $id, string $method): void
if (!$canEditBilling) {
$data['deposit_cents'] = (int) $booking['deposit_cents'];
$data['deposit_required'] = (int) ($booking['deposit_required'] ?? 0);
$data['deposit_account'] = (string) ($booking['deposit_account'] ?? '');
$data['deposit_account_id'] = (int) ($booking['deposit_account_id'] ?? 0);
$data['rent_cents'] = (int) $booking['rent_cents'];
$data['delivery_cents'] = (int) $booking['delivery_cents'];
$data['total_cents'] = (int) $booking['total_cents'];