Uhrzeiten, Miete und Lieferkosten ergänzen; Server-Stand übernehmen

- bookings um optionale start_time/end_time sowie rent_cents und
  delivery_cents erweitert; Gesamtbetrag ist Miete + Lieferkosten
  (Migration 003, Schema und Doku nachgezogen)
- Formular, Detailansicht, Panel, Kalender und Kopiertext zeigen
  Uhrzeiten und die getrennten Beträge
- Live-Stand nachgezogen: Impressum/Datenschutz, Privacy-Cleanup im
  Cron-Lauf, Löschsperre für Buchungen mit Rechnung
- Cache-Buster auf Version 10 erhöht
This commit is contained in:
torsten 2026-11-18 20:59:17 +01:00
parent 672df3d0a7
commit d47a72820d
24 changed files with 1157 additions and 92 deletions

View file

@ -26,12 +26,14 @@ ini_set('display_errors', '0');
ini_set('log_errors', '1');
require DIC_APP . '/util.php';
require DIC_APP . '/legal.php';
require DIC_APP . '/db.php';
require DIC_APP . '/webpush.php';
require DIC_APP . '/auth.php';
require DIC_APP . '/data.php';
require DIC_APP . '/push.php';
require DIC_APP . '/mail.php';
require DIC_APP . '/privacy.php';
require DIC_APP . '/pages.php';
require DIC_APP . '/admin.php';
@ -50,10 +52,18 @@ set_exception_handler(static function (Throwable $error): void {
header('Content-Type: text/html; charset=utf-8');
echo '<!doctype html><meta charset="utf-8"><title>Fehler 500</title>'
. '<body style="font-family:system-ui;background:#f4f9fe;color:#0e1b26;padding:2rem">'
. '<h1>Interner Fehler</h1><p>Bitte später erneut versuchen.</p></body>';
. '<h1>Interner Fehler</h1><p>Bitte später erneut versuchen.</p>'
. '<p style="font-size:.85rem"><a style="color:#196abc" href="' . e(url('/impressum')) . '">Impressum</a>'
. ' · <a style="color:#196abc" href="' . e(url('/datenschutz')) . '">Datenschutz</a></p></body>';
});
if (PHP_SAPI !== 'cli') {
security_headers();
start_session();
// Öffentliche Rechtsseiten, Health-Check und Cron brauchen keine Session.
// So wird auf Impressum/Datenschutz kein unnötiges Sitzungs-Cookie gesetzt.
$path = current_path();
$sessionFree = ['/health', '/cron/reminders'];
if (!legal_is_public_path($path) && !in_array($path, $sessionFree, true)) {
start_session();
}
}

View file

@ -118,13 +118,29 @@ function booking_conflicts(int $trailerId, string $start, string $end, int $excl
function booking_input(array $source): array
{
$kind = (string) ($source['kind'] ?? 'pickup');
if (array_key_exists('rent_cents', $source) || array_key_exists('delivery_cents', $source)) {
$rent = max(0, (int) ($source['rent_cents'] ?? 0));
$delivery = max(0, (int) ($source['delivery_cents'] ?? 0));
} elseif (array_key_exists('rent', $source) || array_key_exists('delivery', $source)) {
$rent = parse_money((string) ($source['rent'] ?? '0'));
$delivery = parse_money((string) ($source['delivery'] ?? '0'));
} else {
// Aufrufer ohne getrennte Beträge: Gesamtbetrag gilt als Miete.
$rent = parse_money((string) ($source['total'] ?? '0'));
$delivery = 0;
}
return [
'trailer_id' => (int) ($source['trailer_id'] ?? 0),
'employee_id' => (int) ($source['employee_id'] ?? 0),
'start_date' => trim((string) ($source['start_date'] ?? '')),
'end_date' => trim((string) ($source['end_date'] ?? '')),
'start_time' => normalize_time($source['start_time'] ?? ''),
'end_time' => normalize_time($source['end_time'] ?? ''),
'deposit_cents' => parse_money((string) ($source['deposit'] ?? '0')),
'total_cents' => parse_money((string) ($source['total'] ?? '0')),
'rent_cents' => $rent,
'delivery_cents' => $delivery,
'total_cents' => $rent + $delivery,
'invoice' => ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0,
'kind' => in_array($kind, ['pickup', 'delivery'], true) ? $kind : 'pickup',
'customer_name' => trim((string) ($source['customer_name'] ?? '')),
@ -135,6 +151,30 @@ function booking_input(array $source): array
];
}
/** Bestehende Buchung als Eingabedaten (Validierung, Verschieben, Wiederherstellen). */
function booking_to_input(array $booking): array
{
return [
'trailer_id' => (int) $booking['trailer_id'],
'employee_id' => (int) $booking['employee_id'],
'start_date' => (string) $booking['start_date'],
'end_date' => (string) $booking['end_date'],
'start_time' => normalize_time($booking['start_time'] ?? ''),
'end_time' => normalize_time($booking['end_time'] ?? ''),
'deposit_cents' => (int) $booking['deposit_cents'],
'rent_cents' => (int) ($booking['rent_cents'] ?? $booking['total_cents']),
'delivery_cents' => (int) ($booking['delivery_cents'] ?? 0),
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],
'city' => (string) $booking['city'],
'mobile' => (string) $booking['mobile'],
'email' => (string) $booking['email'],
];
}
function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId = 0, int $allowEmployeeId = 0): array
{
$errors = [];
@ -163,6 +203,20 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
}
}
foreach (['start_time' => 'Mietbeginn', 'end_time' => 'Mietende'] as $field => $label) {
if (!valid_time((string) $data[$field])) {
$errors[$field] = 'Bitte für ' . $label . ' eine gültige Uhrzeit angeben (HH:MM).';
}
}
if (!isset($errors['start_time']) && !isset($errors['end_time'])
&& !isset($errors['start_date']) && !isset($errors['end_date'])
&& $data['start_date'] === $data['end_date']
&& $data['start_time'] !== '' && $data['end_time'] !== ''
&& $data['end_time'] <= $data['start_time']
) {
$errors['end_time'] = 'Am selben Tag muss das Mietende nach dem Mietbeginn liegen.';
}
if ($data['customer_name'] === '') {
$errors['customer_name'] = 'Bitte den Kundennamen angeben.';
} elseif (mb_strlen($data['customer_name']) > 190) {
@ -183,10 +237,10 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
}
$maxAmount = 10000000; // 100.000,00 €
if ($data['total_cents'] < 0 || $data['deposit_cents'] < 0) {
$errors['total'] = 'Beträge dürfen nicht negativ sein.';
} elseif ($data['total_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
$errors['total'] = 'Der Betrag ist unrealistisch hoch.';
if ($data['rent_cents'] < 0 || $data['delivery_cents'] < 0 || $data['deposit_cents'] < 0) {
$errors['rent'] = 'Beträge dürfen nicht negativ sein.';
} elseif ($data['rent_cents'] > $maxAmount || $data['delivery_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
$errors['rent'] = 'Der Betrag ist unrealistisch hoch.';
} elseif ($data['deposit_cents'] > $data['total_cents']) {
$errors['deposit'] = 'Die Anzahlung darf den Gesamtbetrag nicht übersteigen.';
}
@ -234,13 +288,16 @@ function booking_create(array $data, int $userId): int
}
$stmt = $pdo->prepare(
'INSERT INTO bookings
(trailer_id, employee_id, start_date, end_date, deposit_cents, total_cents, invoice, kind,
(trailer_id, employee_id, start_date, end_date, start_time, end_time, deposit_cents,
rent_cents, delivery_cents, total_cents, invoice, kind,
customer_name, street, city, mobile, email, status, created_at, updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
);
$stmt->execute([
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
utc_now(), utc_now(), $userId, $userId,
]);
@ -270,12 +327,15 @@ function booking_update(int $id, array $data, int $userId): void
}
$stmt = $pdo->prepare(
'UPDATE bookings SET trailer_id = ?, employee_id = ?, start_date = ?, end_date = ?,
deposit_cents = ?, total_cents = ?, invoice = ?, kind = ?, customer_name = ?, street = ?,
start_time = ?, end_time = ?, deposit_cents = ?, rent_cents = ?, delivery_cents = ?,
total_cents = ?, invoice = ?, kind = ?, customer_name = ?, street = ?,
city = ?, mobile = ?, email = ?, updated_at = ?, updated_by = ? WHERE id = ?'
);
$stmt->execute([
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
utc_now(), $userId, $id,
]);
@ -320,21 +380,12 @@ function booking_restore(int $id, int $userId): array
if (!$booking) {
throw new RuntimeException('not_found');
}
$errors = booking_validate([
'trailer_id' => (int) $booking['trailer_id'],
'employee_id' => (int) $booking['employee_id'],
'start_date' => $booking['start_date'],
'end_date' => $booking['end_date'],
'deposit_cents' => (int) $booking['deposit_cents'],
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'kind' => $booking['kind'],
'customer_name' => $booking['customer_name'],
'street' => $booking['street'],
'city' => $booking['city'],
'mobile' => $booking['mobile'],
'email' => $booking['email'],
], $id, (int) $booking['trailer_id'], (int) $booking['employee_id']);
$errors = booking_validate(
booking_to_input($booking),
$id,
(int) $booking['trailer_id'],
(int) $booking['employee_id']
);
if ($errors) {
return $errors;
}
@ -368,21 +419,10 @@ function booking_move(int $id, string $newStart, int $newTrailerId, int $userId)
return ['error' => 'Bitte einen gültigen Kühlanhänger wählen.'];
}
$data = [
'trailer_id' => $newTrailerId,
'employee_id' => (int) $booking['employee_id'],
'start_date' => $newStart,
'end_date' => $newEnd,
'deposit_cents' => (int) $booking['deposit_cents'],
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],
'city' => (string) $booking['city'],
'mobile' => (string) $booking['mobile'],
'email' => (string) $booking['email'],
];
$data = booking_to_input($booking);
$data['trailer_id'] = $newTrailerId;
$data['start_date'] = $newStart;
$data['end_date'] = $newEnd;
$pdo = db();
$pdo->beginTransaction();
@ -440,8 +480,8 @@ function booking_copy_text(array $booking): string
'Gesamtbetrag: ' . fmt_money((int) $booking['total_cents']),
'Noch zu zahlen: ' . fmt_money(due_cents((int) $booking['total_cents'], (int) $booking['deposit_cents'])),
'Rechnung: ' . booking_invoice_label($booking['invoice']),
'Von: ' . fmt_date_short((string) $booking['start_date']),
'Bis: ' . fmt_date_short((string) $booking['end_date']),
'Von: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null),
'Bis: ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null),
'Art: ' . booking_kind_label((string) $booking['kind']),
'Name: ' . $booking['customer_name'],
'Straße: ' . $booking['street'],

93
app/legal.php Normal file
View file

@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
/**
* Rechtliche Pflichtangaben für Impressum und Datenschutzerklärung.
*
* Die Werte lassen sich in app/config.local.php unter dem Schlüssel `legal`
* überschreiben. Fehlende Angaben fallen auf die hier hinterlegten Werte
* zurück. Die Standardwerte stammen von der bisherigen Website
* (drinkitcold.wixsite.com/drinkitcold).
*/
function legal_data(): array
{
static $data = null;
if (is_array($data)) {
return $data;
}
$defaults = [
'business_name' => 'Drink it cold',
'owner' => 'Michael Schmitz',
'street' => 'Rosellener Schulstr. 2',
'postal_code' => '41470',
'city' => 'Neuss',
'country' => 'Deutschland',
'phone' => '+49 172 6384350',
'email' => 'drinkitcold@web.de',
'vat_id' => 'DE408374900',
// Wird bewusst nicht im Impressum veröffentlicht: § 5 DDG verlangt
// die USt-IdNr., nicht die Steuernummer.
'tax_number' => '122/5553/5322',
'register_court' => '',
'register_number' => '',
'hosting_provider' => 'ALL-INKL.COM – Neue Medien Münnich',
'hosting_address' => 'Hauptstraße 68, 02742 Friedersdorf',
'hosting_country' => 'Deutschland',
'dpo_name' => '',
'dpo_email' => '',
'supervisory_authority' => 'Landesbeauftragte für Datenschutz und Informationsfreiheit Nordrhein-Westfalen',
'supervisory_address' => 'Kavalleriestraße 2–4, 40213 Düsseldorf',
'supervisory_phone' => '0211 38424-0',
'supervisory_email' => 'poststelle@ldi.nrw.de',
'supervisory_url' => 'https://www.ldi.nrw.de',
// Bei inhaltlichen Änderungen der Datenschutzerklärung anpassen.
'privacy_version' => '13.11.2026',
'log_retention_days' => 30,
'log_max_mb' => 5,
'invoice_retention_years' => 10,
'limitation_years' => 3,
];
$configured = config('legal', []);
if (is_array($configured)) {
foreach ($configured as $key => $value) {
if (is_string($key) && (is_string($value) || is_int($value)) && $value !== '') {
$defaults[$key] = $value;
}
}
}
$defaults['phone_href'] = legal_phone_href((string) $defaults['phone']);
$defaults['address_line'] = trim(
(string) $defaults['street'] . ', ' . (string) $defaults['postal_code'] . ' ' . (string) $defaults['city']
);
$defaults['session_days'] = max(1, (int) round(((int) config('app.session_absolute_seconds', 7776000)) / 86400));
$defaults['remember_days'] = max(1, (int) round(((int) config('app.remember_seconds', 7776000)) / 86400));
$data = $defaults;
return $data;
}
function legal_phone_href(string $phone): string
{
$digits = preg_replace('/[^0-9+]/', '', $phone) ?? '';
return $digits !== '' ? 'tel:' . $digits : '';
}
/** Öffentliche Rechtsseiten, die ohne Anmeldung und ohne Session erreichbar sind. */
function legal_is_public_path(string $path): bool
{
return in_array($path, ['/impressum', '/datenschutz'], true);
}
function legal_page(string $page): void
{
if (!in_array($page, ['impressum', 'datenschutz'], true)) {
abort_page(404, 'Diese Seite gibt es nicht.');
}
render_standalone('legal', [
'page' => $page,
'info' => legal_data(),
], $page === 'impressum' ? 'Impressum' : 'Datenschutz');
}

View file

@ -54,6 +54,10 @@ function page_handle(string $method, string $path): void
page_login($method);
return;
}
if ($path === '/impressum' || $path === '/datenschutz') {
legal_page(substr($path, 1));
return;
}
$user = auth_user();
if ($user !== null && $user['must_change_password'] === 1
@ -177,9 +181,15 @@ function cron_reminders(): void
}
try {
$cleanup = privacy_cleanup();
$push = push_dispatch_due();
$mail = reminder_send_due();
echo 'Drink it cold – Erinnerungslauf ' . fmt_datetime(utc_now()) . "\n";
echo sprintf(
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['reminder_mail_log'],
$cleanup['reminder_push_log'], $cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
);
if (!push_is_configured()) {
echo "Push: nicht konfiguriert (VAPID-Schlüssel fehlen).\n";
} else {
@ -463,8 +473,11 @@ function form_values_from_input(array $data): array
'employee_id' => (int) $data['employee_id'],
'start_date' => (string) $data['start_date'],
'end_date' => (string) $data['end_date'],
'start_time' => (string) ($data['start_time'] ?? ''),
'end_time' => (string) ($data['end_time'] ?? ''),
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
'total' => number_format($data['total_cents'] / 100, 2, ',', ''),
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $data['invoice'],
'kind' => (string) $data['kind'],
'customer_name' => (string) $data['customer_name'],
@ -505,8 +518,11 @@ function page_booking_new(array $user, string $method): void
'employee_id' => $employeeId,
'start_date' => $start,
'end_date' => $end,
'start_time' => '',
'end_time' => '',
'deposit' => '',
'total' => '',
'rent' => '',
'delivery' => '',
'invoice' => 0,
'kind' => 'pickup',
'customer_name' => '',
@ -549,8 +565,11 @@ function page_booking_edit(array $user, int $id, string $method): void
'employee_id' => (int) $booking['employee_id'],
'start_date' => (string) $booking['start_date'],
'end_date' => (string) $booking['end_date'],
'start_time' => (string) ($booking['start_time'] ?? ''),
'end_time' => (string) ($booking['end_time'] ?? ''),
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
'total' => number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
'rent' => number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $booking['invoice'],
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
@ -585,12 +604,16 @@ function booking_detail_context(array $booking, array $user): array
{
$reminders = booking_reminders($booking);
$done = reminder_done_map([(int) $booking['id']]);
$deleteBlocked = (int) $booking['invoice'] === 1;
$isAdmin = ($user['role'] ?? '') === 'admin';
return [
'booking' => $booking,
'reminders' => $reminders,
'doneMap' => $done,
'copyText' => booking_copy_text($booking),
'canDelete' => ($user['role'] ?? '') === 'admin',
'canDelete' => $isAdmin && !$deleteBlocked,
'deleteBlocked' => $deleteBlocked,
'isAdmin' => $isAdmin,
];
}
@ -660,6 +683,12 @@ function page_booking_delete(array $user, int $id): void
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
// Rechnungs- und Buchhaltungsdaten unterliegen der gesetzlichen
// Aufbewahrungspflicht (§ 147 AO, § 257 HGB) und dürfen nicht gelöscht werden.
if ((int) $booking['invoice'] === 1) {
flash('error', 'Buchungen mit Rechnung können wegen der gesetzlichen Aufbewahrungspflicht nicht gelöscht werden. Bitte zuerst die Rechnungsmarkierung entfernen, wenn keine Rechnung erstellt wurde.');
redirect('/bookings/' . $id);
}
booking_delete($id);
flash('success', 'Buchung von ' . $booking['customer_name'] . ' wurde endgültig gelöscht.');
redirect('/calendar?view=month&date=' . $booking['start_date']);

84
app/privacy.php Normal file
View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* Datenschutz-Aufräumarbeiten.
*
* Wird beim täglichen Erinnerungslauf (Cron) ausgeführt und hält die
* Speicherdauer kurz, die in der Datenschutzerklärung zugesagt wird:
* Login-Fehlversuche, abgelaufene Remember-Tokens und alte Versandprotokolle.
*/
function privacy_cleanup(): array
{
$result = [
'login_attempts' => 0,
'auth_tokens' => 0,
'reminder_mail_log' => 0,
'reminder_push_log' => 0,
'log_rotated' => false,
];
// Ratenbegrenzung braucht nur das aktuelle Zeitfenster (max. 15 Minuten).
$result['login_attempts'] = privacy_delete(
'DELETE FROM login_attempts WHERE attempted_at < ?',
[utc_after(-86400)]
);
$result['auth_tokens'] = privacy_delete(
'DELETE FROM auth_tokens WHERE expires_at < ?',
[utc_now()]
);
$result['reminder_mail_log'] = privacy_delete(
'DELETE FROM reminder_mail_log WHERE sent_at < ?',
[utc_after(-365 * 86400)]
);
$result['reminder_push_log'] = privacy_delete(
'DELETE FROM reminder_push_log WHERE sent_at < ?',
[utc_after(-365 * 86400)]
);
$result['log_rotated'] = privacy_rotate_error_log();
return $result;
}
function privacy_delete(string $sql, array $params): int
{
$stmt = db()->prepare($sql);
$stmt->execute($params);
return $stmt->rowCount();
}
/**
* Rotiert storage/logs/php.log bei 5 MB oder nach 30 Tagen. Es bleibt
* höchstens eine Sicherung (php.log.1) erhalten.
*/
function privacy_rotate_error_log(): bool
{
$storage = (string) config('app.storage_path', DIC_ROOT . '/storage');
$path = $storage . '/logs/php.log';
if (!is_file($path)) {
return false;
}
$size = @filesize($path);
$mtime = @filemtime($path);
if ($size === false || $mtime === false) {
return false;
}
$maxAge = 30 * 86400;
$maxBytes = max(1, (int) config('legal.log_max_mb', 5)) * 1024 * 1024;
if ($size < $maxBytes && $mtime > time() - $maxAge) {
return false;
}
$rotated = $path . '.1';
if (is_file($rotated) && (int) @filemtime($rotated) < time() - $maxAge) {
@unlink($rotated);
}
if (!@rename($path, $rotated)) {
return false;
}
@touch($path);
@chmod($path, 0640);
return true;
}

View file

@ -89,7 +89,7 @@ function url(string $path = '/'): string
}
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
const DIC_ASSET_VERSION = '8';
const DIC_ASSET_VERSION = '10';
function asset(string $path): string
{
@ -233,6 +233,8 @@ function abort_page(int $code, string $message): never
. '<p class="eyebrow">Drink it cold · Terminplanung</p>'
. '<h1>' . e($title) . '</h1><p>' . e($message) . '</p>'
. '<p><a class="btn primary" href="' . e(url('/')) . '">Zur Übersicht</a></p>'
. '<p class="muted small"><a href="' . e(url('/impressum')) . '">Impressum</a>'
. ' · <a href="' . e(url('/datenschutz')) . '">Datenschutz</a></p>'
. '</div></body></html>';
exit;
}
@ -258,6 +260,55 @@ function date_obj(string $iso): DateTimeImmutable
return new DateTimeImmutable($iso . ' 12:00:00', new DateTimeZone('Europe/Berlin'));
}
/** Uhrzeit als "HH:MM" normalisieren; leer bleibt leer (optional). */
function normalize_time(mixed $value): string
{
$text = trim((string) $value);
if ($text === '') {
return '';
}
if (preg_match('/^(\d{1,2}):(\d{2})(?::\d{2})?$/', $text, $match) === 1) {
return sprintf('%02d:%02d', (int) $match[1], (int) $match[2]);
}
return $text;
}
/** Leere Uhrzeit wird in der Datenbank als NULL gespeichert. */
function null_if_empty(string $value): ?string
{
return $value === '' ? null : $value;
}
/** Leere Uhrzeit ist erlaubt – sie ist ein optionales Zusatzfeld. */
function valid_time(?string $time): bool
{
if ($time === null || $time === '') {
return true;
}
return preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) === 1;
}
function fmt_time(?string $time): string
{
$value = normalize_time($time);
return $value !== '' && valid_time($value) ? $value : '';
}
/** Datum mit optionaler Uhrzeit, z. B. "30.11.2026 14:00". */
function fmt_date_with_time(string $iso, ?string $time): string
{
$clock = fmt_time($time);
return $clock === '' ? fmt_date($iso) : fmt_date($iso) . ' ' . $clock;
}
/** Kurzform für Listen/Kopiertext: "30.11.26 14:00". */
function fmt_date_short_with_time(string $iso, ?string $time): string
{
$clock = fmt_time($time);
return $clock === '' ? fmt_date_short($iso) : fmt_date_short($iso) . ' ' . $clock;
}
function add_days(string $iso, int $days): string
{
return date_obj($iso)->modify(($days >= 0 ? '+' : '') . $days . ' days')->format('Y-m-d');