drink-it-cold/app/pages.php

1771 lines
64 KiB
PHP
Raw Normal View History

<?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 === '/cron/backup') {
cron_backup();
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 (in_array($path, ['/impressum', '/datenschutz', '/agb'], true)) {
legal_page(substr($path, 1));
return;
}
if ($path === '/migrate') {
cron_migrate();
return;
}
if ($path === '/anfrage') {
page_inquiry($method);
return;
}
if ($path === '/abmelden') {
page_unsubscribe($method);
return;
}
if (preg_match('#^/unterschrift/([a-f0-9]{64})/pdf$#', $path, $m) === 1) {
page_signature_public_pdf($m[1]);
return;
}
if (preg_match('#^/unterschrift/([a-f0-9]{64})$#', $path, $m) === 1) {
page_signature_public($method, $m[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 === '/' || $path === '/dashboard') {
page_dashboard($user);
return;
}
if ($path === '/calendar') {
page_calendar($user);
return;
}
if ($path === '/availability') {
page_availability($user);
return;
}
if ($path === '/absences') {
page_absences($user, $method);
return;
}
if (preg_match('#^/absences/(\d+)/delete$#', $path, $m) === 1) {
page_absence_delete($user, (int) $m[1]);
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 (preg_match('#^/bookings/(\d+)/documents$#', $path, $m) === 1) {
page_booking_documents_create($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/documents/rechnung$#', $path, $m) === 1) {
page_booking_document_invoice_upload($user, (int) $m[1]);
return;
}
if (preg_match('#^/bookings/(\d+)/documents/(\d+)$#', $path, $m) === 1) {
page_booking_document_file($user, (int) $m[1], (int) $m[2]);
return;
}
if (preg_match('#^/bookings/(\d+)/documents/(\d+)/(sign|request|mail|delete)$#', $path, $m) === 1) {
page_booking_document_action($user, $method, (int) $m[1], (int) $m[2], (string) $m[3]);
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 === '/anleitung') {
page_manual($user);
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, %d Buchungsunterlagen entfernt%s.\n",
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
$cleanup['reminder_mail_log'],
$cleanup['reminder_push_log'], $cleanup['booking_documents'],
$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";
}
}
/**
* Sicherung per HTTP anstoßen (Token = app.cron_token).
*
* Auf dem Webhosting gibt es kein SSH/Cron für CLI-Skripte; dieser Aufruf
* ersetzt `php tools/backup.php create`.
*/
function cron_backup(): void
{
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
$expected = trim((string) config('app.cron_token', ''));
$token = query_string('token');
if ($expected === '' || $token === '' || !hash_equals($expected, $token)) {
http_response_code(403);
echo "Kein Zugriff.\n";
return;
}
try {
$backup = backup_create('cron');
$rotation = backup_rotate();
echo sprintf(
"Sicherung %s erstellt: %d Zeilen, %d Dateien, %d Byte.\n",
$backup['name'],
$backup['rows'],
$backup['files'],
$backup['size']
);
echo $rotation['deleted'] === []
? "Aufgeräumt: nichts zu löschen.\n"
: 'Aufgeräumt: ' . implode(', ', $rotation['deleted']) . " entfernt.\n";
} catch (Throwable $error) {
error_log('Cron-Sicherung: ' . $error->getMessage());
http_response_code(500);
echo "Fehler: Sicherung konnte nicht erstellt werden.\n";
}
}
/**
* Schema-Migrationen per HTTP anstoßen (Token = app.cron_token).
*
* Auf dem Webhosting gibt es kein SSH; nach einem Sync ruft das Deployment
* diese Route auf, damit neue Migrationen auf der Live-DB landen.
*/
function cron_migrate(): void
{
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
$expected = trim((string) config('app.cron_token', ''));
$token = query_string('token');
if ($expected === '' || $token === '' || !hash_equals($expected, $token)) {
http_response_code(403);
echo "Kein Zugriff.\n";
return;
}
try {
$result = migrations_run();
echo $result['applied'] === []
? "Keine ausstehenden Migrationen.\n"
: 'Migrationen angewendet: ' . implode(', ', $result['applied']) . "\n";
} catch (Throwable $error) {
error_log('Migration: ' . $error->getMessage());
http_response_code(500);
echo 'Fehler: ' . $error->getMessage() . "\n";
}
}
/* --------------------------------------------------------------- Anmeldung */
function page_login(string $method): void
{
// Nur der Aufruf der Maske wird bei bestehender Sitzung umgeleitet. Ein
// POST muss immer verarbeitet werden: Sonst würde eine Anmeldung mit
// anderen Zugangsdaten im selben Browser stillschweigend verpuffen und
// man bliebe im alten Konto.
if ($method !== 'POST' && auth_user() !== null) {
redirect('/dashboard');
}
$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'), '/dashboard');
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'), '/dashboard'),
], '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);
// Der Link gehört zum eingeladenen Konto: Eine im Browser noch
// bestehende Sitzung (typisch: der Admin hat den Link im eigenen
// Browser geöffnet) wird beendet, damit die anschließende
// Anmeldung wirklich beim neuen Konto landet.
auth_forget_remember();
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, booking_scope_employee($user));
$employeeScope = booking_scope_employee($user);
$reminderScope = reminder_scope_employee($user);
// Übersicht: strikt auf den zugeordneten Mitarbeiter begrenzt – auch für
// Admins. Ohne Zuordnung bleibt der Block leer; alle Erinnerungen gibt es
// weiterhin unter /reminders.
$remindersWithoutEmployee = $reminderScope === 0;
$allReminders = $reminderScope > 0
? reminder_list(add_days($today, -30), add_days($today, 7), $reminderScope, false)
: [];
$openReminderCount = count($allReminders);
$reminders = array_slice($allReminders, 0, 6);
$upcoming = array_slice($upcoming, 0, 10);
$roadmap = [];
foreach ($trailers as $trailer) {
$bookings = $byTrailer[(int) $trailer['id']] ?? [];
// Frei bis: Tag vor dem nächsten Mietbeginn. Ohne Folge-Buchung bleibt
// der Anhänger dauerhaft frei (null).
$freeUntil = null;
if (!$bookings) {
$next = next_booking_start((int) $trailer['id'], $today);
if ($next !== null) {
$freeUntil = add_days((string) $next['start_date'], -1);
}
}
$roadmap[] = [
'trailer' => $trailer,
'bookings' => $bookings,
'free_until' => $freeUntil,
];
}
$weekEnd = add_days($today, 7);
// Übergaben und Rücknahmen der nächsten Woche – jeweils beim zuständigen
// Mitarbeiter gezählt (Rücknahme ggf. beim abweichend zugewiesenen).
$handoverCount = handover_count($today, $weekEnd, $employeeScope);
render_page('dashboard', [
'today' => $today,
'trailers' => $trailers,
'roadmap' => $roadmap,
'upcoming' => $upcoming,
'reminders' => $reminders,
'openReminderCount' => $openReminderCount,
'handoverCount' => $handoverCount,
'employeeScope' => $employeeScope,
'reminderScope' => $reminderScope,
'remindersWithoutEmployee' => $remindersWithoutEmployee,
], 'Ü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', 'weeks');
if (!in_array($view, ['day', 'weeks', 'month'], true)) {
$view = 'weeks';
}
$date = query_string('date');
if (!valid_date($date)) {
$date = today_iso();
}
$employeeId = query_int('employee');
$showCancelled = query_string('cancelled') === '1';
if ($view === 'day') {
$focusFrom = $date;
$from = $to = $date;
} elseif ($view === 'month') {
$focusFrom = month_start($date);
$from = $focusFrom;
$to = month_end($date);
if (client_is_mobile()) {
// Smartphone: auch im Monat ± 2 Monate rendern, damit sich der
// Kalender seitlich durchwischen lässt.
$from = date_obj($focusFrom)->modify('-' . CALENDAR_MOBILE_MONTHS . ' months')->format('Y-m-d');
$to = date_obj($focusFrom)->modify('+' . (CALENDAR_MOBILE_MONTHS + 1) . ' months')->modify('-1 day')->format('Y-m-d');
}
} else {
// Vier Kalenderwochen ab dem Montag der Woche, in der $date liegt.
$focusFrom = week_start($date);
$from = $focusFrom;
$to = add_days($focusFrom, CALENDAR_WEEKS * 7 - 1);
if (client_is_mobile()) {
// Smartphone: mehr Wochen rendern, damit sich der Kalender nach
// links und rechts wischen lässt (± 2 Monate um die Startwoche).
$from = week_start(date_obj($date)->modify('-' . CALENDAR_MOBILE_MONTHS . ' months')->format('Y-m-d'));
$later = date_obj($date)->modify('+' . CALENDAR_MOBILE_MONTHS . ' months')->format('Y-m-d');
$to = add_days(week_start($later), 6);
}
}
$bookings = booking_list($from, $to, $showCancelled, $employeeId);
// Abwesenheiten im Zeitraum: eigene Zeilen + Kollisionsmarkierung an Buchungen.
$absences = absence_list($from, $to);
$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_week_start' => date_obj($cursor)->format('N') === '1',
'is_first_of_month' => date_obj($cursor)->format('j') === '1',
'holiday' => holiday_name($cursor),
];
$cursor = add_days($cursor, 1);
}
$barBase = ['day' => 76, 'weeks' => 34, 'month' => 34][$view];
$rowMin = ['day' => 104, 'weeks' => 44, '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),
'absent' => booking_absent_hits($booking, $absences) !== [],
];
}
// Zeigt ein Balken zusätzlich den abweichenden Rücknahme-Mitarbeiter,
// braucht er eine Zeile mehr – die Anhängerzeile wächst entsprechend.
$extraMeta = false;
foreach ($laneInfo['bookings'] as $booking) {
if (booking_has_separate_return($booking)) {
$extraMeta = true;
break;
}
}
$rows[] = [
'trailer' => $trailer,
'lanes' => $lanes,
'bars' => $bars,
'height' => max($rowMin, $barBase * $lanes + 16 + ($extraMeta ? 24 : 0)),
];
}
$prevDate = $nextDate = $date;
if ($view === 'day') {
$prevDate = add_days($date, -1);
$nextDate = add_days($date, 1);
} elseif ($view === 'weeks') {
// Wochenweise blättern: der 4-Wochen-Block wandert um eine Kalenderwoche.
$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 === 'weeks') {
$title = 'KW ' . date_obj($focusFrom)->format('W') . '–'
. date_obj(add_days($focusFrom, CALENDAR_WEEKS * 7 - 1))->format('W')
. ' · ' . fmt_date_range($focusFrom, add_days($focusFrom, CALENDAR_WEEKS * 7 - 1));
} else {
$title = fmt_month($date);
}
$employees = employees_all();
// Abwesenheiten als eigene Zeilen unterhalb der Anhänger.
$absencesByEmployee = [];
foreach ($absences as $absence) {
$absencesByEmployee[(int) $absence['employee_id']][] = $absence;
}
$absenceRows = [];
foreach ($absencesByEmployee as $employeeAbsences) {
$laneInfo = calendar_lanes($employeeAbsences);
$bars = [];
foreach ($laneInfo['bookings'] as $absence) {
$bars[] = [
'absence' => $absence,
'geo' => calendar_geometry($absence, $from, $to, $laneInfo['lanes']),
];
}
$absenceRows[] = [
'employee_name' => (string) $employeeAbsences[0]['employee_name'],
'employee_id' => (int) $employeeAbsences[0]['employee_id'],
'bars' => $bars,
'count' => count($employeeAbsences),
'height' => max($rowMin, $barBase * $laneInfo['lanes'] + 16),
];
}
render_page('calendar', [
'view' => $view,
'date' => $date,
'from' => $from,
'to' => $to,
'days' => $days,
'rows' => $rows,
'calTitle' => $title,
'focusFrom' => $focusFrom,
'prevDate' => $prevDate,
'nextDate' => $nextDate,
'today' => today_iso(),
'employeeId' => $employeeId,
'showCancelled' => $showCancelled,
'employees' => $employees,
'bookingCount' => count($bookings),
'absences' => $absences,
'absenceRows' => $absenceRows,
'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++;
// Wechseltage (Rückgabe am Übergabetag bzw. Übergabe am
// Rückgabetag) sind erlaubt, werden zur internen Klärung aber
// ausgewiesen.
$groups[$key][] = [
'trailer' => $trailer,
'edges' => booking_edge_overlaps((int) $trailer['id'], $from, $to),
];
}
}
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);
$currentReturnEmployee = (int) ($values['return_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
|| (int) $e['id'] === $currentReturnEmployee
));
return [
'booking' => $booking,
'values' => $values,
'errors' => $errors,
'trailers' => $trailerOptions,
'employees' => $employeeOptions,
'user' => $user,
'isEdit' => $booking !== null,
'canEditBilling' => auth_can_manage($user),
];
}
function form_values_from_input(array $data): array
{
return [
'trailer_id' => (int) $data['trailer_id'],
'employee_id' => (int) $data['employee_id'],
'return_employee_id' => (int) ($data['return_employee_id'] ?? 0),
'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'],
'note' => (string) ($data['note'] ?? ''),
];
}
function page_booking_new(array $user, string $method): void
{
if (!auth_can_create_booking($user)) {
abort_page(403, 'Nur Administratoren dürfen Buchungen anlegen.');
}
$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,
'return_employee_id' => 0,
'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' => '',
'note' => '',
];
$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
{
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Bitte anmelden, um Buchungen zu bearbeiten.');
}
$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'],
'return_employee_id' => (int) ($booking['return_employee_id'] ?? 0),
'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'],
'note' => (string) ($booking['note'] ?? ''),
];
$errors = [];
// Beträge und Rechnungsdaten darf nur ein Admin ändern; sie werden bei
// allen anderen aus der bestehenden Buchung übernommen – auch dann, wenn
// sie manipuliert mitgeschickt wurden.
$canEditBilling = auth_can_manage($user);
if ($method === 'POST') {
require_post();
$data = booking_input($_POST);
if (!$canEditBilling) {
$data['deposit_cents'] = (int) $booking['deposit_cents'];
$data['rent_cents'] = (int) $booking['rent_cents'];
$data['delivery_cents'] = (int) $booking['delivery_cents'];
$data['total_cents'] = (int) $booking['total_cents'];
$data['invoice'] = (int) $booking['invoice'];
$data['invoice_no'] = (string) ($booking['invoice_no'] ?? '');
}
$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,
// Bearbeiten (Termine, Zeiten, Mitarbeiter, Bemerkung) dürfen alle
// angemeldeten Mitarbeiter; Stornieren/Löschen bleibt beim Admin.
'canEdit' => auth_can_edit_booking($user),
'canCancel' => auth_can_cancel_booking($user),
'canEditBilling' => $isAdmin,
'documents' => documents_for_booking((int) $booking['id']),
'documentVariants' => document_variants(),
'documentVariantDefault' => document_variant_default($booking),
'canManageDocuments' => auth_can_edit_booking($user),
'canDeleteDocuments' => $isAdmin,
'documentsMailEnabled' => mail_is_enabled(),
'documentsRetentionDays' => max(0, (int) config('app.document_retention_days', 30)),
];
}
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();
if (!auth_can_cancel_booking($user)) {
abort_page(403, 'Nur Administratoren dürfen Buchungen stornieren.');
}
$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();
if (!auth_can_cancel_booking($user)) {
abort_page(403, 'Nur Administratoren dürfen Buchungen wiederherstellen.');
}
$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 (!auth_can_manage($user)) {
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?date=' . $booking['start_date']);
}
function page_booking_move(array $user, int $id): void
{
require_post();
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Bitte anmelden, um Buchungen zu verschieben.');
}
$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);
}
/* ------------------------------------------------------- Buchungsunterlagen */
function booking_or_404(int $id): array
{
$booking = booking_find($id);
if (!$booking) {
abort_page(404, 'Buchung nicht gefunden.');
}
return $booking;
}
/** Erzeugt Mietvertrag oder Auftragsbestätigung in der gewählten Variante. */
function page_booking_documents_create(array $user, int $id): void
{
require_post();
$booking = booking_or_404($id);
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
}
$kind = post_string('kind');
$variant = post_string('variant');
if (!in_array($kind, [DOCUMENT_KIND_CONTRACT, DOCUMENT_KIND_CONFIRMATION], true)) {
flash('error', 'Unbekannte Unterlagen-Art.');
redirect('/bookings/' . $id . '#unterlagen');
}
try {
document_create($booking, $kind, $variant, (int) $user['id']);
flash('success', document_kind_label($kind) . ' erstellt – zum Drucken öffnen oder direkt versenden.');
} catch (Throwable $error) {
flash('error', $error->getMessage());
}
redirect('/bookings/' . $id . '#unterlagen');
}
/** Liefert die PDF-Datei einer Unterlage aus (nur angemeldet, nie öffentlich). */
function page_booking_document_file(array $user, int $bookingId, int $docId): void
{
$doc = document_find($docId);
if (!$doc || (int) $doc['booking_id'] !== $bookingId) {
abort_page(404, 'Unterlage nicht gefunden.');
}
$path = document_path($doc);
if (!is_file($path)) {
abort_page(404, 'Die Datei ist nicht mehr vorhanden.');
}
$download = query_string('download') === '1';
$name = (string) preg_replace('/[\r\n"]+/', '', (string) $doc['file_name']);
header('Content-Type: ' . (string) $doc['mime_type']);
header('Content-Length: ' . (string) filesize($path));
header('Content-Disposition: ' . ($download ? 'attachment' : 'inline') . '; filename="' . $name . '"');
header('Cache-Control: private, no-store');
readfile($path);
exit;
}
/** Unterschrift auf dem Tablet, Mailversand und Löschen einer Unterlage. */
function page_booking_document_action(array $user, string $method, int $bookingId, int $docId, string $action): void
{
$booking = booking_or_404($bookingId);
$doc = document_find($docId);
if (!$doc || (int) $doc['booking_id'] !== $bookingId) {
abort_page(404, 'Unterlage nicht gefunden.');
}
if ($action === 'sign') {
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
}
if ($method === 'GET') {
render_standalone('document_sign', [
'booking' => $booking,
'doc' => $doc,
'pageTitle' => 'Unterschrift Mietvertrag',
], 'Unterschrift · ' . $booking['customer_name']);
return;
}
require_post();
try {
document_save_signature($booking, $doc, post_string('signature'), (int) $user['id'], 'tablet');
$mailUrl = '';
if (mail_is_enabled() && filter_var((string) $booking['email'], FILTER_VALIDATE_EMAIL) !== false) {
$mailUrl = '/bookings/' . $bookingId . '/documents/' . $docId . '/mail';
}
render_standalone('document_sign_done', [
'booking' => $booking,
'doc' => document_find($docId) ?? $doc,
'mailed' => false,
'backUrl' => '/bookings/' . $bookingId . '#unterlagen',
'mailUrl' => $mailUrl,
], 'Unterschrift gespeichert');
return;
} catch (Throwable $error) {
flash('error', $error->getMessage());
}
redirect('/bookings/' . $bookingId . '#unterlagen');
}
require_post();
if ($action === 'request') {
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
}
try {
$doc = document_request_signature($doc);
$link = document_sign_link($doc);
if (mail_is_enabled()) {
document_mail_signature_request($booking, $doc)
? flash('success', 'Unterschriftslink an ' . $booking['email'] . ' gesendet.')
: flash('error', 'Die E-Mail konnte nicht verschickt werden – Link bitte kopieren.');
} else {
flash('info', 'E-Mail-Versand ist aus. Unterschriftslink zum Kopieren: ' . $link);
}
} catch (Throwable $error) {
flash('error', $error->getMessage());
}
redirect('/bookings/' . $bookingId . '#unterlagen');
}
if ($action === 'mail') {
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
}
try {
$sent = document_mail_to_customer($booking, $doc);
$sent
? flash('success', document_kind_label((string) $doc['kind']) . ' an ' . $booking['email'] . ' gesendet.')
: flash('error', 'Die E-Mail konnte nicht verschickt werden.');
} catch (Throwable $error) {
flash('error', $error->getMessage());
}
redirect('/bookings/' . $bookingId . '#unterlagen');
}
if ($action === 'delete') {
if (!auth_can_manage($user)) {
abort_page(403, 'Unterlagen darf nur der Admin löschen.');
}
$kindLabel = document_kind_label((string) $doc['kind']);
$wasSigned = trim((string) ($doc['signed_at'] ?? '')) !== '';
document_delete($docId);
error_log(sprintf(
'Unterlage gelöscht: %s (ID %d, Buchung #%d) durch Benutzer %d%s',
$kindLabel,
$docId,
$bookingId,
(int) $user['id'],
$wasSigned ? ' – war unterschrieben, Unterschrift mit entfernt' : ''
));
flash('success', $kindLabel . ' gelöscht' . ($wasSigned ? ' – die Unterschrift wurde mit entfernt' : '') . '.');
redirect('/bookings/' . $bookingId . '#unterlagen');
}
abort_page(404, 'Diese Aktion gibt es nicht.');
}
/** Rechnung (PDF aus Lexware) zur Buchung hochladen. */
function page_booking_document_invoice_upload(array $user, int $id): void
{
require_post();
$booking = booking_or_404($id);
if (!auth_can_edit_booking($user)) {
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
}
try {
document_upload_invoice($booking, (array) ($_FILES['invoice'] ?? []), (int) $user['id']);
flash('success', 'Rechnung abgelegt.');
} catch (Throwable $error) {
flash('error', $error->getMessage());
}
redirect('/bookings/' . $id . '#unterlagen');
}
/**
* Öffentliche Unterschriftsseite des Kunden (/unterschrift/<token>).
*
* Kein Login: der Token im Link ist der Ausweis. Nach dem Unterschreiben wird
* er entwertet und der unterschriebene Vertrag per E-Mail verschickt.
*/
function page_signature_public(string $method, string $token): void
{
$doc = document_find_by_sign_token($token);
if (!$doc) {
abort_page(404, 'Dieser Unterschriftslink ist nicht mehr gültig. Bitte den Betrieb um einen neuen Link bitten.');
}
$booking = booking_find((int) $doc['booking_id']);
if (!$booking) {
abort_page(404, 'Zu diesem Link gibt es keine Buchung mehr.');
}
$error = '';
if ($method === 'POST') {
if (!csrf_valid()) {
$error = 'Die Sitzung ist abgelaufen. Bitte die Seite neu laden und erneut unterschreiben.';
} else {
try {
$result = document_sign_by_customer($booking, $doc, post_string('signature'));
render_standalone('document_sign_done', [
'booking' => $booking,
'doc' => $result['doc'],
'mailed' => $result['mailed'],
'backUrl' => '',
'mailUrl' => '',
], 'Unterschrift gespeichert');
return;
} catch (Throwable $e) {
$error = $e->getMessage();
}
}
}
render_standalone('document_sign_customer', [
'booking' => $booking,
'doc' => $doc,
'token' => $token,
'error' => $error,
], 'Mietvertrag unterschreiben');
}
/** Vertrag als PDF zur Ansicht (nur mit gültigem Unterschriftslink). */
function page_signature_public_pdf(string $token): void
{
$doc = document_find_by_sign_token($token);
if (!$doc) {
abort_page(404, 'Dieser Unterschriftslink ist nicht mehr gültig.');
}
$path = document_path($doc);
if (!is_file($path)) {
abort_page(404, 'Die Datei ist nicht mehr vorhanden.');
}
header('Content-Type: ' . (string) $doc['mime_type']);
header('Content-Length: ' . (string) filesize($path));
header('Content-Disposition: inline; filename="' . (string) preg_replace('/[\r\n\"]+/', '', (string) $doc['file_name']) . '"');
header('Cache-Control: private, no-store');
readfile($path);
exit;
}
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';
}
// Sichtbarkeit: zugeordneter Mitarbeiter ist maßgeblich (auch für Admins).
// Admins können über "Alle" bewusst auf die Gesamtsicht umschalten und
// dürfen dann nach Mitarbeiter filtern.
$scope = reminder_scope_employee($user);
$isAdmin = ($user['role'] ?? '') === 'admin';
$showAll = $isAdmin && query_string('all') === '1';
$canChooseEmployee = $isAdmin && ($scope === 0 || $showAll);
$employeeFilter = (!$showAll && $scope > 0) ? $scope : ($isAdmin ? query_int('employee') : 0);
$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);
}
$hasEmployee = $scope > 0 || $isAdmin;
$rows = reminder_list_for_user($user, $from, $to, $showDone, $employeeFilter, $showAll);
if ($showDone) {
// Haken "Erledigte anzeigen": ausschließlich erledigte Erinnerungen.
$rows = array_values(array_filter($rows, static fn (array $row): bool => (bool) $row['done']));
}
$groups = [];
foreach ($rows as $row) {
$groups[$row['due_date']][] = $row;
}
// Offene Erinnerungen: ältester Fälligkeitstag oben (aufsteigend).
// Erledigte Ansicht: jüngster Fälligkeitstag oben (absteigend).
if ($showDone) {
krsort($groups, SORT_STRING);
}
$employees = employees_all();
render_page('reminders', [
'rows' => $rows,
'groups' => $groups,
'range' => $range,
'employeeFilter' => $employeeFilter,
'showDone' => $showDone,
'employees' => $employees,
'hasEmployee' => $hasEmployee,
'hasOwnEmployee' => $scope > 0,
'canChooseEmployee' => $canChooseEmployee,
'showAll' => $showAll,
'isAdmin' => $isAdmin,
'today' => $today,
'mailEnabled' => (bool) config('app.mail_enabled', false),
'pushEnabled' => push_is_configured(),
], 'Erinnerungen');
}
/* ------------------------------------------------------- Abwesenheiten */
function page_absences(array $user, string $method): void
{
$isAdmin = ($user['role'] ?? '') === 'admin';
$ownEmployeeId = auth_employee_id($user);
$employees = employees_all(false);
$period = query_string('period', 'weeks');
if (!in_array($period, ['weeks', 'month', 'next_month', 'all'], true)) {
$period = 'weeks';
}
$today = today_iso();
$date = query_string('date');
if (!valid_date($date)) {
$date = query_string('from') !== '' && valid_date(query_string('from')) ? query_string('from') : $today;
}
// Mitarbeiterfilter: 0 = alle, sonst genau eine Person.
$employeeFilter = query_int('employee');
if ($employeeFilter > 0 && !array_filter($employees, static fn (array $e): bool => (int) $e['id'] === $employeeFilter)) {
$employeeFilter = 0;
}
if ($period === 'month') {
$from = month_start($date);
$to = month_end($date);
$anchor = $from;
} elseif ($period === 'next_month') {
// Kunde: „den nächsten Monat oder alle anzeigen lassen“.
$anchor = date_obj(month_start($date))->modify('+1 month')->format('Y-m-d');
$from = month_start($anchor);
$to = month_end($anchor);
} elseif ($period === 'all') {
[$firstDay, $lastDay] = absence_bounds();
$anchor = $today;
$from = $firstDay !== '' ? min($firstDay, $today) : $today;
$to = $lastDay !== '' ? max($lastDay, $today) : $today;
} else {
$from = week_start($date);
$to = add_days($from, CALENDAR_WEEKS * 7 - 1);
$anchor = $from;
}
$editId = query_int('edit');
$editing = $editId > 0 ? absence_find($editId) : null;
if ($editing && !$isAdmin && (int) $editing['employee_id'] !== $ownEmployeeId) {
abort_page(403, 'Diese Abwesenheit gehört zu einem anderen Mitarbeiter.');
}
$defaultStart = $period === 'all' ? $today : $from;
$prefillEnd = query_string('to');
if (!valid_date($prefillEnd) || $prefillEnd < $defaultStart) {
$prefillEnd = $defaultStart;
}
$values = [
'id' => $editing ? (int) $editing['id'] : 0,
'employee_id' => $editing ? (int) $editing['employee_id'] : ($isAdmin ? ($employeeFilter ?: 0) : $ownEmployeeId),
'start_date' => $editing ? (string) $editing['start_date'] : $defaultStart,
'end_date' => $editing ? (string) $editing['end_date'] : $prefillEnd,
'note' => $editing ? (string) $editing['note'] : '',
];
$errors = [];
if ($method === 'POST') {
require_post();
$values = [
'id' => (int) post_string('id'),
'employee_id' => $isAdmin ? (int) post_string('employee_id') : $ownEmployeeId,
'start_date' => post_string('start_date'),
'end_date' => post_string('end_date'),
'note' => trim(post_string('note')),
];
$errors = absence_validate($values);
if (!$isAdmin && $values['employee_id'] !== $ownEmployeeId) {
abort_page(403, 'Abwesenheiten anderer Mitarbeiter dürfen nur Admins pflegen.');
}
if (!$errors) {
$id = absence_save($values['id'] > 0 ? $values['id'] : null, $values, (int) $user['id']);
$affected = $values['id'] > 0 ? booking_absence_conflict($values['employee_id'], $values['start_date'], $values['end_date']) : null;
$message = 'Abwesenheit gespeichert.';
if ($affected) {
$message .= ' Achtung: Es gibt bereits Buchungen in diesem Zeitraum – bitte Mitarbeiter tauschen.';
}
flash('success', $message);
redirect('/absences?date=' . rawurlencode((string) $values['start_date'])
. '&period=' . rawurlencode($period)
. ($employeeFilter > 0 ? '&employee=' . $employeeFilter : '')
. '#abwesenheit-' . $id);
}
http_response_code(422);
}
$rows = absence_list($from, $to, $employeeFilter);
$byEmployee = [];
foreach ($employees as $employee) {
$byEmployee[(int) $employee['id']] = [
'employee' => $employee,
'rows' => [],
];
}
foreach ($rows as $row) {
$byEmployee[(int) $row['employee_id']]['rows'][] = $row;
}
// Buchungen im Zeitraum, die mit einer Abwesenheit kollidieren.
$conflicts = [];
foreach ($rows as $row) {
$windowStart = add_days((string) $row['start_date'], -BOOKING_LEAD_DAYS);
foreach (booking_list($windowStart, (string) $row['end_date']) as $booking) {
if ($booking['status'] !== 'active') {
continue;
}
if (booking_employee_for_kind($booking, 'start_1') === (int) $row['employee_id']
|| booking_employee_for_kind($booking, 'end_1') === (int) $row['employee_id']) {
$conflicts[(int) $row['id']][] = $booking;
}
}
}
$prevDate = match ($period) {
'month' => date_obj(month_start($anchor))->modify('-1 month')->format('Y-m-d'),
'next_month' => month_start($anchor),
'all' => $anchor,
default => add_days($anchor, -CALENDAR_WEEKS * 7),
};
$nextDate = match ($period) {
'month' => date_obj(month_start($anchor))->modify('+1 month')->format('Y-m-d'),
'next_month' => date_obj(month_start($anchor))->modify('+2 months')->format('Y-m-d'),
'all' => $anchor,
default => add_days($anchor, CALENDAR_WEEKS * 7),
};
render_page('absences', [
'user' => $user,
'isAdmin' => $isAdmin,
'ownEmployeeId' => $ownEmployeeId,
'employees' => $employees,
'byEmployee' => $byEmployee,
'conflicts' => $conflicts,
'values' => $values,
'errors' => $errors,
'period' => $period,
'employeeFilter' => $employeeFilter,
'date' => $date,
'from' => $from,
'to' => $to,
'prevDate' => $prevDate,
'nextDate' => $nextDate,
'today' => $today,
], 'Abwesenheiten');
}
function page_absence_delete(array $user, int $id): void
{
require_post();
$absence = absence_find($id);
if (!$absence) {
abort_page(404, 'Abwesenheit nicht gefunden.');
}
$isAdmin = ($user['role'] ?? '') === 'admin';
if (!$isAdmin && (int) $absence['employee_id'] !== auth_employee_id($user)) {
abort_page(403, 'Abwesenheiten anderer Mitarbeiter dürfen nur Admins löschen.');
}
absence_delete($id);
flash('success', 'Abwesenheit gelöscht.');
redirect(safe_next(post_string('return_to'), '/absences'));
}
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
&& booking_employee_for_kind($booking, $kind) === 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 */
/**
* Bedienungsanleitung für angemeldete Nutzer (Mein Konto → Anleitung).
*/
function page_manual(array $user): void
{
render_page('manual', [
'isAdmin' => ($user['role'] ?? '') === 'admin',
'info' => legal_data(),
], 'Bedienungsanleitung');
}
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('/dashboard');
} 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);
}