drink-it-cold/app/pages.php
torsten 0a2d0a879d Benutzer per Einladungslink Zugang geben
- Einladung per E-Mail oder als Link zum Weitergeben: 7 Tage gültig,
  einmalig, Token nur als SHA-256-Hash gespeichert
- Seite /invite/<token>, auf der der Benutzer sein Passwort selbst setzt
- Admin kann jederzeit eine neue Einladung erzeugen; altes Passwort und
  bestehende Sitzungen werden dabei ungültig
- Migration 005_user_invites, Aufräumen im Cron, Datenschutzerklärung ergänzt
- deploy.sh: liest credentials.txt im Format KEY: value, nutzt TLS 1.2 für den
  FTP-Datenkanal (KAS bricht bei TLS 1.3 ab ~16 KB mit 426 ab) und übernimmt
  VAPID-Schlüssel, Cron-Token und Mail-Einstellungen aus der Live-Konfiguration
2026-11-18 22:20:37 +01:00

1078 lines
36 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/** Web-Oberfläche: Anmeldung, Übersicht, Kalender, Buchungen, Erinnerungen. */
function render_page(string $template, array $vars, string $pageTitle): void
{
$user = auth_user();
$contentFile = DIC_ROOT . '/views/' . $template . '.php';
if (!is_file($contentFile)) {
throw new RuntimeException('View fehlt: ' . $template);
}
extract($vars, EXTR_SKIP);
$title = $pageTitle;
ob_start();
require $contentFile;
$content = (string) ob_get_clean();
require DIC_ROOT . '/views/layout.php';
}
function render_partial(string $template, array $vars): string
{
$contentFile = DIC_ROOT . '/views/' . $template . '.php';
extract($vars, EXTR_SKIP);
ob_start();
require $contentFile;
return (string) ob_get_clean();
}
function render_standalone(string $template, array $vars, string $pageTitle): void
{
$contentFile = DIC_ROOT . '/views/' . $template . '.php';
extract($vars, EXTR_SKIP);
$title = $pageTitle;
require $contentFile;
}
function page_handle(string $method, string $path): void
{
$path = '/' . trim($path, '/');
if (!in_array($method, ['GET', 'POST'], true)) {
abort_page(405, 'Methode nicht erlaubt.');
}
if ($path === '/health') {
health_check();
return;
}
if ($path === '/cron/reminders') {
cron_reminders();
return;
}
if ($path === '/login') {
page_login($method);
return;
}
if (preg_match('#^/invite/([a-f0-9]{64})$#', $path, $m) === 1) {
page_invite($method, $m[1]);
return;
}
if ($path === '/impressum' || $path === '/datenschutz') {
legal_page(substr($path, 1));
return;
}
$user = auth_user();
if ($user !== null && $user['must_change_password'] === 1
&& !in_array($path, ['/account', '/logout', '/push/subscribe', '/push/unsubscribe', '/push/test'], true)
) {
flash('info', 'Bitte zuerst das eigene Passwort ändern.');
redirect('/account');
}
if ($path === '/logout') {
require_post();
auth_logout();
redirect('/login');
}
$user = auth_require_login();
if ($path === '/') {
page_dashboard($user);
return;
}
if ($path === '/calendar') {
page_calendar($user);
return;
}
if ($path === '/availability') {
page_availability($user);
return;
}
if ($path === '/bookings/new') {
page_booking_new($user, $method);
return;
}
if (preg_match('#^/bookings/(\d+)$#', $path, $m) === 1) {
page_booking_detail($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/panel$#', $path, $m) === 1) {
page_booking_panel($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/edit$#', $path, $m) === 1) {
page_booking_edit($user, (int) $m[1], $method);
return;
}
if (preg_match('#^/bookings/(\d+)/cancel$#', $path, $m) === 1) {
page_booking_cancel($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/restore$#', $path, $m) === 1) {
page_booking_restore($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/delete$#', $path, $m) === 1) {
page_booking_delete($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/move$#', $path, $m) === 1) {
page_booking_move($user, (int) $m[1]);
return;
}
if ($path === '/api/availability') {
api_availability();
return;
}
if ($path === '/search') {
page_search($user);
return;
}
if ($path === '/reminders') {
page_reminders($user);
return;
}
if ($path === '/reminders/done') {
page_reminder_done($user);
return;
}
if ($path === '/push/subscribe') {
page_push_subscribe($user);
return;
}
if ($path === '/push/unsubscribe') {
page_push_unsubscribe($user);
return;
}
if ($path === '/push/test') {
page_push_test($user);
return;
}
if ($path === '/account') {
page_account($user, $method);
return;
}
if ($path === '/admin' || str_starts_with($path, '/admin/')) {
admin_handle($path, $user);
return;
}
abort_page(404, 'Diese Seite gibt es nicht.');
}
function health_check(): void
{
try {
db()->query('SELECT 1');
header('Content-Type: text/plain; charset=utf-8');
echo "ok\n";
} catch (Throwable) {
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo "db error\n";
}
}
function cron_reminders(): void
{
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
$expected = (string) config('app.cron_token', '');
$given = query_string('token');
if ($expected === '' || $given === '' || !hash_equals($expected, $given)) {
http_response_code(403);
echo "Forbidden\n";
exit;
}
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 Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
$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 {
echo sprintf(
"Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt, %d ohne Abo.\n",
$push['sent'], $push['failed'], $push['removed'], $push['skipped_no_subscription']
);
}
if (!$mail['enabled']) {
echo "E-Mail: deaktiviert.\n";
} else {
echo sprintf("E-Mail: %d versendet, %d übersprungen.\n", $mail['sent'], $mail['skipped']);
foreach ($mail['errors'] as $error) {
echo 'E-Mail-Fehler: ' . $error . "\n";
}
}
} catch (Throwable $error) {
error_log('Cron-Erinnerungen: ' . $error->getMessage());
http_response_code(500);
echo "Fehler: Erinnerungslauf konnte nicht abgeschlossen werden.\n";
}
}
/* --------------------------------------------------------------- Anmeldung */
function page_login(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$error = '';
$first = '';
$last = '';
$remember = true;
if ($method === 'POST') {
$first = post_string('first_name');
$last = post_string('last_name');
$password = (string) ($_POST['password'] ?? '');
$remember = post_string('remember') === '1';
$next = safe_next(post_string('next'), '/');
if (!csrf_valid()) {
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
} elseif ($first === '' || $last === '' || $password === '') {
$error = 'Bitte Vorname, Nachname und Passwort angeben.';
} else {
try {
$user = auth_verify_login($first, $last, $password);
auth_login($user, $remember);
if ((int) $user['must_change_password'] === 1) {
flash('info', 'Bitte zuerst ein neues Passwort vergeben.');
redirect('/account');
}
redirect($next);
} catch (RuntimeException $e) {
$error = match ($e->getMessage()) {
'locked' => 'Zu viele Fehlversuche. Bitte in einigen Minuten erneut versuchen.',
'disabled' => 'Dieses Konto ist deaktiviert. Bitte beim Administrator melden.',
default => 'Vorname, Nachname oder Passwort stimmen nicht.',
};
}
}
}
render_standalone('login', [
'error' => $error,
'first' => $first,
'last' => $last,
'remember' => $remember,
'next' => safe_next(query_string('next') ?: post_string('next'), '/'),
], 'Anmelden');
}
/* --------------------------------------------------------------- Einladung */
/**
* Einmaliger Link aus der Einladungs-E-Mail: Der Benutzer vergibt hier sein
* Passwort selbst. Danach wird er bewusst zur Anmeldung geschickt, damit er
* das neue Passwort direkt ausprobiert.
*/
function page_invite(string $method, string $token): void
{
$invite = invite_find($token);
$state = 'form';
$error = '';
if ($invite === null) {
$state = 'invalid';
http_response_code(410);
} elseif ($invite['status'] !== 'active') {
$state = 'invalid';
http_response_code(403);
} elseif ($method === 'POST') {
require_post();
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['repeat_password'] ?? '');
if (mb_strlen($password) < 8) {
$error = 'Das Passwort muss mindestens 8 Zeichen haben.';
} elseif ($password !== $repeat) {
$error = 'Die beiden Passwörter stimmen nicht überein.';
} else {
try {
invite_accept($invite, $password);
// Eine bestehende Sitzung dieses Kontos ist durch den neuen
// auth_epoch ohnehin ungültig; hier wird sie auch formal beendet.
$current = auth_user();
if ($current !== null && (int) $current['id'] === (int) $invite['user_id']) {
auth_clear_session();
}
flash('success', 'Ihr Zugang ist eingerichtet. Bitte jetzt mit Vorname, Nachname und dem neuen Passwort anmelden.');
redirect('/login');
} catch (RuntimeException $e) {
if ($e->getMessage() !== 'invite_used') {
throw $e;
}
// Zwei Geräte haben den Link gleichzeitig geöffnet.
$state = 'invalid';
http_response_code(410);
}
}
if ($state === 'form') {
http_response_code(422);
}
}
render_standalone('invite', [
'state' => $state,
'error' => $error,
'firstName' => $invite !== null ? (string) $invite['first_name'] : '',
'lastName' => $invite !== null ? (string) $invite['last_name'] : '',
'email' => $invite !== null ? (string) ($invite['email'] ?? '') : '',
], 'Zugang einrichten');
}
/* --------------------------------------------------------------- Übersicht */
function page_dashboard(array $user): void
{
$today = today_iso();
$trailers = trailers_all();
$todayBookings = bookings_by_date($today);
$byTrailer = [];
foreach ($todayBookings as $booking) {
$byTrailer[(int) $booking['trailer_id']][] = $booking;
}
$upcoming = upcoming_handovers(14, reminder_scope_employee($user));
$employeeScope = reminder_scope_employee($user);
$allReminders = reminder_list(add_days($today, -30), add_days($today, 7), $employeeScope, false);
$openReminderCount = count($allReminders);
$reminders = array_slice($allReminders, 0, 6);
$upcoming = array_slice($upcoming, 0, 10);
$roadmap = [];
foreach ($trailers as $trailer) {
$roadmap[] = [
'trailer' => $trailer,
'bookings' => $byTrailer[(int) $trailer['id']] ?? [],
];
}
$weekEnd = add_days($today, 7);
$handoverCount = 0;
foreach (booking_list($today, $weekEnd, false, $employeeScope) as $booking) {
if ($booking['start_date'] >= $today && $booking['start_date'] <= $weekEnd) {
$handoverCount++;
}
}
render_page('dashboard', [
'today' => $today,
'trailers' => $trailers,
'roadmap' => $roadmap,
'upcoming' => $upcoming,
'reminders' => $reminders,
'openReminderCount' => $openReminderCount,
'handoverCount' => $handoverCount,
'employeeScope' => $employeeScope,
], 'Übersicht');
}
/* ---------------------------------------------------------------- Kalender */
function calendar_url(string $date, string $view, int $employeeId, bool $showCancelled): string
{
$params = ['view' => $view, 'date' => $date];
if ($employeeId > 0) {
$params['employee'] = $employeeId;
}
if ($showCancelled) {
$params['cancelled'] = '1';
}
return '/calendar?' . http_build_query($params);
}
function page_calendar(array $user): void
{
$view = query_string('view', 'month');
if (!in_array($view, ['day', 'week', 'month'], true)) {
$view = 'month';
}
$date = query_string('date');
if (!valid_date($date)) {
$date = today_iso();
}
$employeeId = query_int('employee');
$showCancelled = query_string('cancelled') === '1';
if ($view === 'day') {
$from = $to = $date;
} elseif ($view === 'month') {
$from = month_start($date);
$to = month_end($date);
} else {
$from = week_start($date);
$to = add_days($from, 6);
}
$bookings = booking_list($from, $to, $showCancelled, $employeeId);
$byTrailer = [];
foreach ($bookings as $booking) {
$byTrailer[(int) $booking['trailer_id']][] = $booking;
}
// Aktive Anhänger immer zeigen; inaktive nur, wenn im Zeitraum noch
// historische Buchungen sichtbar sind.
$trailers = array_values(array_filter(
trailers_all(false),
static fn (array $t): bool => (int) $t['active'] === 1 || !empty($byTrailer[(int) $t['id']])
));
$days = [];
$cursor = $from;
while ($cursor <= $to) {
$days[] = [
'iso' => $cursor,
'day' => (int) date_obj($cursor)->format('j'),
'weekday' => fmt_weekday_short($cursor),
'is_today' => $cursor === today_iso(),
'is_weekend' => (int) date_obj($cursor)->format('N') >= 6,
'is_first_of_month' => date_obj($cursor)->format('j') === '1',
];
$cursor = add_days($cursor, 1);
}
$barBase = ['day' => 76, 'week' => 48, 'month' => 34][$view];
$rowMin = ['day' => 104, 'week' => 64, 'month' => 44][$view];
$rows = [];
foreach ($trailers as $trailer) {
$laneInfo = calendar_lanes($byTrailer[(int) $trailer['id']] ?? []);
$lanes = $laneInfo['lanes'];
$bars = [];
foreach ($laneInfo['bookings'] as $booking) {
$bars[] = [
'booking' => $booking,
'geo' => calendar_geometry($booking, $from, $to, $lanes),
];
}
$rows[] = [
'trailer' => $trailer,
'lanes' => $lanes,
'bars' => $bars,
'height' => max($rowMin, $barBase * $lanes + 16),
];
}
$prevDate = $nextDate = $date;
if ($view === 'day') {
$prevDate = add_days($date, -1);
$nextDate = add_days($date, 1);
} elseif ($view === 'week') {
$prevDate = add_days($date, -7);
$nextDate = add_days($date, 7);
} else {
$prevDate = date_obj(month_start($date))->modify('first day of previous month')->format('Y-m-d');
$nextDate = date_obj(month_start($date))->modify('first day of next month')->format('Y-m-d');
}
if ($view === 'day') {
$title = fmt_date_long($date);
} elseif ($view === 'week') {
$title = 'KW ' . date_obj($from)->format('W') . ' · ' . fmt_date_range($from, $to);
} else {
$title = fmt_month($date);
}
$employees = employees_all();
render_page('calendar', [
'view' => $view,
'date' => $date,
'from' => $from,
'to' => $to,
'days' => $days,
'rows' => $rows,
'calTitle' => $title,
'prevDate' => $prevDate,
'nextDate' => $nextDate,
'today' => today_iso(),
'employeeId' => $employeeId,
'showCancelled' => $showCancelled,
'employees' => $employees,
'bookingCount' => count($bookings),
'urlFor' => static function (string $d) use ($view, $employeeId, $showCancelled): string {
return calendar_url($d, $view, $employeeId, $showCancelled);
},
], 'Kalender');
}
/* ----------------------------------------------------------- Verfügbarkeit */
function page_availability(array $user): void
{
$from = query_string('from');
$to = query_string('to');
$checked = $from !== '' || $to !== '';
$errors = [];
if (!$checked) {
$from = today_iso();
$to = add_days($from, 3);
} else {
if (!valid_date($from)) {
$errors['from'] = 'Bitte ein gültiges Startdatum angeben.';
}
if ($to === '') {
$to = $from;
}
if (!valid_date($to)) {
$errors['to'] = 'Bitte ein gültiges Enddatum angeben.';
}
if (!$errors) {
if ($to < $from) {
$errors['to'] = 'Das Ende darf nicht vor dem Beginn liegen.';
} elseif (days_between($from, $to) > 365) {
$errors['to'] = 'Der Zeitraum darf höchstens 365 Tage betragen.';
}
}
}
$groups = ['trailer' => [], 'chest' => []];
$totals = ['trailer' => 0, 'chest' => 0];
$freeCount = 0;
if ($checked && !$errors) {
foreach (trailers_all() as $trailer) {
$key = trailer_is_chest($trailer) ? 'chest' : 'trailer';
$totals[$key]++;
// Nur tatsächlich freie Fahrzeuge ausweisen; belegte entfallen.
if (booking_conflicts((int) $trailer['id'], $from, $to)) {
continue;
}
$freeCount++;
$groups[$key][] = ['trailer' => $trailer];
}
}
render_page('availability', [
'from' => $from,
'to' => $to,
'checked' => $checked,
'errors' => $errors,
'groups' => $groups,
'totals' => $totals,
'freeCount' => $freeCount,
'total' => $totals['trailer'] + $totals['chest'],
'user' => $user,
], 'Verfügbarkeit');
}
/* --------------------------------------------------------------- Buchungen */
function booking_form_context(array $user, ?array $booking = null, array $values = [], array $errors = []): array
{
$trailers = trailers_all(false);
$employees = employees_all(false);
$currentTrailer = (int) ($values['trailer_id'] ?? 0);
$currentEmployee = (int) ($values['employee_id'] ?? 0);
$trailerOptions = array_values(array_filter(
$trailers,
static fn (array $t): bool => (int) $t['active'] === 1 || (int) $t['id'] === $currentTrailer
));
$employeeOptions = array_values(array_filter(
$employees,
static fn (array $e): bool => (int) $e['active'] === 1 || (int) $e['id'] === $currentEmployee
));
return [
'booking' => $booking,
'values' => $values,
'errors' => $errors,
'trailers' => $trailerOptions,
'employees' => $employeeOptions,
'user' => $user,
'isEdit' => $booking !== null,
];
}
function form_values_from_input(array $data): array
{
return [
'trailer_id' => (int) $data['trailer_id'],
'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, ',', ''),
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $data['invoice'],
'invoice_no' => (string) ($data['invoice_no'] ?? ''),
'kind' => (string) $data['kind'],
'customer_name' => (string) $data['customer_name'],
'street' => (string) $data['street'],
'city' => (string) $data['city'],
'mobile' => (string) $data['mobile'],
'email' => (string) $data['email'],
];
}
function page_booking_new(array $user, string $method): void
{
$trailers = trailers_all();
$employees = employees_all();
if (!$trailers || !$employees) {
abort_page(500, 'Es sind keine Kühlanhänger oder Mitarbeiter hinterlegt.');
}
$start = query_string('start');
if (!valid_date($start)) {
$start = today_iso();
}
$end = query_string('end');
if (!valid_date($end) || $end < $start) {
$end = add_days($start, 3);
}
$trailerId = query_int('trailer');
if (!array_filter($trailers, static fn (array $t): bool => (int) $t['id'] === $trailerId)) {
$trailerId = (int) $trailers[0]['id'];
}
$employeeId = auth_employee_id($user);
if (!array_filter($employees, static fn (array $e): bool => (int) $e['id'] === $employeeId)) {
$employeeId = (int) $employees[0]['id'];
}
$values = [
'trailer_id' => $trailerId,
'employee_id' => $employeeId,
'start_date' => $start,
'end_date' => $end,
'start_time' => '',
'end_time' => '',
'deposit' => '',
'rent' => '',
'delivery' => '',
'invoice' => 0,
'invoice_no' => '',
'kind' => 'pickup',
'customer_name' => '',
'street' => '',
'city' => '',
'mobile' => '',
'email' => '',
];
$errors = [];
if ($method === 'POST') {
require_post();
$data = booking_input($_POST);
$values = form_values_from_input($data);
$errors = booking_validate($data);
if (!$errors) {
try {
$id = booking_create($data, (int) $user['id']);
flash('success', 'Buchung für ' . $data['customer_name'] . ' wurde angelegt.');
redirect('/bookings/' . $id);
} catch (InvalidArgumentException $e) {
$errors = json_decode($e->getMessage(), true) ?: ['form' => 'Buchung konnte nicht gespeichert werden.'];
}
}
http_response_code(422);
}
render_page('booking_form', booking_form_context($user, null, $values, $errors), 'Neue Buchung');
}
function page_booking_edit(array $user, int $id, string $method): void
{
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
$values = [
'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' => (string) ($booking['start_time'] ?? ''),
'end_time' => (string) ($booking['end_time'] ?? ''),
'deposit' => number_format((int) $booking['deposit_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'],
'invoice_no' => (string) ($booking['invoice_no'] ?? ''),
'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'],
];
$errors = [];
if ($method === 'POST') {
require_post();
$data = booking_input($_POST);
$values = form_values_from_input($data);
$errors = booking_validate($data, $id, (int) $booking['trailer_id'], (int) $booking['employee_id']);
if (!$errors) {
try {
booking_update($id, $data, (int) $user['id']);
flash('success', 'Buchung wurde aktualisiert.');
redirect('/bookings/' . $id);
} catch (InvalidArgumentException $e) {
$errors = json_decode($e->getMessage(), true) ?: ['form' => 'Buchung konnte nicht gespeichert werden.'];
}
}
http_response_code(422);
}
render_page('booking_form', booking_form_context($user, $booking, $values, $errors), 'Buchung bearbeiten');
}
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' => $isAdmin && !$deleteBlocked,
'deleteBlocked' => $deleteBlocked,
'isAdmin' => $isAdmin,
];
}
function page_booking_detail(array $user, int $id): void
{
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
render_page('booking_detail', booking_detail_context($booking, $user), 'Buchung ' . $booking['customer_name']);
}
function page_booking_panel(array $user, int $id): void
{
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
header('Content-Type: text/html; charset=utf-8');
echo render_partial('booking_panel', booking_detail_context($booking, $user) + ['panel' => true]);
}
function page_booking_cancel(array $user, int $id): void
{
require_post();
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
if ($booking['status'] === 'active') {
booking_cancel($id, (int) $user['id']);
flash('success', 'Buchung von ' . $booking['customer_name'] . ' wurde storniert. Die Erinnerungen entfallen.');
}
$back = safe_next(post_string('return_to'), '/bookings/' . $id);
redirect($back);
}
function page_booking_restore(array $user, int $id): void
{
require_post();
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
if ($booking['status'] === 'cancelled') {
try {
$errors = booking_restore($id, (int) $user['id']);
if ($errors) {
flash('error', reset($errors) ?: 'Buchung kann nicht wiederhergestellt werden.');
} else {
flash('success', 'Buchung wurde wieder aktiviert.');
}
} catch (RuntimeException) {
abort_page(404, 'Buchung nicht gefunden.');
}
}
redirect('/bookings/' . $id);
}
function page_booking_delete(array $user, int $id): void
{
require_post();
if (($user['role'] ?? '') !== 'admin') {
abort_page(403, 'Nur Administratoren dürfen Buchungen löschen.');
}
$booking = booking_find($id);
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']);
}
function page_booking_move(array $user, int $id): void
{
require_post();
$result = booking_move(
$id,
post_string('start_date'),
(int) post_string('trailer_id'),
(int) $user['id']
);
if (isset($result['error'])) {
json_response(['ok' => false, 'error' => $result['error']], 409);
}
json_response($result);
}
function api_availability(): void
{
auth_require_login();
$trailerId = query_int('trailer');
$start = query_string('start');
$end = query_string('end');
$exclude = query_int('exclude');
if ($trailerId <= 0 || !valid_date($start) || !valid_date($end) || $end < $start) {
json_response(['ok' => false, 'error' => 'Bitte Anhänger und Zeitraum angeben.'], 422);
}
$conflicts = booking_conflicts($trailerId, $start, $end, $exclude);
json_response([
'ok' => !$conflicts,
'conflicts' => array_map(static fn (array $b): array => [
'id' => (int) $b['id'],
'customer' => $b['customer_name'],
'start' => $b['start_date'],
'end' => $b['end_date'],
], $conflicts),
]);
}
/* ------------------------------------------------------------------ Suche */
function page_search(array $user): void
{
$query = query_string('q');
$results = $query !== '' ? booking_search($query) : [];
render_page('search', [
'query' => $query,
'results' => $results,
], 'Suche');
}
/* ------------------------------------------------------------ Erinnerungen */
function page_reminders(array $user): void
{
$range = query_string('range', '14');
if (!in_array($range, ['7', '14', '30', 'all'], true)) {
$range = '14';
}
$scope = reminder_scope_employee($user);
$employeeFilter = $scope;
if (($user['role'] ?? '') === 'admin') {
$employeeFilter = query_int('employee');
}
$showDone = query_string('done') === '1';
$today = today_iso();
if ($range === 'all') {
$from = add_days($today, -365);
$to = add_days($today, 365);
} else {
$from = add_days($today, -30);
$to = add_days($today, (int) $range);
}
$rows = [];
$hasEmployee = $scope > 0 || ($user['role'] ?? '') === 'admin';
if ($hasEmployee) {
$rows = reminder_list($from, $to, $employeeFilter, $showDone);
}
$groups = [];
foreach ($rows as $row) {
$groups[$row['due_date']][] = $row;
}
$employees = employees_all();
render_page('reminders', [
'rows' => $rows,
'groups' => $groups,
'range' => $range,
'employeeFilter' => $employeeFilter,
'showDone' => $showDone,
'employees' => $employees,
'hasEmployee' => $hasEmployee,
'isAdmin' => ($user['role'] ?? '') === 'admin',
'today' => $today,
'mailEnabled' => (bool) config('app.mail_enabled', false),
'pushEnabled' => push_is_configured(),
], 'Erinnerungen');
}
function page_reminder_done(array $user): void
{
require_post();
$bookingId = (int) post_string('booking_id');
$kind = post_string('kind');
$done = post_string('done') === '1';
$booking = booking_find($bookingId);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
$allowed = ($user['role'] ?? '') === 'admin'
|| (auth_employee_id($user) > 0 && (int) $booking['employee_id'] === auth_employee_id($user));
if (!$allowed) {
abort_page(403, 'Diese Erinnerung gehört zu einem anderen Mitarbeiter.');
}
if (!reminder_done_set($bookingId, $kind, $done, (int) $user['id'])) {
abort_page(422, 'Erinnerung nicht gefunden.');
}
flash('success', $done ? 'Erinnerung als erledigt markiert.' : 'Erinnerung wieder geöffnet.');
$back = safe_next(post_string('return_to'), '/reminders');
redirect($back);
}
/* ------------------------------------------------------------------ Konto */
function page_account(array $user, string $method): void
{
$errors = [];
if ($method === 'POST') {
require_post();
$current = (string) ($_POST['current_password'] ?? '');
$new = (string) ($_POST['new_password'] ?? '');
$repeat = (string) ($_POST['repeat_password'] ?? '');
if (!password_verify($current, (string) $user['password_hash'])) {
$errors['current_password'] = 'Das aktuelle Passwort stimmt nicht.';
}
if (mb_strlen($new) < 8) {
$errors['new_password'] = 'Das neue Passwort muss mindestens 8 Zeichen haben.';
}
if ($new !== $repeat) {
$errors['repeat_password'] = 'Die beiden neuen Passwörter stimmen nicht überein.';
}
if (!$errors) {
$pdo = db();
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare('UPDATE users SET password_hash = ?, password_changed_at = ?, updated_at = ?,
must_change_password = 0, auth_epoch = auth_epoch + 1 WHERE id = ?');
$stmt->execute([hash_password($new), utc_now(), utc_now(), (int) $user['id']]);
$newEpoch = (int) $pdo->query('SELECT auth_epoch FROM users WHERE id = ' . (int) $user['id'])->fetchColumn();
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([(int) $user['id']]);
$pdo->commit();
$_SESSION['epoch'] = $newEpoch;
$_SESSION['csrf'] = bin2hex(random_bytes(32));
flash('success', 'Das Passwort wurde geändert. Andere Geräte müssen sich neu anmelden.');
redirect('/');
} catch (Throwable $error) {
$pdo->rollBack();
throw $error;
}
}
http_response_code(422);
}
render_page('account', [
'errors' => $errors,
'employee' => auth_employee_id($user) > 0 ? employee_find(auth_employee_id($user)) : null,
'pushEnabled' => push_is_configured(),
'pushEligible' => auth_employee_id($user) > 0,
'pushPublicKey' => WebPush::publicKey(),
'pushDeviceCount' => push_subscription_count((int) $user['id']),
'pushSubscribeUrl' => url('/push/subscribe'),
'pushUnsubscribeUrl' => url('/push/unsubscribe'),
'pushTestUrl' => url('/push/test'),
], 'Mein Konto');
}
/* ------------------------------------------------------------- Web-Push */
function json_body(): array
{
$raw = file_get_contents('php://input', false, null, 0, 20000);
if (is_string($raw) && $raw !== '') {
$data = json_decode($raw, true);
if (is_array($data)) {
return $data;
}
}
return $_POST;
}
function page_push_subscribe(array $user): void
{
require_post();
$body = json_body();
$endpoint = trim((string) ($body['endpoint'] ?? ''));
$keys = is_array($body['keys'] ?? null) ? $body['keys'] : [];
$p256dh = trim((string) ($keys['p256dh'] ?? ($body['p256dh'] ?? '')));
$auth = trim((string) ($keys['auth'] ?? ($body['auth'] ?? '')));
if (!WebPush::isValidEndpoint($endpoint) || !WebPush::isValidKeyMaterial($p256dh, $auth)) {
json_response(['ok' => false, 'error' => 'Ungültiges Push-Abo.'], 422);
}
$saved = push_subscription_save(
(int) $user['id'],
$endpoint,
$p256dh,
$auth,
(string) ($_SERVER['HTTP_USER_AGENT'] ?? '')
);
if (!$saved) {
json_response(['ok' => false, 'error' => 'Abo konnte nicht gespeichert werden.'], 500);
}
json_response(['ok' => true, 'count' => push_subscription_count((int) $user['id'])]);
}
function page_push_unsubscribe(array $user): void
{
require_post();
$body = json_body();
$endpoint = trim((string) ($body['endpoint'] ?? ''));
if ($endpoint === '') {
json_response(['ok' => false, 'error' => 'Geräte-Endpunkt fehlt.'], 422);
}
$removed = push_subscription_delete((int) $user['id'], $endpoint);
json_response(['ok' => true, 'removed' => $removed, 'count' => push_subscription_count((int) $user['id'])]);
}
function page_push_test(array $user): void
{
require_post();
$body = json_body();
$endpoint = trim((string) ($body['endpoint'] ?? ''));
$last = (int) ($_SESSION['push_test_at'] ?? 0);
if (time() - $last < 5) {
json_response(['ok' => false, 'error' => 'Bitte kurz warten, bevor erneut getestet wird.'], 429);
}
if (!push_subscription_for_user_endpoint((int) $user['id'], $endpoint)) {
json_response(['ok' => false, 'error' => 'Dieses Gerät ist nicht für Erinnerungen angemeldet.'], 409);
}
$_SESSION['push_test_at'] = time();
$result = push_send_test((int) $user['id'], $endpoint);
if ($result['sent'] > 0) {
json_response(['ok' => true]);
}
if ($result['removed'] > 0) {
json_response(['ok' => false, 'error' => 'Das Abo ist abgelaufen. Bitte Erinnerungen aus- und wieder einschalten.'], 410);
}
json_response(['ok' => false, 'error' => 'Push-Dienst nicht erreichbar.'], 502);
}