2026-11-13 00:35:39 +01:00
< ? 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 ;
}
2026-11-18 22:20:37 +01:00
if ( preg_match ( '#^/invite/([a-f0-9]{64})$#' , $path , $m ) === 1 ) {
page_invite ( $method , $m [ 1 ]);
return ;
}
2026-11-18 20:59:17 +01:00
if ( $path === '/impressum' || $path === '/datenschutz' ) {
legal_page ( substr ( $path , 1 ));
return ;
}
2026-11-13 00:35:39 +01:00
$user = auth_user ();
if ( $user !== null && $user [ 'must_change_password' ] === 1
2026-11-13 01:03:54 +01:00
&& ! in_array ( $path , [ '/account' , '/logout' , '/push/subscribe' , '/push/unsubscribe' , '/push/test' ], true )
2026-11-13 00:35:39 +01:00
) {
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 ;
}
2026-11-18 21:45:10 +01:00
if ( $path === '/availability' ) {
page_availability ( $user );
return ;
}
2026-11-25 22:54:06 +01:00
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 ;
}
2026-11-13 00:35:39 +01:00
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 ;
}
2026-11-13 01:03:54 +01:00
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 ;
}
2026-11-13 00:35:39 +01:00
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
{
2026-11-13 01:03:54 +01:00
header ( 'Content-Type: text/plain; charset=utf-8' );
header ( 'Cache-Control: no-store' );
2026-11-13 00:35:39 +01:00
$expected = ( string ) config ( 'app.cron_token' , '' );
$given = query_string ( 'token' );
if ( $expected === '' || $given === '' || ! hash_equals ( $expected , $given )) {
2026-11-13 01:03:54 +01:00
http_response_code ( 403 );
echo " Forbidden \n " ;
exit ;
}
try {
2026-11-18 20:59:17 +01:00
$cleanup = privacy_cleanup ();
2026-11-13 01:03:54 +01:00
$push = push_dispatch_due ();
$mail = reminder_send_due ();
echo 'Drink it cold – Erinnerungslauf ' . fmt_datetime ( utc_now ()) . " \n " ;
2026-11-18 20:59:17 +01:00
echo sprintf (
2026-11-18 22:20:37 +01:00
" 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' ],
2026-11-18 20:59:17 +01:00
$cleanup [ 'reminder_push_log' ], $cleanup [ 'log_rotated' ] ? ', Fehlerprotokoll rotiert' : ''
);
2026-11-13 01:03:54 +01:00
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 " ;
2026-11-13 00:35:39 +01:00
}
}
/* --------------------------------------------------------------- Anmeldung */
function page_login ( string $method ) : void
{
2026-11-19 11:03:31 +01:00
// 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 ) {
2026-11-13 00:35:39 +01:00
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' );
}
2026-11-18 22:20:37 +01:00
/* --------------------------------------------------------------- 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 );
2026-11-19 11:03:31 +01:00
// 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 ();
2026-11-18 22:20:37 +01:00
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' );
}
2026-11-13 00:35:39 +01:00
/* --------------------------------------------------------------- Ü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 ;
}
2026-11-19 16:17:27 +01:00
$upcoming = upcoming_handovers ( 14 , booking_scope_employee ( $user ));
$employeeScope = booking_scope_employee ( $user );
$reminderScope = reminder_scope_employee ( $user );
2026-11-19 16:31:29 +01:00
// Ü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 )
: [];
2026-11-13 00:35:39 +01:00
$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 );
2026-11-19 11:26:46 +01:00
// Ü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 );
2026-11-13 00:35:39 +01:00
render_page ( 'dashboard' , [
'today' => $today ,
'trailers' => $trailers ,
'roadmap' => $roadmap ,
'upcoming' => $upcoming ,
'reminders' => $reminders ,
'openReminderCount' => $openReminderCount ,
'handoverCount' => $handoverCount ,
'employeeScope' => $employeeScope ,
2026-11-19 16:17:27 +01:00
'reminderScope' => $reminderScope ,
'remindersWithoutEmployee' => $remindersWithoutEmployee ,
2026-11-13 00:35:39 +01:00
], 'Ü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
{
2026-11-25 22:14:39 +01:00
$view = query_string ( 'view' , 'weeks' );
if ( ! in_array ( $view , [ 'day' , 'weeks' , 'month' ], true )) {
$view = 'weeks' ;
2026-11-13 00:35:39 +01:00
}
$date = query_string ( 'date' );
if ( ! valid_date ( $date )) {
$date = today_iso ();
}
$employeeId = query_int ( 'employee' );
$showCancelled = query_string ( 'cancelled' ) === '1' ;
if ( $view === 'day' ) {
2026-11-25 22:41:55 +01:00
$focusFrom = $date ;
2026-11-13 00:35:39 +01:00
$from = $to = $date ;
} elseif ( $view === 'month' ) {
2026-11-25 22:41:55 +01:00
$focusFrom = month_start ( $date );
$from = $focusFrom ;
2026-11-13 00:35:39 +01:00
$to = month_end ( $date );
2026-11-25 22:41:55 +01:00
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' );
}
2026-11-13 00:35:39 +01:00
} else {
2026-11-25 22:14:39 +01:00
// Vier Kalenderwochen ab dem Montag der Woche, in der $date liegt.
2026-11-25 22:41:55 +01:00
$focusFrom = week_start ( $date );
2026-11-25 22:31:46 +01:00
$from = $focusFrom ;
2026-11-25 22:41:55 +01:00
$to = add_days ( $focusFrom , CALENDAR_WEEKS * 7 - 1 );
2026-11-25 22:31:46 +01:00
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 );
}
2026-11-13 00:35:39 +01:00
}
$bookings = booking_list ( $from , $to , $showCancelled , $employeeId );
$byTrailer = [];
foreach ( $bookings as $booking ) {
$byTrailer [( int ) $booking [ 'trailer_id' ]][] = $booking ;
}
2026-11-13 01:19:05 +01:00
// 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' ]])
));
2026-11-13 00:35:39 +01:00
$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 ,
2026-11-25 22:14:39 +01:00
'is_week_start' => date_obj ( $cursor ) -> format ( 'N' ) === '1' ,
2026-11-13 00:35:39 +01:00
'is_first_of_month' => date_obj ( $cursor ) -> format ( 'j' ) === '1' ,
];
$cursor = add_days ( $cursor , 1 );
}
2026-11-25 22:14:39 +01:00
$barBase = [ 'day' => 76 , 'weeks' => 34 , 'month' => 34 ][ $view ];
$rowMin = [ 'day' => 104 , 'weeks' => 44 , 'month' => 44 ][ $view ];
2026-11-13 00:35:39 +01:00
$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 );
2026-11-25 22:14:39 +01:00
} elseif ( $view === 'weeks' ) {
2026-11-25 22:16:02 +01:00
// Wochenweise blättern: der 4-Wochen-Block wandert um eine Kalenderwoche.
$prevDate = add_days ( $date , - 7 );
$nextDate = add_days ( $date , 7 );
2026-11-13 00:35:39 +01:00
} 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 );
2026-11-25 22:14:39 +01:00
} elseif ( $view === 'weeks' ) {
2026-11-25 22:41:55 +01:00
$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 ));
2026-11-13 00:35:39 +01:00
} else {
$title = fmt_month ( $date );
}
$employees = employees_all ();
2026-11-25 22:54:06 +01:00
$absences = absence_list ( $from , $to );
2026-11-13 00:35:39 +01:00
render_page ( 'calendar' , [
'view' => $view ,
'date' => $date ,
'from' => $from ,
'to' => $to ,
'days' => $days ,
'rows' => $rows ,
'calTitle' => $title ,
2026-11-25 22:31:46 +01:00
'focusFrom' => $focusFrom ,
2026-11-13 00:35:39 +01:00
'prevDate' => $prevDate ,
'nextDate' => $nextDate ,
'today' => today_iso (),
'employeeId' => $employeeId ,
'showCancelled' => $showCancelled ,
'employees' => $employees ,
'bookingCount' => count ( $bookings ),
2026-11-25 22:54:06 +01:00
'absences' => $absences ,
2026-11-13 00:35:39 +01:00
'urlFor' => static function ( string $d ) use ( $view , $employeeId , $showCancelled ) : string {
return calendar_url ( $d , $view , $employeeId , $showCancelled );
},
], 'Kalender' );
}
2026-11-18 21:45:10 +01:00
/* ----------------------------------------------------------- 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' => []];
2026-11-18 21:47:11 +01:00
$totals = [ 'trailer' => 0 , 'chest' => 0 ];
2026-11-18 21:45:10 +01:00
$freeCount = 0 ;
if ( $checked && ! $errors ) {
foreach ( trailers_all () as $trailer ) {
2026-11-18 21:47:11 +01:00
$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 ++ ;
2026-11-19 11:26:46 +01:00
// 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 ),
];
2026-11-18 21:45:10 +01:00
}
}
render_page ( 'availability' , [
'from' => $from ,
'to' => $to ,
'checked' => $checked ,
'errors' => $errors ,
'groups' => $groups ,
2026-11-18 21:47:11 +01:00
'totals' => $totals ,
2026-11-18 21:45:10 +01:00
'freeCount' => $freeCount ,
2026-11-18 21:47:11 +01:00
'total' => $totals [ 'trailer' ] + $totals [ 'chest' ],
2026-11-18 21:45:10 +01:00
'user' => $user ,
], 'Verfügbarkeit' );
}
2026-11-13 00:35:39 +01:00
/* --------------------------------------------------------------- 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 );
2026-11-19 11:26:46 +01:00
$currentReturnEmployee = ( int ) ( $values [ 'return_employee_id' ] ? ? 0 );
2026-11-13 00:35:39 +01:00
$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 ,
2026-11-19 11:26:46 +01:00
static fn ( array $e ) : bool => ( int ) $e [ 'active' ] === 1
|| ( int ) $e [ 'id' ] === $currentEmployee
|| ( int ) $e [ 'id' ] === $currentReturnEmployee
2026-11-13 00:35:39 +01:00
));
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' ],
2026-11-19 11:26:46 +01:00
'return_employee_id' => ( int ) ( $data [ 'return_employee_id' ] ? ? 0 ),
2026-11-13 00:35:39 +01:00
'start_date' => ( string ) $data [ 'start_date' ],
'end_date' => ( string ) $data [ 'end_date' ],
2026-11-18 20:59:17 +01:00
'start_time' => ( string ) ( $data [ 'start_time' ] ? ? '' ),
'end_time' => ( string ) ( $data [ 'end_time' ] ? ? '' ),
2026-11-13 00:35:39 +01:00
'deposit' => number_format ( $data [ 'deposit_cents' ] / 100 , 2 , ',' , '' ),
2026-11-18 20:59:17 +01:00
'rent' => number_format ( $data [ 'rent_cents' ] / 100 , 2 , ',' , '' ),
'delivery' => number_format ( $data [ 'delivery_cents' ] / 100 , 2 , ',' , '' ),
2026-11-13 00:35:39 +01:00
'invoice' => ( int ) $data [ 'invoice' ],
2026-11-18 21:27:50 +01:00
'invoice_no' => ( string ) ( $data [ 'invoice_no' ] ? ? '' ),
2026-11-13 00:35:39 +01:00
'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
{
2026-11-19 10:48:32 +01:00
if ( ! auth_can_manage ( $user )) {
abort_page ( 403 , 'Nur Administratoren dürfen Buchungen anlegen.' );
}
2026-11-13 00:35:39 +01:00
$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 ,
2026-11-19 11:26:46 +01:00
'return_employee_id' => 0 ,
2026-11-13 00:35:39 +01:00
'start_date' => $start ,
'end_date' => $end ,
2026-11-18 20:59:17 +01:00
'start_time' => '' ,
'end_time' => '' ,
2026-11-13 00:35:39 +01:00
'deposit' => '' ,
2026-11-18 20:59:17 +01:00
'rent' => '' ,
'delivery' => '' ,
2026-11-13 00:35:39 +01:00
'invoice' => 0 ,
2026-11-18 21:27:50 +01:00
'invoice_no' => '' ,
2026-11-13 00:35:39 +01:00
'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' ],
2026-11-19 11:26:46 +01:00
'return_employee_id' => ( int ) ( $booking [ 'return_employee_id' ] ? ? 0 ),
2026-11-13 00:35:39 +01:00
'start_date' => ( string ) $booking [ 'start_date' ],
'end_date' => ( string ) $booking [ 'end_date' ],
2026-11-18 20:59:17 +01:00
'start_time' => ( string ) ( $booking [ 'start_time' ] ? ? '' ),
'end_time' => ( string ) ( $booking [ 'end_time' ] ? ? '' ),
2026-11-13 00:35:39 +01:00
'deposit' => number_format (( int ) $booking [ 'deposit_cents' ] / 100 , 2 , ',' , '' ),
2026-11-18 20:59:17 +01:00
'rent' => number_format (( int ) $booking [ 'rent_cents' ] / 100 , 2 , ',' , '' ),
'delivery' => number_format (( int ) $booking [ 'delivery_cents' ] / 100 , 2 , ',' , '' ),
2026-11-13 00:35:39 +01:00
'invoice' => ( int ) $booking [ 'invoice' ],
2026-11-18 21:27:50 +01:00
'invoice_no' => ( string ) ( $booking [ 'invoice_no' ] ? ? '' ),
2026-11-13 00:35:39 +01:00
'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' ]]);
2026-11-18 20:59:17 +01:00
$deleteBlocked = ( int ) $booking [ 'invoice' ] === 1 ;
$isAdmin = ( $user [ 'role' ] ? ? '' ) === 'admin' ;
2026-11-13 00:35:39 +01:00
return [
'booking' => $booking ,
'reminders' => $reminders ,
'doneMap' => $done ,
'copyText' => booking_copy_text ( $booking ),
2026-11-18 20:59:17 +01:00
'canDelete' => $isAdmin && ! $deleteBlocked ,
'deleteBlocked' => $deleteBlocked ,
'isAdmin' => $isAdmin ,
2026-11-13 00:35:39 +01:00
];
}
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.' );
}
2026-11-18 20:59:17 +01:00
// 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 );
}
2026-11-13 00:35:39 +01:00
booking_delete ( $id );
flash ( 'success' , 'Buchung von ' . $booking [ 'customer_name' ] . ' wurde endgültig gelöscht.' );
2026-11-25 22:14:39 +01:00
redirect ( '/calendar?date=' . $booking [ 'start_date' ]);
2026-11-13 00:35:39 +01:00
}
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' ;
}
2026-11-19 16:17:27 +01:00
// Sichtbarkeit: zugeordneter Mitarbeiter ist maßgeblich (auch für Admins).
2026-11-25 20:50:26 +01:00
// Admins können über "Alle" bewusst auf die Gesamtsicht umschalten und
// dürfen dann nach Mitarbeiter filtern.
2026-11-13 00:35:39 +01:00
$scope = reminder_scope_employee ( $user );
2026-11-19 16:17:27 +01:00
$isAdmin = ( $user [ 'role' ] ? ? '' ) === 'admin' ;
2026-11-25 20:50:26 +01:00
$showAll = $isAdmin && query_string ( 'all' ) === '1' ;
$canChooseEmployee = $isAdmin && ( $scope === 0 || $showAll );
$employeeFilter = ( ! $showAll && $scope > 0 ) ? $scope : ( $isAdmin ? query_int ( 'employee' ) : 0 );
2026-11-13 00:35:39 +01:00
$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 );
}
2026-11-19 16:17:27 +01:00
$hasEmployee = $scope > 0 || $isAdmin ;
2026-11-25 20:50:26 +01:00
$rows = reminder_list_for_user ( $user , $from , $to , $showDone , $employeeFilter , $showAll );
2026-11-25 20:57:11 +01:00
if ( $showDone ) {
// Haken "Erledigte anzeigen": ausschließlich erledigte Erinnerungen.
$rows = array_values ( array_filter ( $rows , static fn ( array $row ) : bool => ( bool ) $row [ 'done' ]));
}
2026-11-13 00:35:39 +01:00
$groups = [];
foreach ( $rows as $row ) {
$groups [ $row [ 'due_date' ]][] = $row ;
}
2026-11-25 21:09:35 +01:00
// Offene Erinnerungen: ältester Fälligkeitstag oben (aufsteigend).
// Erledigte Ansicht: jüngster Fälligkeitstag oben (absteigend).
if ( $showDone ) {
krsort ( $groups , SORT_STRING );
}
2026-11-13 00:35:39 +01:00
$employees = employees_all ();
render_page ( 'reminders' , [
'rows' => $rows ,
'groups' => $groups ,
'range' => $range ,
'employeeFilter' => $employeeFilter ,
'showDone' => $showDone ,
'employees' => $employees ,
'hasEmployee' => $hasEmployee ,
2026-11-25 20:50:26 +01:00
'hasOwnEmployee' => $scope > 0 ,
2026-11-19 16:17:27 +01:00
'canChooseEmployee' => $canChooseEmployee ,
2026-11-25 20:50:26 +01:00
'showAll' => $showAll ,
2026-11-19 16:17:27 +01:00
'isAdmin' => $isAdmin ,
2026-11-13 00:35:39 +01:00
'today' => $today ,
'mailEnabled' => ( bool ) config ( 'app.mail_enabled' , false ),
2026-11-13 01:03:54 +01:00
'pushEnabled' => push_is_configured (),
2026-11-13 00:35:39 +01:00
], 'Erinnerungen' );
}
2026-11-25 22:54:06 +01:00
/* ------------------------------------------------------- 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' ], 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 ;
}
$from = $period === 'month' ? month_start ( $date ) : week_start ( $date );
$to = $period === 'month' ? month_end ( $date ) : add_days ( $from , CALENDAR_WEEKS * 7 - 1 );
$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.' );
}
$values = [
'id' => $editing ? ( int ) $editing [ 'id' ] : 0 ,
'employee_id' => $editing ? ( int ) $editing [ 'employee_id' ] : ( $isAdmin ? 0 : $ownEmployeeId ),
'start_date' => $editing ? ( string ) $editing [ 'start_date' ] : $from ,
'end_date' => $editing ? ( string ) $editing [ 'end_date' ] : $from ,
'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=' . $period . '#abwesenheit-' . $id );
}
http_response_code ( 422 );
}
$rows = absence_list ( $from , $to );
$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 = $period === 'month'
? date_obj ( $from ) -> modify ( '-1 month' ) -> format ( 'Y-m-d' )
: add_days ( $date , - CALENDAR_WEEKS * 7 );
$nextDate = $period === 'month'
? date_obj ( $from ) -> modify ( '+1 month' ) -> format ( 'Y-m-d' )
: add_days ( $date , CALENDAR_WEEKS * 7 );
render_page ( 'absences' , [
'user' => $user ,
'isAdmin' => $isAdmin ,
'ownEmployeeId' => $ownEmployeeId ,
'employees' => $employees ,
'byEmployee' => $byEmployee ,
'conflicts' => $conflicts ,
'values' => $values ,
'errors' => $errors ,
'period' => $period ,
'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' ));
}
2026-11-13 00:35:39 +01:00
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'
2026-11-19 11:26:46 +01:00
|| ( auth_employee_id ( $user ) > 0
&& booking_employee_for_kind ( $booking , $kind ) === auth_employee_id ( $user ));
2026-11-13 00:35:39 +01:00
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 ,
2026-11-13 01:03:54 +01:00
'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' ),
2026-11-13 00:35:39 +01:00
], 'Mein Konto' );
}
2026-11-13 01:03:54 +01:00
/* ------------------------------------------------------------- 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 );
}