Drink it cold: Terminplanung für Kühlanhänger
This commit is contained in:
commit
ec88c8ebac
55 changed files with 7091 additions and 0 deletions
7
app/.htaccess
Normal file
7
app/.htaccess
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<IfModule mod_authz_core.c>
|
||||
Require all denied
|
||||
</IfModule>
|
||||
<IfModule !mod_authz_core.c>
|
||||
Order allow,deny
|
||||
Deny from all
|
||||
</IfModule>
|
||||
389
app/admin.php
Normal file
389
app/admin.php
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Verwaltung: Benutzer, Mitarbeiter, Anhänger, Erinnerungsversand. */
|
||||
|
||||
function admin_handle(string $path, array $user): void
|
||||
{
|
||||
auth_require_admin();
|
||||
|
||||
if ($path === '/admin' || $path === '/admin/') {
|
||||
redirect('/admin/users');
|
||||
}
|
||||
if ($path === '/admin/users') {
|
||||
admin_users_list();
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/users/new') {
|
||||
admin_user_form(null);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)$#', $path, $m) === 1) {
|
||||
admin_user_form((int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)/delete$#', $path, $m) === 1) {
|
||||
admin_user_delete((int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/employees') {
|
||||
admin_employees();
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/trailers') {
|
||||
admin_trailers();
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/reminders/send') {
|
||||
admin_reminders_send();
|
||||
return;
|
||||
}
|
||||
|
||||
abort_page(404, 'Diese Verwaltungsseite gibt es nicht.');
|
||||
}
|
||||
|
||||
function admin_users_list(): void
|
||||
{
|
||||
$sql = 'SELECT u.*, e.name AS employee_name
|
||||
FROM users u LEFT JOIN employees e ON e.id = u.employee_id
|
||||
ORDER BY u.last_name, u.first_name';
|
||||
$users = db()->query($sql)->fetchAll();
|
||||
render_page('admin_users', ['users' => $users], 'Benutzer');
|
||||
}
|
||||
|
||||
function admin_user_form(?int $id): void
|
||||
{
|
||||
$editing = $id !== null ? auth_user_by_id($id) : null;
|
||||
if ($id !== null && !$editing) {
|
||||
abort_page(404, 'Benutzer nicht gefunden.');
|
||||
}
|
||||
|
||||
$employees = employees_all();
|
||||
$errors = [];
|
||||
$values = $editing ? [
|
||||
'first_name' => (string) $editing['first_name'],
|
||||
'last_name' => (string) $editing['last_name'],
|
||||
'email' => (string) ($editing['email'] ?? ''),
|
||||
'role' => (string) $editing['role'],
|
||||
'status' => (string) $editing['status'],
|
||||
'employee_id' => (int) ($editing['employee_id'] ?? 0),
|
||||
'must_change_password' => (int) $editing['must_change_password'],
|
||||
] : [
|
||||
'first_name' => '',
|
||||
'last_name' => '',
|
||||
'email' => '',
|
||||
'role' => 'user',
|
||||
'status' => 'active',
|
||||
'employee_id' => 0,
|
||||
'must_change_password' => 1,
|
||||
];
|
||||
|
||||
if (is_post()) {
|
||||
require_post();
|
||||
$values = [
|
||||
'first_name' => post_string('first_name'),
|
||||
'last_name' => post_string('last_name'),
|
||||
'email' => post_string('email'),
|
||||
'role' => post_string('role') === 'admin' ? 'admin' : 'user',
|
||||
'status' => post_string('status') === 'disabled' ? 'disabled' : 'active',
|
||||
'employee_id' => (int) post_string('employee_id'),
|
||||
'must_change_password' => post_string('must_change_password') === '1' ? 1 : 0,
|
||||
];
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
|
||||
if ($values['first_name'] === '' || mb_strlen($values['first_name']) > 80) {
|
||||
$errors['first_name'] = 'Bitte einen Vornamen angeben (max. 80 Zeichen).';
|
||||
}
|
||||
if ($values['last_name'] === '' || mb_strlen($values['last_name']) > 80) {
|
||||
$errors['last_name'] = 'Bitte einen Nachnamen angeben (max. 80 Zeichen).';
|
||||
}
|
||||
if ($values['email'] !== '' && (!filter_var($values['email'], FILTER_VALIDATE_EMAIL) || mb_strlen($values['email']) > 190)) {
|
||||
$errors['email'] = 'Bitte eine gültige E-Mail-Adresse angeben.';
|
||||
} elseif ($values['email'] !== '') {
|
||||
$stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$values['email'], $id ?? 0]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
$errors['email'] = 'Diese E-Mail-Adresse ist bereits einem anderen Benutzer zugeordnet.';
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT id FROM users WHERE first_name = ? AND last_name = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$values['first_name'], $values['last_name'], $id ?? 0]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
$errors['name'] = 'Ein Benutzer mit diesem Vor- und Nachnamen existiert bereits.';
|
||||
}
|
||||
|
||||
if ($values['employee_id'] > 0) {
|
||||
$stmt = db()->prepare('SELECT id, first_name, last_name FROM users WHERE employee_id = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$values['employee_id'], $id ?? 0]);
|
||||
if ($other = $stmt->fetch()) {
|
||||
$errors['employee_id'] = 'Dieser Mitarbeiter ist bereits mit ' . $other['first_name'] . ' ' . $other['last_name'] . ' verknüpft.';
|
||||
}
|
||||
if (!employee_find($values['employee_id'])) {
|
||||
$errors['employee_id'] = 'Mitarbeiter nicht gefunden.';
|
||||
}
|
||||
}
|
||||
|
||||
if ($id === null && mb_strlen($password) < 8) {
|
||||
$errors['password'] = 'Das Startpasswort muss mindestens 8 Zeichen haben.';
|
||||
}
|
||||
if ($id !== null && $password !== '' && mb_strlen($password) < 8) {
|
||||
$errors['password'] = 'Das neue Passwort muss mindestens 8 Zeichen haben.';
|
||||
}
|
||||
|
||||
// Der letzte aktive Admin darf nicht degradiert oder deaktiviert werden.
|
||||
if ($editing && ($editing['role'] === 'admin' && $editing['status'] === 'active')
|
||||
&& ($values['role'] !== 'admin' || $values['status'] !== 'active')
|
||||
) {
|
||||
$stmt = db()->query("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id <> " . (int) $editing['id']);
|
||||
if ((int) $stmt->fetchColumn() === 0) {
|
||||
$errors['role'] = 'Der letzte aktive Administrator kann nicht herabgestuft oder deaktiviert werden.';
|
||||
}
|
||||
}
|
||||
if ($editing && (int) $editing['id'] === auth_user()['id']
|
||||
&& ($values['role'] !== 'admin' || $values['status'] !== 'active')
|
||||
) {
|
||||
$errors['role'] = 'Das eigene Konto kann nicht deaktiviert oder zum normalen Benutzer gemacht werden.';
|
||||
}
|
||||
|
||||
if (!$errors) {
|
||||
$email = $values['email'] === '' ? null : $values['email'];
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
if ($id === null) {
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO users (first_name, last_name, email, password_hash, role, status, employee_id,
|
||||
must_change_password, auth_epoch, created_at, updated_at, password_changed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$values['first_name'], $values['last_name'], $email, hash_password($password),
|
||||
$values['role'], $values['status'], $values['employee_id'] ?: null,
|
||||
$values['must_change_password'], utc_now(), utc_now(), utc_now(),
|
||||
]);
|
||||
$newId = (int) $pdo->lastInsertId();
|
||||
$pdo->commit();
|
||||
flash('success', 'Benutzer ' . $values['first_name'] . ' ' . $values['last_name'] . ' wurde angelegt.');
|
||||
redirect('/admin/users/' . $newId);
|
||||
}
|
||||
|
||||
$newId = (int) $editing['id'];
|
||||
$securityChange = $password !== '' || ($editing['status'] === 'active' && $values['status'] === 'disabled');
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE users SET first_name = ?, last_name = ?, email = ?, role = ?, status = ?,
|
||||
employee_id = ?, must_change_password = ?, updated_at = ? WHERE id = ?'
|
||||
);
|
||||
$stmt->execute([
|
||||
$values['first_name'], $values['last_name'], $email, $values['role'], $values['status'],
|
||||
$values['employee_id'] ?: null, $values['must_change_password'], utc_now(), $newId,
|
||||
]);
|
||||
if ($password !== '') {
|
||||
$pdo->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = ?,
|
||||
auth_epoch = auth_epoch + 1 WHERE id = ?'
|
||||
)->execute([hash_password($password), utc_now(), $values['must_change_password'], $newId]);
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$newId]);
|
||||
} elseif ($securityChange) {
|
||||
$pdo->prepare('UPDATE users SET auth_epoch = auth_epoch + 1 WHERE id = ?')->execute([$newId]);
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$newId]);
|
||||
}
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
|
||||
flash('success', 'Benutzer wurde gespeichert.');
|
||||
if ($password !== '' && $newId === (int) auth_user()['id']) {
|
||||
auth_logout();
|
||||
redirect('/login');
|
||||
}
|
||||
redirect('/admin/users');
|
||||
}
|
||||
http_response_code(422);
|
||||
}
|
||||
|
||||
render_page('admin_user_form', [
|
||||
'editing' => $editing,
|
||||
'values' => $values,
|
||||
'errors' => $errors,
|
||||
'employees' => $employees,
|
||||
], $editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen');
|
||||
}
|
||||
|
||||
function admin_user_delete(int $id, array $actor): void
|
||||
{
|
||||
require_post();
|
||||
$target = auth_user_by_id($id);
|
||||
if (!$target) {
|
||||
abort_page(404, 'Benutzer nicht gefunden.');
|
||||
}
|
||||
if ($id === (int) $actor['id']) {
|
||||
abort_page(422, 'Das eigene Konto kann nicht gelöscht werden.');
|
||||
}
|
||||
if ($target['role'] === 'admin' && $target['status'] === 'active') {
|
||||
$count = (int) db()->query("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id <> $id")->fetchColumn();
|
||||
if ($count === 0) {
|
||||
abort_page(422, 'Der letzte aktive Administrator kann nicht gelöscht werden.');
|
||||
}
|
||||
}
|
||||
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$id]);
|
||||
flash('success', 'Benutzer ' . $target['first_name'] . ' ' . $target['last_name'] . ' wurde gelöscht.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
|
||||
function admin_employees(): void
|
||||
{
|
||||
$errors = [];
|
||||
$editId = query_int('edit');
|
||||
$editing = $editId > 0 ? employee_find($editId) : null;
|
||||
$values = ['name' => '', 'sort_order' => 0, 'active' => 1];
|
||||
|
||||
if (is_post()) {
|
||||
require_post();
|
||||
$action = post_string('action');
|
||||
$id = (int) post_string('id');
|
||||
$values = [
|
||||
'name' => post_string('name'),
|
||||
'sort_order' => (int) post_string('sort_order'),
|
||||
'active' => post_string('active') === '1' ? 1 : 0,
|
||||
];
|
||||
if ($values['name'] === '' || mb_strlen($values['name']) > 100) {
|
||||
$errors['name'] = 'Bitte einen Namen angeben (max. 100 Zeichen).';
|
||||
}
|
||||
$stmt = db()->prepare('SELECT id FROM employees WHERE name = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$values['name'], $id]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
$errors['name'] = 'Dieser Mitarbeiter existiert bereits.';
|
||||
}
|
||||
|
||||
if (!$errors) {
|
||||
if ($action === 'create') {
|
||||
db()->prepare('INSERT INTO employees (name, active, sort_order, created_at) VALUES (?, ?, ?, ?)')
|
||||
->execute([$values['name'], $values['active'], $values['sort_order'], utc_now()]);
|
||||
flash('success', 'Mitarbeiter ' . $values['name'] . ' wurde angelegt.');
|
||||
} elseif ($action === 'update' && $id > 0) {
|
||||
$existing = employee_find($id);
|
||||
if (!$existing) {
|
||||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||||
}
|
||||
if ((int) $existing['active'] === 1 && $values['active'] === 0) {
|
||||
$stmt = db()->prepare("SELECT COUNT(*) FROM bookings WHERE employee_id = ? AND status = 'active' AND end_date >= ?");
|
||||
$stmt->execute([$id, today_iso()]);
|
||||
if ((int) $stmt->fetchColumn() > 0) {
|
||||
$errors['active'] = 'Der Mitarbeiter hat noch aktive Buchungen und kann nicht deaktiviert werden. Bitte zuerst umbuchen.';
|
||||
}
|
||||
}
|
||||
if (!$errors) {
|
||||
db()->prepare('UPDATE employees SET name = ?, active = ?, sort_order = ? WHERE id = ?')
|
||||
->execute([$values['name'], $values['active'], $values['sort_order'], $id]);
|
||||
flash('success', 'Mitarbeiter wurde gespeichert.');
|
||||
}
|
||||
}
|
||||
if (!$errors) {
|
||||
redirect('/admin/employees');
|
||||
}
|
||||
}
|
||||
http_response_code(422);
|
||||
$editId = $action === 'update' ? $id : 0;
|
||||
if ($editId > 0) {
|
||||
$editing = employee_find($editId);
|
||||
if (!$editing) {
|
||||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($editId > 0 && !$editing) {
|
||||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||||
}
|
||||
if ($editing && !is_post()) {
|
||||
$values = [
|
||||
'name' => (string) $editing['name'],
|
||||
'sort_order' => (int) $editing['sort_order'],
|
||||
'active' => (int) $editing['active'],
|
||||
];
|
||||
}
|
||||
|
||||
$rows = db()->query(
|
||||
'SELECT e.*, u.first_name, u.last_name,
|
||||
(SELECT COUNT(*) FROM bookings b WHERE b.employee_id = e.id AND b.status = "active" AND b.end_date >= CURDATE()) AS future_bookings
|
||||
FROM employees e LEFT JOIN users u ON u.employee_id = e.id
|
||||
ORDER BY e.sort_order, e.name'
|
||||
)->fetchAll();
|
||||
|
||||
render_page('admin_employees', [
|
||||
'rows' => $rows,
|
||||
'editing' => $editing,
|
||||
'editId' => $editId,
|
||||
'values' => $values,
|
||||
'errors' => $errors,
|
||||
], 'Mitarbeiter');
|
||||
}
|
||||
|
||||
function admin_trailers(): void
|
||||
{
|
||||
$errors = [];
|
||||
if (is_post()) {
|
||||
require_post();
|
||||
$labels = post_array('label');
|
||||
$colorNames = post_array('color_name');
|
||||
$colors = post_array('color_hex');
|
||||
$sorts = post_array('sort_order');
|
||||
|
||||
$existing = trailers_map();
|
||||
$seen = [];
|
||||
foreach ($existing as $id => $trailer) {
|
||||
$label = trim((string) ($labels[$id] ?? ''));
|
||||
$colorName = trim((string) ($colorNames[$id] ?? ''));
|
||||
$color = strtolower(trim((string) ($colors[$id] ?? '')));
|
||||
$sort = (int) ($sorts[$id] ?? $trailer['sort_order']);
|
||||
|
||||
if ($label === '' || mb_strlen($label) > 40) {
|
||||
$errors['trailer_' . $id] = 'Bitte eine Bezeichnung angeben (max. 40 Zeichen).';
|
||||
continue;
|
||||
}
|
||||
if (isset($seen[mb_strtolower($label)])) {
|
||||
$errors['trailer_' . $id] = 'Die Bezeichnung muss eindeutig sein.';
|
||||
continue;
|
||||
}
|
||||
$seen[mb_strtolower($label)] = true;
|
||||
if ($colorName === '' || mb_strlen($colorName) > 40) {
|
||||
$errors['trailer_' . $id] = 'Bitte einen Farbnamen angeben.';
|
||||
continue;
|
||||
}
|
||||
if (!preg_match('/^#[0-9a-f]{6}$/', $color)) {
|
||||
$errors['trailer_' . $id] = 'Bitte eine gültige Farbe (#rrggbb) wählen.';
|
||||
continue;
|
||||
}
|
||||
db()->prepare('UPDATE trailers SET label = ?, color_name = ?, color_hex = ?, sort_order = ? WHERE id = ?')
|
||||
->execute([$label, $colorName, $color, $sort, $id]);
|
||||
}
|
||||
if (!$errors) {
|
||||
flash('success', 'Anhänger wurden gespeichert.');
|
||||
redirect('/admin/trailers');
|
||||
}
|
||||
http_response_code(422);
|
||||
}
|
||||
|
||||
$rows = trailers_all(false);
|
||||
render_page('admin_trailers', [
|
||||
'rows' => $rows,
|
||||
'errors' => $errors,
|
||||
], 'Anhänger');
|
||||
}
|
||||
|
||||
function admin_reminders_send(): void
|
||||
{
|
||||
require_post();
|
||||
$result = reminder_send_due();
|
||||
if (!$result['enabled']) {
|
||||
flash('info', 'Der E-Mail-Versand ist in der Konfiguration deaktiviert. Die Erinnerungen bleiben in der App sichtbar.');
|
||||
} elseif ($result['errors']) {
|
||||
flash('error', implode(' ', $result['errors']));
|
||||
} else {
|
||||
flash('success', 'E-Mail-Versand ausgeführt: ' . $result['sent'] . ' Erinnerung(en) versendet, ' . $result['skipped'] . ' übersprungen.');
|
||||
}
|
||||
redirect('/reminders');
|
||||
}
|
||||
323
app/auth.php
Normal file
323
app/auth.php
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Anmeldung, Sessions, Angemeldet-bleiben und Ratenbegrenzung.
|
||||
*
|
||||
* Angemeldet wird – wie bei tippspiel2027 – mit Vorname, Nachname und
|
||||
* Passwort. Konten werden ausschließlich vom Admin angelegt.
|
||||
*/
|
||||
|
||||
const DIC_DUMMY_HASH = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
|
||||
const DIC_REMEMBER_COOKIE = 'DIC_REMEMBER';
|
||||
|
||||
function hash_password(string $password): string
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_hash($password, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 1,
|
||||
]);
|
||||
}
|
||||
return password_hash($password, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function password_needs_upgrade(string $hash): bool
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_needs_rehash($hash, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 1,
|
||||
]);
|
||||
}
|
||||
return password_needs_rehash($hash, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function auth_user(): ?array
|
||||
{
|
||||
static $loaded = false;
|
||||
static $user = null;
|
||||
if ($loaded) {
|
||||
return $user;
|
||||
}
|
||||
$loaded = true;
|
||||
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
auth_restore_from_remember();
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([(int) $uid]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row || $row['status'] !== 'active') {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$idleLimit = (int) config('app.session_idle_seconds', 2592000);
|
||||
$absoluteLimit = (int) config('app.session_absolute_seconds', 7776000);
|
||||
$created = (int) ($_SESSION['created'] ?? 0);
|
||||
$lastSeen = (int) ($_SESSION['last_seen'] ?? 0);
|
||||
if ($created === 0 || $lastSeen === 0
|
||||
|| $now - $lastSeen > $idleLimit
|
||||
|| $now - $created > $absoluteLimit
|
||||
) {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
if ($now - $lastSeen > 300) {
|
||||
$_SESSION['last_seen'] = $now;
|
||||
}
|
||||
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
$user = $row;
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_user_by_id(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function auth_login(array $user, bool $remember = false): void
|
||||
{
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['uid'] = (int) $user['id'];
|
||||
$_SESSION['epoch'] = (int) $user['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
|
||||
$stmt = db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?');
|
||||
$stmt->execute([utc_now(), (int) $user['id']]);
|
||||
|
||||
if ($remember) {
|
||||
auth_issue_remember((int) $user['id']);
|
||||
}
|
||||
db()->prepare('DELETE FROM login_attempts WHERE name_key = ?')->execute([auth_name_key((string) $user['first_name'], (string) $user['last_name'])]);
|
||||
}
|
||||
|
||||
function auth_clear_session(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_logout(): void
|
||||
{
|
||||
auth_forget_remember();
|
||||
auth_clear_session();
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
session_destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function auth_require_login(): array
|
||||
{
|
||||
$user = auth_user();
|
||||
if ($user === null) {
|
||||
$target = current_path();
|
||||
$query = (string) ($_SERVER['QUERY_STRING'] ?? '');
|
||||
if ($query !== '') {
|
||||
$target .= '?' . $query;
|
||||
}
|
||||
redirect('/login?next=' . rawurlencode($target));
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_require_admin(): array
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if (($user['role'] ?? '') !== 'admin') {
|
||||
abort_page(403, 'Diese Seite ist nur für Administratoren.');
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_name_key(string $first, string $last): string
|
||||
{
|
||||
return mb_strtolower(trim($first) . ' ' . trim($last), 'UTF-8');
|
||||
}
|
||||
|
||||
function auth_find_by_name(string $first, string $last): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE first_name = ? AND last_name = ? LIMIT 1');
|
||||
$stmt->execute([trim($first), trim($last)]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
function auth_is_locked_out(string $first, string $last): bool
|
||||
{
|
||||
$window = (int) config('app.login_window_seconds', 900);
|
||||
$maxIp = (int) config('app.login_max_per_ip', 15);
|
||||
$maxName = (int) config('app.login_max_per_user', 5);
|
||||
|
||||
$stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND attempted_at >= ?');
|
||||
$stmt->execute([client_ip(), utc_after(-$window)]);
|
||||
if ((int) $stmt->fetchColumn() >= $maxIp) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE name_key = ? AND attempted_at >= ?');
|
||||
$stmt->execute([auth_name_key($first, $last), utc_after(-$window)]);
|
||||
return (int) $stmt->fetchColumn() >= $maxName;
|
||||
}
|
||||
|
||||
function auth_record_failure(string $first, string $last): void
|
||||
{
|
||||
$stmt = db()->prepare('INSERT INTO login_attempts (ip, name_key, attempted_at) VALUES (?, ?, ?)');
|
||||
$stmt->execute([client_ip(), auth_name_key($first, $last), utc_now()]);
|
||||
|
||||
// Tabelle klein halten; nur das Ratenfenster ist relevant.
|
||||
$window = (int) config('app.login_window_seconds', 900);
|
||||
db()->prepare('DELETE FROM login_attempts WHERE attempted_at < ?')->execute([utc_after(-max($window * 8, 86400))]);
|
||||
}
|
||||
|
||||
function auth_verify_login(string $first, string $last, string $password): array
|
||||
{
|
||||
if (auth_is_locked_out($first, $last)) {
|
||||
throw new RuntimeException('locked');
|
||||
}
|
||||
|
||||
$user = auth_find_by_name($first, $last);
|
||||
$hash = $user['password_hash'] ?? DIC_DUMMY_HASH;
|
||||
$ok = password_verify($password, $hash);
|
||||
if (!$user || !$ok) {
|
||||
auth_record_failure($first, $last);
|
||||
throw new RuntimeException('invalid');
|
||||
}
|
||||
if ($user['status'] !== 'active') {
|
||||
auth_record_failure($first, $last);
|
||||
throw new RuntimeException('disabled');
|
||||
}
|
||||
if (password_needs_upgrade($hash)) {
|
||||
db()->prepare('UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?')
|
||||
->execute([hash_password($password), utc_now(), (int) $user['id']]);
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_invalidate_sessions(int $userId): void
|
||||
{
|
||||
db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), $userId]);
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ Angemeldet bleiben */
|
||||
|
||||
function auth_issue_remember(int $userId): void
|
||||
{
|
||||
$selector = bin2hex(random_bytes(12));
|
||||
$validator = bin2hex(random_bytes(32));
|
||||
$lifetime = (int) config('app.remember_seconds', 7776000);
|
||||
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE expires_at < ?')->execute([utc_now()]);
|
||||
$stmt = db()->prepare('INSERT INTO auth_tokens (user_id, selector, validator_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?)');
|
||||
$stmt->execute([$userId, $selector, hash('sha256', $validator), utc_now(), utc_after($lifetime)]);
|
||||
|
||||
setcookie(DIC_REMEMBER_COOKIE, $selector . '.' . $validator, [
|
||||
'expires' => time() + $lifetime,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
}
|
||||
|
||||
function auth_forget_remember(): void
|
||||
{
|
||||
$raw = $_COOKIE[DIC_REMEMBER_COOKIE] ?? '';
|
||||
if (is_string($raw) && str_contains($raw, '.')) {
|
||||
[$selector] = explode('.', $raw, 2);
|
||||
if ($selector !== '') {
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE selector = ?')->execute([$selector]);
|
||||
}
|
||||
}
|
||||
if (isset($_COOKIE[DIC_REMEMBER_COOKIE])) {
|
||||
setcookie(DIC_REMEMBER_COOKIE, '', [
|
||||
'expires' => time() - 3600,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
unset($_COOKIE[DIC_REMEMBER_COOKIE]);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_restore_from_remember(): void
|
||||
{
|
||||
$raw = $_COOKIE[DIC_REMEMBER_COOKIE] ?? '';
|
||||
if (!is_string($raw) || !preg_match('/^([a-f0-9]{24})\.([a-f0-9]{64})$/', $raw, $m)) {
|
||||
return;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT t.*, u.auth_epoch, u.status, u.must_change_password
|
||||
FROM auth_tokens t JOIN users u ON u.id = t.user_id
|
||||
WHERE t.selector = ? AND t.expires_at >= ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$m[1], utc_now()]);
|
||||
$token = $stmt->fetch();
|
||||
if (!$token || !hash_equals((string) $token['validator_hash'], hash('sha256', $m[2]))) {
|
||||
auth_forget_remember();
|
||||
return;
|
||||
}
|
||||
if ($token['status'] !== 'active') {
|
||||
auth_forget_remember();
|
||||
return;
|
||||
}
|
||||
|
||||
// Token rotieren, damit ein gestohlenes Cookie nur einmal nutzbar ist.
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE id = ?')->execute([(int) $token['id']]);
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['uid'] = (int) $token['user_id'];
|
||||
$_SESSION['epoch'] = (int) $token['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
auth_issue_remember((int) $token['user_id']);
|
||||
}
|
||||
|
||||
function auth_can_manage(User|null|array $user): bool
|
||||
{
|
||||
return is_array($user) && ($user['role'] ?? '') === 'admin';
|
||||
}
|
||||
|
||||
function auth_employee_id(array $user): int
|
||||
{
|
||||
return (int) ($user['employee_id'] ?? 0);
|
||||
}
|
||||
|
||||
/** Offene Erinnerungen, die den Benutzer betreffen (für die Navigation). */
|
||||
function auth_reminder_badge(array $user): int
|
||||
{
|
||||
return reminder_open_count($user, add_days(today_iso(), 7));
|
||||
}
|
||||
57
app/bootstrap.php
Normal file
57
app/bootstrap.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Drink it cold – Bootstrap.
|
||||
*
|
||||
* Lädt Konfiguration, Datenbank, Session und Helfer. Die Konfiguration mit
|
||||
* Zugangsdaten liegt in app/config.local.php und wird beim Deployment erzeugt.
|
||||
*/
|
||||
|
||||
define('DIC_ROOT', dirname(__DIR__));
|
||||
define('DIC_APP', __DIR__);
|
||||
|
||||
$configFile = DIC_APP . '/config.local.php';
|
||||
if (!is_file($configFile)) {
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "Die Anwendung ist noch nicht konfiguriert (app/config.local.php fehlt).\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
$GLOBALS['dic_config'] = require $configFile;
|
||||
|
||||
date_default_timezone_set('Europe/Berlin');
|
||||
ini_set('display_errors', '0');
|
||||
ini_set('log_errors', '1');
|
||||
|
||||
require DIC_APP . '/util.php';
|
||||
require DIC_APP . '/db.php';
|
||||
require DIC_APP . '/auth.php';
|
||||
require DIC_APP . '/data.php';
|
||||
require DIC_APP . '/mail.php';
|
||||
require DIC_APP . '/pages.php';
|
||||
require DIC_APP . '/admin.php';
|
||||
|
||||
$storage = (string) config('app.storage_path', DIC_ROOT . '/storage');
|
||||
if (is_dir($storage) && is_dir($storage . '/logs') && is_writable($storage . '/logs')) {
|
||||
ini_set('error_log', $storage . '/logs/php.log');
|
||||
}
|
||||
|
||||
set_exception_handler(static function (Throwable $error): void {
|
||||
error_log('Drink it cold: ' . $error::class . ': ' . $error->getMessage() . ' in ' . $error->getFile() . ':' . $error->getLine());
|
||||
if (function_exists('wants_json') && wants_json()) {
|
||||
json_response(['error' => ['code' => 'server_error', 'message' => 'Interner Fehler.']], 500);
|
||||
return;
|
||||
}
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
echo '<!doctype html><meta charset="utf-8"><title>Fehler 500</title>'
|
||||
. '<body style="font-family:system-ui;background:#f4f9fe;color:#0e1b26;padding:2rem">'
|
||||
. '<h1>Interner Fehler</h1><p>Bitte später erneut versuchen.</p></body>';
|
||||
});
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
security_headers();
|
||||
start_session();
|
||||
}
|
||||
33
app/config.example.php
Normal file
33
app/config.example.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
/**
|
||||
* Beispielkonfiguration. Wird nicht ausgeliefert; beim Deployment erzeugt
|
||||
* tools/deploy.sh daraus app/config.local.php.
|
||||
*/
|
||||
return [
|
||||
'db' => [
|
||||
'host' => 'localhost',
|
||||
'port' => 3306,
|
||||
'name' => 'DB_NAME',
|
||||
'user' => 'DB_USER',
|
||||
'password' => 'DB_PASSWORD',
|
||||
'charset' => 'utf8mb4',
|
||||
],
|
||||
'app' => [
|
||||
// Leer, wenn die App direkt im DocumentRoot der Subdomain liegt.
|
||||
'base_path' => '',
|
||||
'public_url' => 'https://drink-it-cold.programmschmiede.de',
|
||||
'storage_path' => dirname(__DIR__) . '/storage',
|
||||
'install_token' => 'wird-beim-deployment-erzeugt',
|
||||
'session_idle_seconds' => 30 * 86400,
|
||||
'session_absolute_seconds' => 90 * 86400,
|
||||
'remember_seconds' => 90 * 86400,
|
||||
'login_window_seconds' => 900,
|
||||
'login_max_per_user' => 5,
|
||||
'login_max_per_ip' => 15,
|
||||
// Optionaler täglicher E-Mail-Digest (tools/send_reminders.php).
|
||||
'mail_enabled' => false,
|
||||
'mail_from' => 'Drink it cold <noreply@drink-it-cold.programmschmiede.de>',
|
||||
// Token für /cron/reminders?token=…, falls kein CLI-Cron möglich ist.
|
||||
'cron_token' => '',
|
||||
],
|
||||
];
|
||||
685
app/data.php
Normal file
685
app/data.php
Normal file
|
|
@ -0,0 +1,685 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Anhänger, Mitarbeiter, Buchungen, Kalendergeometrie und Erinnerungen. */
|
||||
|
||||
/* --------------------------------------------------------------- Anhänger */
|
||||
|
||||
function trailers_all(bool $activeOnly = true): array
|
||||
{
|
||||
$sql = 'SELECT * FROM trailers' . ($activeOnly ? ' WHERE active = 1' : '') . ' ORDER BY sort_order, id';
|
||||
return db()->query($sql)->fetchAll();
|
||||
}
|
||||
|
||||
function trailers_map(bool $activeOnly = false): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (trailers_all($activeOnly) as $trailer) {
|
||||
$out[(int) $trailer['id']] = $trailer;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
function trailer_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM trailers WHERE id = ?');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Mitarbeiter */
|
||||
|
||||
function employees_all(bool $activeOnly = true): array
|
||||
{
|
||||
$sql = 'SELECT * FROM employees' . ($activeOnly ? ' WHERE active = 1' : '') . ' ORDER BY sort_order, name';
|
||||
return db()->query($sql)->fetchAll();
|
||||
}
|
||||
|
||||
function employees_map(bool $activeOnly = false): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (employees_all($activeOnly) as $employee) {
|
||||
$out[(int) $employee['id']] = $employee;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
function employee_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM employees WHERE id = ?');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Buchungen */
|
||||
|
||||
const BOOKING_SELECT = 'SELECT b.*, t.label AS trailer_label, t.color_hex AS trailer_color,
|
||||
t.color_name AS trailer_color_name, t.sort_order AS trailer_sort,
|
||||
e.name AS employee_name
|
||||
FROM bookings b
|
||||
JOIN trailers t ON t.id = b.trailer_id
|
||||
JOIN employees e ON e.id = b.employee_id';
|
||||
|
||||
function booking_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare(BOOKING_SELECT . ' WHERE b.id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/** Aktive (und optional stornierte) Buchungen, die den Zeitraum berühren. */
|
||||
function booking_list(string $from, string $to, bool $includeCancelled = false, int $employeeId = 0): array
|
||||
{
|
||||
$sql = BOOKING_SELECT . ' WHERE b.start_date <= ? AND b.end_date >= ?';
|
||||
$params = [$to, $from];
|
||||
if (!$includeCancelled) {
|
||||
$sql .= " AND b.status = 'active'";
|
||||
}
|
||||
if ($employeeId > 0) {
|
||||
$sql .= ' AND b.employee_id = ?';
|
||||
$params[] = $employeeId;
|
||||
}
|
||||
$sql .= ' ORDER BY t.sort_order, b.start_date, b.end_date, b.id';
|
||||
$stmt = db()->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function booking_search(string $query, int $limit = 100): array
|
||||
{
|
||||
$query = trim($query);
|
||||
if ($query === '') {
|
||||
return [];
|
||||
}
|
||||
$like = '%' . addcslashes($query, '%_\\') . '%';
|
||||
$stmt = db()->prepare(
|
||||
BOOKING_SELECT . ' WHERE b.customer_name LIKE ? OR b.city LIKE ? OR b.street LIKE ?
|
||||
ORDER BY b.start_date DESC, b.id DESC LIMIT ' . max(1, min(200, $limit))
|
||||
);
|
||||
$stmt->execute([$like, $like, $like]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function booking_conflicts(int $trailerId, string $start, string $end, int $excludeId = 0): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
BOOKING_SELECT . " WHERE b.trailer_id = ? AND b.status = 'active'
|
||||
AND b.start_date < ? AND b.end_date > ? AND b.id <> ?
|
||||
ORDER BY b.start_date"
|
||||
);
|
||||
$stmt->execute([$trailerId, $end, $start, $excludeId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/** Formulardaten in ein normalisiertes Array übersetzen. */
|
||||
function booking_input(array $source): array
|
||||
{
|
||||
$kind = (string) ($source['kind'] ?? 'pickup');
|
||||
return [
|
||||
'trailer_id' => (int) ($source['trailer_id'] ?? 0),
|
||||
'employee_id' => (int) ($source['employee_id'] ?? 0),
|
||||
'start_date' => trim((string) ($source['start_date'] ?? '')),
|
||||
'end_date' => trim((string) ($source['end_date'] ?? '')),
|
||||
'deposit_cents' => parse_money((string) ($source['deposit'] ?? '0')),
|
||||
'total_cents' => parse_money((string) ($source['total'] ?? '0')),
|
||||
'invoice' => ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0,
|
||||
'kind' => in_array($kind, ['pickup', 'delivery'], true) ? $kind : 'pickup',
|
||||
'customer_name' => trim((string) ($source['customer_name'] ?? '')),
|
||||
'street' => trim((string) ($source['street'] ?? '')),
|
||||
'city' => trim((string) ($source['city'] ?? '')),
|
||||
'mobile' => trim((string) ($source['mobile'] ?? '')),
|
||||
'email' => trim((string) ($source['email'] ?? '')),
|
||||
];
|
||||
}
|
||||
|
||||
function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId = 0, int $allowEmployeeId = 0): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
$trailer = $data['trailer_id'] > 0 ? trailer_find((int) $data['trailer_id']) : null;
|
||||
if (!$trailer || ((int) $trailer['active'] !== 1 && (int) $trailer['id'] !== $allowTrailerId)) {
|
||||
$errors['trailer_id'] = 'Bitte einen Kühlanhänger auswählen.';
|
||||
}
|
||||
|
||||
$employee = $data['employee_id'] > 0 ? employee_find((int) $data['employee_id']) : null;
|
||||
if (!$employee || ((int) $employee['active'] !== 1 && (int) $employee['id'] !== $allowEmployeeId)) {
|
||||
$errors['employee_id'] = 'Bitte einen zuständigen Mitarbeiter auswählen.';
|
||||
}
|
||||
|
||||
if (!valid_date($data['start_date'])) {
|
||||
$errors['start_date'] = 'Bitte ein gültiges Mietbeginn-Datum angeben.';
|
||||
}
|
||||
if (!valid_date($data['end_date'])) {
|
||||
$errors['end_date'] = 'Bitte ein gültiges Mietende-Datum angeben.';
|
||||
}
|
||||
if (!isset($errors['start_date']) && !isset($errors['end_date'])) {
|
||||
if ($data['end_date'] < $data['start_date']) {
|
||||
$errors['end_date'] = 'Das Mietende darf nicht vor dem Mietbeginn liegen.';
|
||||
} elseif (days_between($data['start_date'], $data['end_date']) > 365) {
|
||||
$errors['end_date'] = 'Der Mietzeitraum darf höchstens 365 Tage betragen.';
|
||||
}
|
||||
}
|
||||
|
||||
if ($data['customer_name'] === '') {
|
||||
$errors['customer_name'] = 'Bitte den Kundennamen angeben.';
|
||||
} elseif (mb_strlen($data['customer_name']) > 190) {
|
||||
$errors['customer_name'] = 'Der Kundenname ist zu lang (max. 190 Zeichen).';
|
||||
}
|
||||
foreach (['street' => 'Straße', 'city' => 'Ort', 'mobile' => 'Handy'] as $field => $label) {
|
||||
if (mb_strlen((string) $data[$field]) > 190) {
|
||||
$errors[$field] = $label . ' ist zu lang (max. 190 Zeichen).';
|
||||
}
|
||||
}
|
||||
|
||||
if ($data['email'] !== '') {
|
||||
if (mb_strlen($data['email']) > 190) {
|
||||
$errors['email'] = 'Die E-Mail-Adresse ist zu lang.';
|
||||
} elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors['email'] = 'Bitte eine gültige E-Mail-Adresse angeben.';
|
||||
}
|
||||
}
|
||||
|
||||
$maxAmount = 10000000; // 100.000,00 €
|
||||
if ($data['total_cents'] < 0 || $data['deposit_cents'] < 0) {
|
||||
$errors['total'] = 'Beträge dürfen nicht negativ sein.';
|
||||
} elseif ($data['total_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
|
||||
$errors['total'] = 'Der Betrag ist unrealistisch hoch.';
|
||||
} elseif ($data['deposit_cents'] > $data['total_cents']) {
|
||||
$errors['deposit'] = 'Die Anzahlung darf den Gesamtbetrag nicht übersteigen.';
|
||||
}
|
||||
|
||||
if (!$errors && $trailer) {
|
||||
$conflicts = booking_conflicts((int) $trailer['id'], $data['start_date'], $data['end_date'], $excludeId);
|
||||
if ($conflicts) {
|
||||
$c = $conflicts[0];
|
||||
$errors['period'] = sprintf(
|
||||
'%s ist vom %s bis %s bereits an %s vergeben. Ein Wechseltag (letzter Tag = erster Tag) ist erlaubt.',
|
||||
$trailer['label'],
|
||||
fmt_date($c['start_date']),
|
||||
fmt_date($c['end_date']),
|
||||
$c['customer_name']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/** Serialisiert Änderungen pro Anhänger, damit parallele Buchungen nicht kollidieren. */
|
||||
function booking_lock_trailers(array $trailerIds): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_map('intval', $trailerIds)));
|
||||
if (!$ids) {
|
||||
return;
|
||||
}
|
||||
sort($ids);
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$stmt = db()->prepare("SELECT id FROM trailers WHERE id IN ($placeholders) ORDER BY id FOR UPDATE");
|
||||
$stmt->execute($ids);
|
||||
$stmt->fetchAll();
|
||||
}
|
||||
|
||||
function booking_create(array $data, int $userId): int
|
||||
{
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
booking_lock_trailers([$data['trailer_id']]);
|
||||
$errors = booking_validate($data);
|
||||
if ($errors) {
|
||||
throw new InvalidArgumentException(json_encode($errors, JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO bookings
|
||||
(trailer_id, employee_id, start_date, end_date, deposit_cents, total_cents, invoice, kind,
|
||||
customer_name, street, city, mobile, email, status, created_at, updated_at, created_by, updated_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
|
||||
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
|
||||
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
|
||||
utc_now(), utc_now(), $userId, $userId,
|
||||
]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
$pdo->commit();
|
||||
return $id;
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
function booking_update(int $id, array $data, int $userId): void
|
||||
{
|
||||
$existing = booking_find($id);
|
||||
if (!$existing) {
|
||||
throw new RuntimeException('not_found');
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
booking_lock_trailers([(int) $existing['trailer_id'], (int) $data['trailer_id']]);
|
||||
$errors = booking_validate($data, $id, (int) $existing['trailer_id'], (int) $existing['employee_id']);
|
||||
if ($errors) {
|
||||
throw new InvalidArgumentException(json_encode($errors, JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE bookings SET trailer_id = ?, employee_id = ?, start_date = ?, end_date = ?,
|
||||
deposit_cents = ?, total_cents = ?, invoice = ?, kind = ?, customer_name = ?, street = ?,
|
||||
city = ?, mobile = ?, email = ?, updated_at = ?, updated_by = ? WHERE id = ?'
|
||||
);
|
||||
$stmt->execute([
|
||||
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
|
||||
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
|
||||
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
|
||||
utc_now(), $userId, $id,
|
||||
]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
|
||||
// Wechselt der zuständige Mitarbeiter, gehören die Erinnerungen (inkl.
|
||||
// Erledigt-Status und Versandprotokoll) dem neuen Mitarbeiter.
|
||||
if ((int) $existing['employee_id'] !== (int) $data['employee_id']) {
|
||||
db()->prepare('DELETE FROM reminder_done WHERE booking_id = ?')->execute([$id]);
|
||||
db()->prepare('DELETE FROM reminder_mail_log WHERE booking_id = ?')->execute([$id]);
|
||||
}
|
||||
|
||||
// Abgehakte Erinnerungen gelten nur für ihr Fälligkeitsdatum. Bleibt das
|
||||
// Datum gleich, bleibt auch der Haken; sonst öffnet die Erinnerung wieder.
|
||||
db()->prepare(
|
||||
'DELETE rd FROM reminder_done rd
|
||||
JOIN bookings b ON b.id = rd.booking_id
|
||||
WHERE rd.booking_id = ? AND (
|
||||
(rd.kind = "start_8" AND rd.due_date <> DATE_SUB(b.start_date, INTERVAL 8 DAY)) OR
|
||||
(rd.kind = "start_1" AND rd.due_date <> DATE_SUB(b.start_date, INTERVAL 1 DAY)) OR
|
||||
(rd.kind = "end_1" AND rd.due_date <> DATE_SUB(b.end_date, INTERVAL 1 DAY))
|
||||
)'
|
||||
)->execute([$id]);
|
||||
}
|
||||
|
||||
function booking_cancel(int $id, int $userId): void
|
||||
{
|
||||
db()->prepare(
|
||||
"UPDATE bookings SET status = 'cancelled', cancelled_at = ?, cancelled_by = ?, updated_at = ?, updated_by = ?
|
||||
WHERE id = ? AND status = 'active'"
|
||||
)->execute([utc_now(), $userId, utc_now(), $userId, $id]);
|
||||
}
|
||||
|
||||
function booking_restore(int $id, int $userId): array
|
||||
{
|
||||
$booking = booking_find($id);
|
||||
if (!$booking) {
|
||||
throw new RuntimeException('not_found');
|
||||
}
|
||||
$errors = booking_validate([
|
||||
'trailer_id' => (int) $booking['trailer_id'],
|
||||
'employee_id' => (int) $booking['employee_id'],
|
||||
'start_date' => $booking['start_date'],
|
||||
'end_date' => $booking['end_date'],
|
||||
'deposit_cents' => (int) $booking['deposit_cents'],
|
||||
'total_cents' => (int) $booking['total_cents'],
|
||||
'invoice' => (int) $booking['invoice'],
|
||||
'kind' => $booking['kind'],
|
||||
'customer_name' => $booking['customer_name'],
|
||||
'street' => $booking['street'],
|
||||
'city' => $booking['city'],
|
||||
'mobile' => $booking['mobile'],
|
||||
'email' => $booking['email'],
|
||||
], $id, (int) $booking['trailer_id'], (int) $booking['employee_id']);
|
||||
if ($errors) {
|
||||
return $errors;
|
||||
}
|
||||
db()->prepare(
|
||||
"UPDATE bookings SET status = 'active', cancelled_at = NULL, cancelled_by = NULL,
|
||||
updated_at = ?, updated_by = ? WHERE id = ?"
|
||||
)->execute([utc_now(), $userId, $id]);
|
||||
db()->prepare('DELETE FROM reminder_done WHERE booking_id = ?')->execute([$id]);
|
||||
return [];
|
||||
}
|
||||
|
||||
function booking_delete(int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM bookings WHERE id = ?')->execute([$id]);
|
||||
}
|
||||
|
||||
/** Drag & Drop: Beginn verschieben, Dauer beibehalten, optional Anhänger wechseln. */
|
||||
function booking_move(int $id, string $newStart, int $newTrailerId, int $userId): array
|
||||
{
|
||||
$booking = booking_find($id);
|
||||
if (!$booking || $booking['status'] !== 'active') {
|
||||
return ['error' => 'Diese Buchung kann nicht verschoben werden.'];
|
||||
}
|
||||
if (!valid_date($newStart)) {
|
||||
return ['error' => 'Ungültiges Datum.'];
|
||||
}
|
||||
$duration = days_between((string) $booking['start_date'], (string) $booking['end_date']);
|
||||
$newEnd = add_days($newStart, $duration);
|
||||
$trailer = trailer_find($newTrailerId);
|
||||
if (!$trailer || (int) $trailer['active'] !== 1) {
|
||||
return ['error' => 'Bitte einen gültigen Kühlanhänger wählen.'];
|
||||
}
|
||||
|
||||
$data = [
|
||||
'trailer_id' => $newTrailerId,
|
||||
'employee_id' => (int) $booking['employee_id'],
|
||||
'start_date' => $newStart,
|
||||
'end_date' => $newEnd,
|
||||
'deposit_cents' => (int) $booking['deposit_cents'],
|
||||
'total_cents' => (int) $booking['total_cents'],
|
||||
'invoice' => (int) $booking['invoice'],
|
||||
'kind' => (string) $booking['kind'],
|
||||
'customer_name' => (string) $booking['customer_name'],
|
||||
'street' => (string) $booking['street'],
|
||||
'city' => (string) $booking['city'],
|
||||
'mobile' => (string) $booking['mobile'],
|
||||
'email' => (string) $booking['email'],
|
||||
];
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
booking_lock_trailers([(int) $booking['trailer_id'], $newTrailerId]);
|
||||
$errors = booking_validate($data, $id, 0, (int) $booking['employee_id']);
|
||||
if ($errors) {
|
||||
$pdo->rollBack();
|
||||
return ['error' => reset($errors) ?: 'Der neue Zeitraum ist belegt.'];
|
||||
}
|
||||
$pdo->prepare(
|
||||
'UPDATE bookings SET trailer_id = ?, start_date = ?, end_date = ?, updated_at = ?, updated_by = ? WHERE id = ?'
|
||||
)->execute([$newTrailerId, $newStart, $newEnd, utc_now(), $userId, $id]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
|
||||
db()->prepare(
|
||||
'DELETE rd FROM reminder_done rd
|
||||
JOIN bookings b ON b.id = rd.booking_id
|
||||
WHERE rd.booking_id = ? AND (
|
||||
(rd.kind = "start_8" AND rd.due_date <> DATE_SUB(b.start_date, INTERVAL 8 DAY)) OR
|
||||
(rd.kind = "start_1" AND rd.due_date <> DATE_SUB(b.start_date, INTERVAL 1 DAY)) OR
|
||||
(rd.kind = "end_1" AND rd.due_date <> DATE_SUB(b.end_date, INTERVAL 1 DAY))
|
||||
)'
|
||||
)->execute([$id]);
|
||||
|
||||
$fresh = booking_find($id);
|
||||
return [
|
||||
'ok' => true,
|
||||
'booking' => $fresh,
|
||||
'start_date' => $fresh['start_date'],
|
||||
'end_date' => $fresh['end_date'],
|
||||
'trailer_id' => (int) $fresh['trailer_id'],
|
||||
];
|
||||
}
|
||||
|
||||
function booking_kind_label(string $kind): string
|
||||
{
|
||||
return $kind === 'delivery' ? 'Lieferung' : 'Abholer';
|
||||
}
|
||||
|
||||
function booking_invoice_label(int|string $invoice): string
|
||||
{
|
||||
return (int) $invoice === 1 ? 'JA' : 'NEIN';
|
||||
}
|
||||
|
||||
/** Exakt der Text aus der Anforderung, Zeile für Zeile. */
|
||||
function booking_copy_text(array $booking): string
|
||||
{
|
||||
return implode("\n", [
|
||||
'Anzahlung: ' . fmt_money((int) $booking['deposit_cents']),
|
||||
'Gesamtbetrag: ' . fmt_money((int) $booking['total_cents']),
|
||||
'Noch zu zahlen: ' . fmt_money(due_cents((int) $booking['total_cents'], (int) $booking['deposit_cents'])),
|
||||
'Rechnung: ' . booking_invoice_label($booking['invoice']),
|
||||
'Von: ' . fmt_date_short((string) $booking['start_date']),
|
||||
'Bis: ' . fmt_date_short((string) $booking['end_date']),
|
||||
'Art: ' . booking_kind_label((string) $booking['kind']),
|
||||
'Name: ' . $booking['customer_name'],
|
||||
'Straße: ' . $booking['street'],
|
||||
'Ort: ' . $booking['city'],
|
||||
'Handy: ' . $booking['mobile'],
|
||||
'E-Mail: ' . $booking['email'],
|
||||
]);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- Erinnerungen */
|
||||
|
||||
function reminder_kinds(): array
|
||||
{
|
||||
return [
|
||||
'start_8' => [
|
||||
'label' => 'Übergabetermin vereinbaren',
|
||||
'short' => '8 Tage vor Mietbeginn',
|
||||
'message' => 'Bitte mit dem Kunden einen Übergabetermin für den Kühlanhänger vereinbaren.',
|
||||
'anchor' => 'start',
|
||||
'offset' => -8,
|
||||
],
|
||||
'start_1' => [
|
||||
'label' => 'Übergabe / Lieferung',
|
||||
'short' => '1 Tag vor Mietbeginn',
|
||||
'message' => 'Morgen steht die Übergabe bzw. Lieferung des Kühlanhängers an.',
|
||||
'anchor' => 'start',
|
||||
'offset' => -1,
|
||||
],
|
||||
'end_1' => [
|
||||
'label' => 'Abholung / Rücknahme',
|
||||
'short' => '1 Tag vor Mietende',
|
||||
'message' => 'Morgen muss der Kühlanhänger beim Kunden abgeholt bzw. zurückgenommen werden.',
|
||||
'anchor' => 'end',
|
||||
'offset' => -1,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
function booking_reminders(array $booking): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach (reminder_kinds() as $kind => $meta) {
|
||||
$anchor = $meta['anchor'] === 'start' ? (string) $booking['start_date'] : (string) $booking['end_date'];
|
||||
$rows[] = [
|
||||
'kind' => $kind,
|
||||
'label' => $meta['label'],
|
||||
'short' => $meta['short'],
|
||||
'message' => $meta['message'],
|
||||
'due_date' => add_days($anchor, (int) $meta['offset']),
|
||||
];
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array<string,bool> Schlüssel: bookingId:kind:dueDate */
|
||||
function reminder_done_map(array $bookingIds): array
|
||||
{
|
||||
if (!$bookingIds) {
|
||||
return [];
|
||||
}
|
||||
$ids = array_values(array_unique(array_map('intval', $bookingIds)));
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$stmt = db()->prepare("SELECT booking_id, kind, due_date FROM reminder_done WHERE booking_id IN ($placeholders)");
|
||||
$stmt->execute($ids);
|
||||
$out = [];
|
||||
foreach ($stmt->fetchAll() as $row) {
|
||||
$out[$row['booking_id'] . ':' . $row['kind'] . ':' . $row['due_date']] = true;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
function reminder_done_key(array $booking, string $kind, string $dueDate): string
|
||||
{
|
||||
return (int) $booking['id'] . ':' . $kind . ':' . $dueDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle fälligen Erinnerungen im Zeitraum. Erinnerungen werden aus den
|
||||
* Buchungsdaten berechnet und sind damit bei Terminänderungen automatisch
|
||||
* aktuell; eine Stornierung entfernt sie, weil nur aktive Buchungen zählen.
|
||||
*/
|
||||
function reminder_list(string $from, string $to, int $employeeId = 0, bool $includeDone = false): array
|
||||
{
|
||||
if ($from > $to) {
|
||||
[$from, $to] = [$to, $from];
|
||||
}
|
||||
$sql = BOOKING_SELECT . " WHERE b.status = 'active' AND b.start_date <= ? AND b.end_date >= ?";
|
||||
$params = [add_days($to, 8), add_days($from, -2)];
|
||||
if ($employeeId > 0) {
|
||||
$sql .= ' AND b.employee_id = ?';
|
||||
$params[] = $employeeId;
|
||||
}
|
||||
$sql .= ' ORDER BY b.start_date, b.id';
|
||||
$stmt = db()->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$bookings = $stmt->fetchAll();
|
||||
|
||||
$done = reminder_done_map(array_column($bookings, 'id'));
|
||||
$rows = [];
|
||||
foreach ($bookings as $booking) {
|
||||
foreach (booking_reminders($booking) as $reminder) {
|
||||
if ($reminder['due_date'] < $from || $reminder['due_date'] > $to) {
|
||||
continue;
|
||||
}
|
||||
$isDone = isset($done[reminder_done_key($booking, $reminder['kind'], $reminder['due_date'])]);
|
||||
if ($isDone && !$includeDone) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = $reminder + [
|
||||
'booking' => $booking,
|
||||
'done' => $isDone,
|
||||
];
|
||||
}
|
||||
}
|
||||
usort($rows, static function (array $a, array $b): int {
|
||||
return [$a['due_date'], $a['booking']['trailer_sort'], $a['kind']]
|
||||
<=> [$b['due_date'], $b['booking']['trailer_sort'], $b['kind']];
|
||||
});
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** Sichtbarkeit: Admins sehen alles, Mitarbeiter nur ihre Buchungen. */
|
||||
function reminder_scope_employee(array $user): int
|
||||
{
|
||||
return ($user['role'] ?? '') === 'admin' ? 0 : auth_employee_id($user);
|
||||
}
|
||||
|
||||
function reminder_open_count(array $user, string $until, string $from = ''): int
|
||||
{
|
||||
if ($from === '') {
|
||||
$from = add_days(today_iso(), -30);
|
||||
}
|
||||
$rows = reminder_list($from, $until, reminder_scope_employee($user), false);
|
||||
return count($rows);
|
||||
}
|
||||
|
||||
function reminder_done_set(int $bookingId, string $kind, bool $done, int $userId): bool
|
||||
{
|
||||
$booking = booking_find($bookingId);
|
||||
if (!$booking || $booking['status'] !== 'active') {
|
||||
return false;
|
||||
}
|
||||
$row = null;
|
||||
foreach (booking_reminders($booking) as $reminder) {
|
||||
if ($reminder['kind'] === $kind) {
|
||||
$row = $reminder;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
if ($done) {
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO reminder_done (booking_id, kind, due_date, done_by, done_at) VALUES (?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE done_by = VALUES(done_by), done_at = VALUES(done_at)'
|
||||
);
|
||||
$stmt->execute([$bookingId, $kind, $row['due_date'], $userId, utc_now()]);
|
||||
} else {
|
||||
db()->prepare('DELETE FROM reminder_done WHERE booking_id = ? AND kind = ? AND due_date = ?')
|
||||
->execute([$bookingId, $kind, $row['due_date']]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Kalendergeometrie */
|
||||
|
||||
/**
|
||||
* Verteilt Buchungen einer Zeile auf Lanes. Ein Wechseltag (eine Buchung endet,
|
||||
* eine andere beginnt am selben Tag) ist erlaubt und wird als zweite Lane
|
||||
* dargestellt, damit beide Balken sichtbar bleiben.
|
||||
*
|
||||
* @return array{bookings: array, lanes: int}
|
||||
*/
|
||||
function calendar_lanes(array $bookings): array
|
||||
{
|
||||
usort($bookings, static function (array $a, array $b): int {
|
||||
return [(string) $a['start_date'], (string) $a['end_date'], (int) $a['id']]
|
||||
<=> [(string) $b['start_date'], (string) $b['end_date'], (int) $b['id']];
|
||||
});
|
||||
|
||||
$laneEnds = [];
|
||||
$out = [];
|
||||
foreach ($bookings as $booking) {
|
||||
$lane = 0;
|
||||
while (isset($laneEnds[$lane]) && $laneEnds[$lane] >= $booking['start_date']) {
|
||||
$lane++;
|
||||
}
|
||||
$laneEnds[$lane] = $booking['end_date'];
|
||||
$booking['_lane'] = $lane;
|
||||
$out[] = $booking;
|
||||
}
|
||||
return ['bookings' => $out, 'lanes' => max(1, count($laneEnds))];
|
||||
}
|
||||
|
||||
/** Position eines Balkens im sichtbaren Zeitraum (Prozent). */
|
||||
function calendar_geometry(array $booking, string $from, string $to, int $lanes): array
|
||||
{
|
||||
$total = max(1, days_between($from, $to) + 1);
|
||||
$start = max((string) $booking['start_date'], $from);
|
||||
$end = min((string) $booking['end_date'], $to);
|
||||
$offset = max(0, days_between($from, $start));
|
||||
$span = max(1, days_between($start, $end) + 1);
|
||||
$lane = (int) ($booking['_lane'] ?? 0);
|
||||
return [
|
||||
'left' => $offset / $total * 100,
|
||||
'width' => $span / $total * 100,
|
||||
'top' => $lane / $lanes * 100,
|
||||
'height' => 100 / $lanes,
|
||||
'span' => $span,
|
||||
'cut_start' => (string) $booking['start_date'] < $from,
|
||||
'cut_end' => (string) $booking['end_date'] > $to,
|
||||
];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- Auswertung */
|
||||
|
||||
function bookings_by_date(string $date): array
|
||||
{
|
||||
return booking_list($date, $date, false);
|
||||
}
|
||||
|
||||
/** Nächste Übergaben und Rücknahmen ab heute. */
|
||||
function upcoming_handovers(int $days = 14, int $employeeId = 0): array
|
||||
{
|
||||
$today = today_iso();
|
||||
$until = add_days($today, $days);
|
||||
$bookings = booking_list($today, $until, false, $employeeId);
|
||||
$events = [];
|
||||
foreach ($bookings as $booking) {
|
||||
if ($booking['start_date'] >= $today && $booking['start_date'] <= $until) {
|
||||
$events[] = ['type' => 'handover', 'date' => $booking['start_date'], 'booking' => $booking];
|
||||
}
|
||||
if ($booking['end_date'] >= $today && $booking['end_date'] <= $until) {
|
||||
$events[] = ['type' => 'return', 'date' => $booking['end_date'], 'booking' => $booking];
|
||||
}
|
||||
}
|
||||
usort($events, static function (array $a, array $b): int {
|
||||
return [$a['date'], $a['type']] <=> [$b['date'], $b['type']];
|
||||
});
|
||||
return $events;
|
||||
}
|
||||
28
app/db.php
Normal file
28
app/db.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
function db(): PDO
|
||||
{
|
||||
static $pdo = null;
|
||||
if ($pdo instanceof PDO) {
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
$db = (array) config('db', []);
|
||||
$dsn = sprintf(
|
||||
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
||||
(string) ($db['host'] ?? 'localhost'),
|
||||
(int) ($db['port'] ?? 3306),
|
||||
(string) ($db['name'] ?? ''),
|
||||
(string) ($db['charset'] ?? 'utf8mb4')
|
||||
);
|
||||
|
||||
$pdo = new PDO($dsn, (string) ($db['user'] ?? ''), (string) ($db['password'] ?? ''), [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
]);
|
||||
$pdo->exec("SET time_zone = '+00:00'");
|
||||
return $pdo;
|
||||
}
|
||||
122
app/mail.php
Normal file
122
app/mail.php
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Optionaler täglicher E-Mail-Digest für fällige Erinnerungen.
|
||||
*
|
||||
* Die In-App-Erinnerungen sind immer vorhanden. Dieser Versand ist zusätzlich
|
||||
* und wird über tools/send_reminders.php (Cron) oder /cron/reminders?token=…
|
||||
* ausgelöst. Jede Erinnerung wird genau einmal verschickt; das Protokoll steht
|
||||
* in reminder_mail_log.
|
||||
*/
|
||||
|
||||
function reminder_mail_recipients(): array
|
||||
{
|
||||
$sql = "SELECT u.employee_id, u.email, u.first_name, u.last_name, e.name AS employee_name
|
||||
FROM users u JOIN employees e ON e.id = u.employee_id
|
||||
WHERE u.status = 'active' AND u.employee_id IS NOT NULL AND u.email IS NOT NULL AND u.email <> ''
|
||||
ORDER BY e.sort_order";
|
||||
$out = [];
|
||||
foreach (db()->query($sql)->fetchAll() as $row) {
|
||||
$out[(int) $row['employee_id']] = $row;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt alle offenen, heute (oder in den letzten 7 Tagen) fälligen
|
||||
* Erinnerungen als einen Digest pro Mitarbeiter.
|
||||
*
|
||||
* @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array}
|
||||
*/
|
||||
function reminder_send_due(int $lookbackDays = 7): array
|
||||
{
|
||||
$result = ['enabled' => (bool) config('app.mail_enabled', false), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
|
||||
if (!$result['enabled']) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$today = today_iso();
|
||||
$from = add_days($today, -max(1, $lookbackDays));
|
||||
$recipients = reminder_mail_recipients();
|
||||
$rows = reminder_list($from, $today, 0, false);
|
||||
if (!$rows) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$byEmployee = [];
|
||||
foreach ($rows as $row) {
|
||||
$employeeId = (int) $row['booking']['employee_id'];
|
||||
if (!isset($recipients[$employeeId])) {
|
||||
$result['skipped']++;
|
||||
continue;
|
||||
}
|
||||
// Bereits verschickt?
|
||||
$stmt = db()->prepare('SELECT 1 FROM reminder_mail_log WHERE booking_id = ? AND kind = ? AND due_date = ?');
|
||||
$stmt->execute([(int) $row['booking']['id'], $row['kind'], $row['due_date']]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
$result['skipped']++;
|
||||
continue;
|
||||
}
|
||||
$byEmployee[$employeeId][] = $row;
|
||||
}
|
||||
|
||||
$fromHeader = (string) config('app.mail_from', 'Drink it cold <noreply@localhost>');
|
||||
$appUrl = rtrim((string) config('app.public_url', ''), '/');
|
||||
|
||||
foreach ($byEmployee as $employeeId => $items) {
|
||||
$recipient = $recipients[$employeeId];
|
||||
$lines = [
|
||||
'Guten Tag ' . $recipient['employee_name'] . ',',
|
||||
'',
|
||||
'diese Erinnerungen stehen an:',
|
||||
'',
|
||||
];
|
||||
foreach ($items as $item) {
|
||||
$booking = $item['booking'];
|
||||
$lines[] = '• ' . fmt_date($item['due_date']) . ' – ' . $item['label'];
|
||||
$lines[] = ' ' . $item['message'];
|
||||
$lines[] = ' ' . $booking['customer_name'] . ', ' . $booking['trailer_label'] . ' (' . $booking['trailer_color_name'] . ')';
|
||||
$lines[] = ' Miete: ' . fmt_date($booking['start_date']) . ' bis ' . fmt_date($booking['end_date']);
|
||||
if ($appUrl !== '') {
|
||||
$lines[] = ' ' . $appUrl . '/bookings/' . (int) $booking['id'];
|
||||
}
|
||||
$lines[] = '';
|
||||
}
|
||||
$lines[] = 'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.';
|
||||
$body = implode("\n", $lines);
|
||||
$subject = 'Drink it cold – ' . count($items) . ' fällige Erinnerung' . (count($items) === 1 ? '' : 'en');
|
||||
|
||||
$headers = [
|
||||
'From: ' . $fromHeader,
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: text/plain; charset=UTF-8',
|
||||
'Content-Transfer-Encoding: 8bit',
|
||||
];
|
||||
$ok = @mail(
|
||||
(string) $recipient['email'],
|
||||
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
|
||||
$body,
|
||||
implode("\r\n", $headers)
|
||||
);
|
||||
if (!$ok) {
|
||||
$result['errors'][] = 'Versand an ' . $recipient['email'] . ' fehlgeschlagen.';
|
||||
continue;
|
||||
}
|
||||
|
||||
$log = db()->prepare(
|
||||
'INSERT IGNORE INTO reminder_mail_log (booking_id, kind, due_date, employee_id, sent_to, sent_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
foreach ($items as $item) {
|
||||
$log->execute([
|
||||
(int) $item['booking']['id'], $item['kind'], $item['due_date'],
|
||||
$employeeId, (string) $recipient['email'], utc_now(),
|
||||
]);
|
||||
$result['sent']++;
|
||||
}
|
||||
$result['details'][] = $recipient['email'] . ' (' . count($items) . ')';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
789
app/pages.php
Normal file
789
app/pages.php
Normal file
|
|
@ -0,0 +1,789 @@
|
|||
<?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;
|
||||
}
|
||||
|
||||
$user = auth_user();
|
||||
if ($user !== null && $user['must_change_password'] === 1
|
||||
&& !in_array($path, ['/account', '/logout'], true)
|
||||
) {
|
||||
flash('info', 'Bitte zuerst das eigene Passwort ändern.');
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
if ($path === '/logout') {
|
||||
require_post();
|
||||
auth_logout();
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
$user = auth_require_login();
|
||||
|
||||
if ($path === '/') {
|
||||
page_dashboard($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/calendar') {
|
||||
page_calendar($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/bookings/new') {
|
||||
page_booking_new($user, $method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)$#', $path, $m) === 1) {
|
||||
page_booking_detail($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/panel$#', $path, $m) === 1) {
|
||||
page_booking_panel($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/edit$#', $path, $m) === 1) {
|
||||
page_booking_edit($user, (int) $m[1], $method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/cancel$#', $path, $m) === 1) {
|
||||
page_booking_cancel($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/restore$#', $path, $m) === 1) {
|
||||
page_booking_restore($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/delete$#', $path, $m) === 1) {
|
||||
page_booking_delete($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/move$#', $path, $m) === 1) {
|
||||
page_booking_move($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if ($path === '/api/availability') {
|
||||
api_availability();
|
||||
return;
|
||||
}
|
||||
if ($path === '/search') {
|
||||
page_search($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/reminders') {
|
||||
page_reminders($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/reminders/done') {
|
||||
page_reminder_done($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/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
|
||||
{
|
||||
$expected = (string) config('app.cron_token', '');
|
||||
$given = query_string('token');
|
||||
if ($expected === '' || $given === '' || !hash_equals($expected, $given)) {
|
||||
abort_page(403, 'Kein Zugriff.');
|
||||
}
|
||||
$result = reminder_send_due();
|
||||
json_response($result);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Anmeldung */
|
||||
|
||||
function page_login(string $method): void
|
||||
{
|
||||
if (auth_user() !== null) {
|
||||
redirect('/');
|
||||
}
|
||||
$error = '';
|
||||
$first = '';
|
||||
$last = '';
|
||||
$remember = true;
|
||||
|
||||
if ($method === 'POST') {
|
||||
$first = post_string('first_name');
|
||||
$last = post_string('last_name');
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
$remember = post_string('remember') === '1';
|
||||
$next = safe_next(post_string('next'), '/');
|
||||
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} elseif ($first === '' || $last === '' || $password === '') {
|
||||
$error = 'Bitte Vorname, Nachname und Passwort angeben.';
|
||||
} else {
|
||||
try {
|
||||
$user = auth_verify_login($first, $last, $password);
|
||||
auth_login($user, $remember);
|
||||
if ((int) $user['must_change_password'] === 1) {
|
||||
flash('info', 'Bitte zuerst ein neues Passwort vergeben.');
|
||||
redirect('/account');
|
||||
}
|
||||
redirect($next);
|
||||
} catch (RuntimeException $e) {
|
||||
$error = match ($e->getMessage()) {
|
||||
'locked' => 'Zu viele Fehlversuche. Bitte in einigen Minuten erneut versuchen.',
|
||||
'disabled' => 'Dieses Konto ist deaktiviert. Bitte beim Administrator melden.',
|
||||
default => 'Vorname, Nachname oder Passwort stimmen nicht.',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render_standalone('login', [
|
||||
'error' => $error,
|
||||
'first' => $first,
|
||||
'last' => $last,
|
||||
'remember' => $remember,
|
||||
'next' => safe_next(query_string('next') ?: post_string('next'), '/'),
|
||||
], 'Anmelden');
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Übersicht */
|
||||
|
||||
function page_dashboard(array $user): void
|
||||
{
|
||||
$today = today_iso();
|
||||
$trailers = trailers_all();
|
||||
$todayBookings = bookings_by_date($today);
|
||||
$byTrailer = [];
|
||||
foreach ($todayBookings as $booking) {
|
||||
$byTrailer[(int) $booking['trailer_id']][] = $booking;
|
||||
}
|
||||
|
||||
$upcoming = upcoming_handovers(14, reminder_scope_employee($user));
|
||||
$employeeScope = reminder_scope_employee($user);
|
||||
$allReminders = reminder_list(add_days($today, -30), add_days($today, 7), $employeeScope, false);
|
||||
$openReminderCount = count($allReminders);
|
||||
$reminders = array_slice($allReminders, 0, 6);
|
||||
$upcoming = array_slice($upcoming, 0, 10);
|
||||
|
||||
$roadmap = [];
|
||||
foreach ($trailers as $trailer) {
|
||||
$roadmap[] = [
|
||||
'trailer' => $trailer,
|
||||
'bookings' => $byTrailer[(int) $trailer['id']] ?? [],
|
||||
];
|
||||
}
|
||||
|
||||
$weekEnd = add_days($today, 7);
|
||||
$handoverCount = 0;
|
||||
foreach (booking_list($today, $weekEnd, false, $employeeScope) as $booking) {
|
||||
if ($booking['start_date'] >= $today && $booking['start_date'] <= $weekEnd) {
|
||||
$handoverCount++;
|
||||
}
|
||||
}
|
||||
|
||||
render_page('dashboard', [
|
||||
'today' => $today,
|
||||
'trailers' => $trailers,
|
||||
'roadmap' => $roadmap,
|
||||
'upcoming' => $upcoming,
|
||||
'reminders' => $reminders,
|
||||
'openReminderCount' => $openReminderCount,
|
||||
'handoverCount' => $handoverCount,
|
||||
'employeeScope' => $employeeScope,
|
||||
], 'Übersicht');
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Kalender */
|
||||
|
||||
function calendar_url(string $date, string $view, int $employeeId, bool $showCancelled): string
|
||||
{
|
||||
$params = ['view' => $view, 'date' => $date];
|
||||
if ($employeeId > 0) {
|
||||
$params['employee'] = $employeeId;
|
||||
}
|
||||
if ($showCancelled) {
|
||||
$params['cancelled'] = '1';
|
||||
}
|
||||
return '/calendar?' . http_build_query($params);
|
||||
}
|
||||
|
||||
function page_calendar(array $user): void
|
||||
{
|
||||
$view = query_string('view', 'week');
|
||||
if (!in_array($view, ['day', 'week', 'month'], true)) {
|
||||
$view = 'week';
|
||||
}
|
||||
$date = query_string('date');
|
||||
if (!valid_date($date)) {
|
||||
$date = today_iso();
|
||||
}
|
||||
$employeeId = query_int('employee');
|
||||
$showCancelled = query_string('cancelled') === '1';
|
||||
|
||||
if ($view === 'day') {
|
||||
$from = $to = $date;
|
||||
} elseif ($view === 'month') {
|
||||
$from = month_start($date);
|
||||
$to = month_end($date);
|
||||
} else {
|
||||
$from = week_start($date);
|
||||
$to = add_days($from, 6);
|
||||
}
|
||||
|
||||
$trailers = trailers_all();
|
||||
$bookings = booking_list($from, $to, $showCancelled, $employeeId);
|
||||
$byTrailer = [];
|
||||
foreach ($bookings as $booking) {
|
||||
$byTrailer[(int) $booking['trailer_id']][] = $booking;
|
||||
}
|
||||
|
||||
$days = [];
|
||||
$cursor = $from;
|
||||
while ($cursor <= $to) {
|
||||
$days[] = [
|
||||
'iso' => $cursor,
|
||||
'day' => (int) date_obj($cursor)->format('j'),
|
||||
'weekday' => fmt_weekday_short($cursor),
|
||||
'is_today' => $cursor === today_iso(),
|
||||
'is_weekend' => (int) date_obj($cursor)->format('N') >= 6,
|
||||
'is_first_of_month' => date_obj($cursor)->format('j') === '1',
|
||||
];
|
||||
$cursor = add_days($cursor, 1);
|
||||
}
|
||||
|
||||
$barBase = ['day' => 76, 'week' => 48, 'month' => 28][$view];
|
||||
$rowMin = ['day' => 104, 'week' => 64, 'month' => 40][$view];
|
||||
|
||||
$rows = [];
|
||||
foreach ($trailers as $trailer) {
|
||||
$laneInfo = calendar_lanes($byTrailer[(int) $trailer['id']] ?? []);
|
||||
$lanes = $laneInfo['lanes'];
|
||||
$bars = [];
|
||||
foreach ($laneInfo['bookings'] as $booking) {
|
||||
$bars[] = [
|
||||
'booking' => $booking,
|
||||
'geo' => calendar_geometry($booking, $from, $to, $lanes),
|
||||
];
|
||||
}
|
||||
$rows[] = [
|
||||
'trailer' => $trailer,
|
||||
'lanes' => $lanes,
|
||||
'bars' => $bars,
|
||||
'height' => max($rowMin, $barBase * $lanes + 16),
|
||||
];
|
||||
}
|
||||
|
||||
$prevDate = $nextDate = $date;
|
||||
if ($view === 'day') {
|
||||
$prevDate = add_days($date, -1);
|
||||
$nextDate = add_days($date, 1);
|
||||
} elseif ($view === 'week') {
|
||||
$prevDate = add_days($date, -7);
|
||||
$nextDate = add_days($date, 7);
|
||||
} else {
|
||||
$prevDate = date_obj(month_start($date))->modify('first day of previous month')->format('Y-m-d');
|
||||
$nextDate = date_obj(month_start($date))->modify('first day of next month')->format('Y-m-d');
|
||||
}
|
||||
|
||||
if ($view === 'day') {
|
||||
$title = fmt_date_long($date);
|
||||
} elseif ($view === 'week') {
|
||||
$title = 'KW ' . date_obj($from)->format('W') . ' · ' . fmt_date_range($from, $to);
|
||||
} else {
|
||||
$title = fmt_month($date);
|
||||
}
|
||||
|
||||
$employees = employees_all();
|
||||
render_page('calendar', [
|
||||
'view' => $view,
|
||||
'date' => $date,
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'days' => $days,
|
||||
'rows' => $rows,
|
||||
'calTitle' => $title,
|
||||
'prevDate' => $prevDate,
|
||||
'nextDate' => $nextDate,
|
||||
'today' => today_iso(),
|
||||
'employeeId' => $employeeId,
|
||||
'showCancelled' => $showCancelled,
|
||||
'employees' => $employees,
|
||||
'bookingCount' => count($bookings),
|
||||
'urlFor' => static function (string $d) use ($view, $employeeId, $showCancelled): string {
|
||||
return calendar_url($d, $view, $employeeId, $showCancelled);
|
||||
},
|
||||
], 'Kalender');
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Buchungen */
|
||||
|
||||
function booking_form_context(array $user, ?array $booking = null, array $values = [], array $errors = []): array
|
||||
{
|
||||
$trailers = trailers_all(false);
|
||||
$employees = employees_all(false);
|
||||
$currentTrailer = (int) ($values['trailer_id'] ?? 0);
|
||||
$currentEmployee = (int) ($values['employee_id'] ?? 0);
|
||||
$trailerOptions = array_values(array_filter(
|
||||
$trailers,
|
||||
static fn (array $t): bool => (int) $t['active'] === 1 || (int) $t['id'] === $currentTrailer
|
||||
));
|
||||
$employeeOptions = array_values(array_filter(
|
||||
$employees,
|
||||
static fn (array $e): bool => (int) $e['active'] === 1 || (int) $e['id'] === $currentEmployee
|
||||
));
|
||||
|
||||
return [
|
||||
'booking' => $booking,
|
||||
'values' => $values,
|
||||
'errors' => $errors,
|
||||
'trailers' => $trailerOptions,
|
||||
'employees' => $employeeOptions,
|
||||
'user' => $user,
|
||||
'isEdit' => $booking !== null,
|
||||
];
|
||||
}
|
||||
|
||||
function form_values_from_input(array $data): array
|
||||
{
|
||||
return [
|
||||
'trailer_id' => (int) $data['trailer_id'],
|
||||
'employee_id' => (int) $data['employee_id'],
|
||||
'start_date' => (string) $data['start_date'],
|
||||
'end_date' => (string) $data['end_date'],
|
||||
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
|
||||
'total' => number_format($data['total_cents'] / 100, 2, ',', ''),
|
||||
'invoice' => (int) $data['invoice'],
|
||||
'kind' => (string) $data['kind'],
|
||||
'customer_name' => (string) $data['customer_name'],
|
||||
'street' => (string) $data['street'],
|
||||
'city' => (string) $data['city'],
|
||||
'mobile' => (string) $data['mobile'],
|
||||
'email' => (string) $data['email'],
|
||||
];
|
||||
}
|
||||
|
||||
function page_booking_new(array $user, string $method): void
|
||||
{
|
||||
$trailers = trailers_all();
|
||||
$employees = employees_all();
|
||||
if (!$trailers || !$employees) {
|
||||
abort_page(500, 'Es sind keine Kühlanhänger oder Mitarbeiter hinterlegt.');
|
||||
}
|
||||
|
||||
$start = query_string('start');
|
||||
if (!valid_date($start)) {
|
||||
$start = today_iso();
|
||||
}
|
||||
$end = query_string('end');
|
||||
if (!valid_date($end) || $end < $start) {
|
||||
$end = add_days($start, 3);
|
||||
}
|
||||
$trailerId = query_int('trailer');
|
||||
if (!array_filter($trailers, static fn (array $t): bool => (int) $t['id'] === $trailerId)) {
|
||||
$trailerId = (int) $trailers[0]['id'];
|
||||
}
|
||||
$employeeId = auth_employee_id($user);
|
||||
if (!array_filter($employees, static fn (array $e): bool => (int) $e['id'] === $employeeId)) {
|
||||
$employeeId = (int) $employees[0]['id'];
|
||||
}
|
||||
|
||||
$values = [
|
||||
'trailer_id' => $trailerId,
|
||||
'employee_id' => $employeeId,
|
||||
'start_date' => $start,
|
||||
'end_date' => $end,
|
||||
'deposit' => '',
|
||||
'total' => '',
|
||||
'invoice' => 0,
|
||||
'kind' => 'pickup',
|
||||
'customer_name' => '',
|
||||
'street' => '',
|
||||
'city' => '',
|
||||
'mobile' => '',
|
||||
'email' => '',
|
||||
];
|
||||
$errors = [];
|
||||
|
||||
if ($method === 'POST') {
|
||||
require_post();
|
||||
$data = booking_input($_POST);
|
||||
$values = form_values_from_input($data);
|
||||
$errors = booking_validate($data);
|
||||
if (!$errors) {
|
||||
try {
|
||||
$id = booking_create($data, (int) $user['id']);
|
||||
flash('success', 'Buchung für ' . $data['customer_name'] . ' wurde angelegt.');
|
||||
redirect('/bookings/' . $id);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$errors = json_decode($e->getMessage(), true) ?: ['form' => 'Buchung konnte nicht gespeichert werden.'];
|
||||
}
|
||||
}
|
||||
http_response_code(422);
|
||||
}
|
||||
|
||||
render_page('booking_form', booking_form_context($user, null, $values, $errors), 'Neue Buchung');
|
||||
}
|
||||
|
||||
function page_booking_edit(array $user, int $id, string $method): void
|
||||
{
|
||||
$booking = booking_find($id);
|
||||
if (!$booking) {
|
||||
abort_page(404, 'Buchung nicht gefunden.');
|
||||
}
|
||||
|
||||
$values = [
|
||||
'trailer_id' => (int) $booking['trailer_id'],
|
||||
'employee_id' => (int) $booking['employee_id'],
|
||||
'start_date' => (string) $booking['start_date'],
|
||||
'end_date' => (string) $booking['end_date'],
|
||||
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
|
||||
'total' => number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
|
||||
'invoice' => (int) $booking['invoice'],
|
||||
'kind' => (string) $booking['kind'],
|
||||
'customer_name' => (string) $booking['customer_name'],
|
||||
'street' => (string) $booking['street'],
|
||||
'city' => (string) $booking['city'],
|
||||
'mobile' => (string) $booking['mobile'],
|
||||
'email' => (string) $booking['email'],
|
||||
];
|
||||
$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']]);
|
||||
return [
|
||||
'booking' => $booking,
|
||||
'reminders' => $reminders,
|
||||
'doneMap' => $done,
|
||||
'copyText' => booking_copy_text($booking),
|
||||
'canDelete' => ($user['role'] ?? '') === 'admin',
|
||||
];
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
booking_delete($id);
|
||||
flash('success', 'Buchung von ' . $booking['customer_name'] . ' wurde endgültig gelöscht.');
|
||||
redirect('/calendar?view=month&date=' . $booking['start_date']);
|
||||
}
|
||||
|
||||
function page_booking_move(array $user, int $id): void
|
||||
{
|
||||
require_post();
|
||||
$result = booking_move(
|
||||
$id,
|
||||
post_string('start_date'),
|
||||
(int) post_string('trailer_id'),
|
||||
(int) $user['id']
|
||||
);
|
||||
if (isset($result['error'])) {
|
||||
json_response(['ok' => false, 'error' => $result['error']], 409);
|
||||
}
|
||||
json_response($result);
|
||||
}
|
||||
|
||||
function api_availability(): void
|
||||
{
|
||||
auth_require_login();
|
||||
$trailerId = query_int('trailer');
|
||||
$start = query_string('start');
|
||||
$end = query_string('end');
|
||||
$exclude = query_int('exclude');
|
||||
if ($trailerId <= 0 || !valid_date($start) || !valid_date($end) || $end < $start) {
|
||||
json_response(['ok' => false, 'error' => 'Bitte Anhänger und Zeitraum angeben.'], 422);
|
||||
}
|
||||
$conflicts = booking_conflicts($trailerId, $start, $end, $exclude);
|
||||
json_response([
|
||||
'ok' => !$conflicts,
|
||||
'conflicts' => array_map(static fn (array $b): array => [
|
||||
'id' => (int) $b['id'],
|
||||
'customer' => $b['customer_name'],
|
||||
'start' => $b['start_date'],
|
||||
'end' => $b['end_date'],
|
||||
], $conflicts),
|
||||
]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Suche */
|
||||
|
||||
function page_search(array $user): void
|
||||
{
|
||||
$query = query_string('q');
|
||||
$results = $query !== '' ? booking_search($query) : [];
|
||||
render_page('search', [
|
||||
'query' => $query,
|
||||
'results' => $results,
|
||||
], 'Suche');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Erinnerungen */
|
||||
|
||||
function page_reminders(array $user): void
|
||||
{
|
||||
$range = query_string('range', '14');
|
||||
if (!in_array($range, ['7', '14', '30', 'all'], true)) {
|
||||
$range = '14';
|
||||
}
|
||||
$scope = reminder_scope_employee($user);
|
||||
$employeeFilter = $scope;
|
||||
if (($user['role'] ?? '') === 'admin') {
|
||||
$employeeFilter = query_int('employee');
|
||||
}
|
||||
$showDone = query_string('done') === '1';
|
||||
$today = today_iso();
|
||||
|
||||
if ($range === 'all') {
|
||||
$from = add_days($today, -365);
|
||||
$to = add_days($today, 365);
|
||||
} else {
|
||||
$from = add_days($today, -30);
|
||||
$to = add_days($today, (int) $range);
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
$hasEmployee = $scope > 0 || ($user['role'] ?? '') === 'admin';
|
||||
if ($hasEmployee) {
|
||||
$rows = reminder_list($from, $to, $employeeFilter, $showDone);
|
||||
}
|
||||
$groups = [];
|
||||
foreach ($rows as $row) {
|
||||
$groups[$row['due_date']][] = $row;
|
||||
}
|
||||
|
||||
$employees = employees_all();
|
||||
render_page('reminders', [
|
||||
'rows' => $rows,
|
||||
'groups' => $groups,
|
||||
'range' => $range,
|
||||
'employeeFilter' => $employeeFilter,
|
||||
'showDone' => $showDone,
|
||||
'employees' => $employees,
|
||||
'hasEmployee' => $hasEmployee,
|
||||
'isAdmin' => ($user['role'] ?? '') === 'admin',
|
||||
'today' => $today,
|
||||
'mailEnabled' => (bool) config('app.mail_enabled', false),
|
||||
], 'Erinnerungen');
|
||||
}
|
||||
|
||||
function page_reminder_done(array $user): void
|
||||
{
|
||||
require_post();
|
||||
$bookingId = (int) post_string('booking_id');
|
||||
$kind = post_string('kind');
|
||||
$done = post_string('done') === '1';
|
||||
$booking = booking_find($bookingId);
|
||||
if (!$booking) {
|
||||
abort_page(404, 'Buchung nicht gefunden.');
|
||||
}
|
||||
$allowed = ($user['role'] ?? '') === 'admin'
|
||||
|| (auth_employee_id($user) > 0 && (int) $booking['employee_id'] === auth_employee_id($user));
|
||||
if (!$allowed) {
|
||||
abort_page(403, 'Diese Erinnerung gehört zu einem anderen Mitarbeiter.');
|
||||
}
|
||||
if (!reminder_done_set($bookingId, $kind, $done, (int) $user['id'])) {
|
||||
abort_page(422, 'Erinnerung nicht gefunden.');
|
||||
}
|
||||
flash('success', $done ? 'Erinnerung als erledigt markiert.' : 'Erinnerung wieder geöffnet.');
|
||||
$back = safe_next(post_string('return_to'), '/reminders');
|
||||
redirect($back);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Konto */
|
||||
|
||||
function page_account(array $user, string $method): void
|
||||
{
|
||||
$errors = [];
|
||||
if ($method === 'POST') {
|
||||
require_post();
|
||||
$current = (string) ($_POST['current_password'] ?? '');
|
||||
$new = (string) ($_POST['new_password'] ?? '');
|
||||
$repeat = (string) ($_POST['repeat_password'] ?? '');
|
||||
if (!password_verify($current, (string) $user['password_hash'])) {
|
||||
$errors['current_password'] = 'Das aktuelle Passwort stimmt nicht.';
|
||||
}
|
||||
if (mb_strlen($new) < 8) {
|
||||
$errors['new_password'] = 'Das neue Passwort muss mindestens 8 Zeichen haben.';
|
||||
}
|
||||
if ($new !== $repeat) {
|
||||
$errors['repeat_password'] = 'Die beiden neuen Passwörter stimmen nicht überein.';
|
||||
}
|
||||
if (!$errors) {
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
$stmt = $pdo->prepare('UPDATE users SET password_hash = ?, password_changed_at = ?, updated_at = ?,
|
||||
must_change_password = 0, auth_epoch = auth_epoch + 1 WHERE id = ?');
|
||||
$stmt->execute([hash_password($new), utc_now(), utc_now(), (int) $user['id']]);
|
||||
$newEpoch = (int) $pdo->query('SELECT auth_epoch FROM users WHERE id = ' . (int) $user['id'])->fetchColumn();
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([(int) $user['id']]);
|
||||
$pdo->commit();
|
||||
$_SESSION['epoch'] = $newEpoch;
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
flash('success', 'Das Passwort wurde geändert. Andere Geräte müssen sich neu anmelden.');
|
||||
redirect('/');
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
http_response_code(422);
|
||||
}
|
||||
|
||||
render_page('account', [
|
||||
'errors' => $errors,
|
||||
'employee' => auth_employee_id($user) > 0 ? employee_find(auth_employee_id($user)) : null,
|
||||
], 'Mein Konto');
|
||||
}
|
||||
433
app/util.php
Normal file
433
app/util.php
Normal file
|
|
@ -0,0 +1,433 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Kleine Helfer: Konfiguration, Session, CSRF, Ausgabe, Zeit und Geld. */
|
||||
|
||||
function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$value = $GLOBALS['dic_config'] ?? [];
|
||||
foreach (explode('.', $key) as $part) {
|
||||
if (!is_array($value) || !array_key_exists($part, $value)) {
|
||||
return $default;
|
||||
}
|
||||
$value = $value[$part];
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function is_https(): bool
|
||||
{
|
||||
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
|
||||
return true;
|
||||
}
|
||||
return strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
|
||||
}
|
||||
|
||||
function security_headers(): void
|
||||
{
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('X-Frame-Options: DENY');
|
||||
header('X-Robots-Tag: noindex, nofollow, noarchive');
|
||||
header('Referrer-Policy: same-origin');
|
||||
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
|
||||
header(
|
||||
"Content-Security-Policy: default-src 'self'; img-src 'self' data:; "
|
||||
. "font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; "
|
||||
. "connect-src 'self'; media-src 'self'; form-action 'self'; "
|
||||
. "frame-ancestors 'none'; base-uri 'none'"
|
||||
);
|
||||
header('Cache-Control: no-store');
|
||||
if (is_https()) {
|
||||
header('Strict-Transport-Security: max-age=15552000');
|
||||
}
|
||||
}
|
||||
|
||||
function start_session(): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
return;
|
||||
}
|
||||
$absolute = (int) config('app.session_absolute_seconds', 7776000);
|
||||
ini_set('session.use_strict_mode', '1');
|
||||
ini_set('session.use_only_cookies', '1');
|
||||
ini_set('session.cookie_httponly', '1');
|
||||
ini_set('session.cookie_samesite', 'Lax');
|
||||
ini_set('session.cookie_secure', is_https() ? '1' : '0');
|
||||
ini_set('session.cookie_path', '/');
|
||||
ini_set('session.gc_maxlifetime', (string) $absolute);
|
||||
session_name('DIC_SESSION');
|
||||
session_start();
|
||||
}
|
||||
|
||||
function utc_now(): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
function utc_after(int $seconds): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s', time() + $seconds);
|
||||
}
|
||||
|
||||
function e(mixed $value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
function e_attr(mixed $value): string
|
||||
{
|
||||
return e($value);
|
||||
}
|
||||
|
||||
function url(string $path = '/'): string
|
||||
{
|
||||
$base = rtrim((string) config('app.base_path', ''), '/');
|
||||
if ($path === '' || $path[0] !== '/') {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
return $base . $path;
|
||||
}
|
||||
|
||||
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
|
||||
const DIC_ASSET_VERSION = '1';
|
||||
|
||||
function asset(string $path): string
|
||||
{
|
||||
return url('/assets/' . ltrim($path, '/')) . '?v=' . DIC_ASSET_VERSION;
|
||||
}
|
||||
|
||||
function redirect(string $path, int $status = 303): never
|
||||
{
|
||||
header('Location: ' . url($path), true, $status);
|
||||
exit;
|
||||
}
|
||||
|
||||
function current_path(): string
|
||||
{
|
||||
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
|
||||
$base = rtrim((string) config('app.base_path', ''), '/');
|
||||
if ($base !== '' && str_starts_with($path, $base)) {
|
||||
$path = substr($path, strlen($base));
|
||||
}
|
||||
return '/' . trim($path, '/');
|
||||
}
|
||||
|
||||
function client_ip(): string
|
||||
{
|
||||
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
|
||||
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
|
||||
}
|
||||
|
||||
function request_method(): string
|
||||
{
|
||||
return strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||
}
|
||||
|
||||
function is_post(): bool
|
||||
{
|
||||
return request_method() === 'POST';
|
||||
}
|
||||
|
||||
function post_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_POST[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function post_array(string $key): array
|
||||
{
|
||||
$value = $_POST[$key] ?? [];
|
||||
return is_array($value) ? $value : [];
|
||||
}
|
||||
|
||||
function query_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_GET[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function query_int(string $key, int $default = 0): int
|
||||
{
|
||||
$value = $_GET[$key] ?? null;
|
||||
return is_numeric($value) ? (int) $value : $default;
|
||||
}
|
||||
|
||||
function wants_json(): bool
|
||||
{
|
||||
$accept = strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? ''));
|
||||
return str_contains($accept, 'application/json')
|
||||
|| strtolower((string) ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === 'fetch';
|
||||
}
|
||||
|
||||
function json_response(array $payload, int $status = 200): never
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
function flash(string $type, string $message): void
|
||||
{
|
||||
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
|
||||
}
|
||||
|
||||
function flash_pull(): array
|
||||
{
|
||||
$items = $_SESSION['flash'] ?? [];
|
||||
unset($_SESSION['flash']);
|
||||
return is_array($items) ? $items : [];
|
||||
}
|
||||
|
||||
function csrf_token(): string
|
||||
{
|
||||
if (empty($_SESSION['csrf'])) {
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
return (string) $_SESSION['csrf'];
|
||||
}
|
||||
|
||||
function csrf_field(): string
|
||||
{
|
||||
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
|
||||
}
|
||||
|
||||
function csrf_valid(): bool
|
||||
{
|
||||
$sent = $_POST['_csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
|
||||
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
|
||||
}
|
||||
|
||||
function require_post(): void
|
||||
{
|
||||
if (!is_post()) {
|
||||
abort_page(405, 'Diese Aktion ist nur per POST möglich.');
|
||||
}
|
||||
if (!csrf_valid()) {
|
||||
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte die Seite neu laden und erneut versuchen.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Nur lokale Pfade als Rücksprungziel zulassen. */
|
||||
function safe_next(string $next, string $fallback = '/'): string
|
||||
{
|
||||
$next = trim($next);
|
||||
if ($next === '' || $next[0] !== '/' || str_starts_with($next, '//') || str_contains($next, '\\')) {
|
||||
return $fallback;
|
||||
}
|
||||
return $next;
|
||||
}
|
||||
|
||||
function abort_page(int $code, string $message): never
|
||||
{
|
||||
http_response_code($code);
|
||||
$titles = [403 => 'Kein Zugriff', 404 => 'Nicht gefunden', 405 => 'Nicht erlaubt', 419 => 'Sitzung abgelaufen'];
|
||||
$title = $titles[$code] ?? 'Fehler';
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
echo '<!doctype html><html lang="de"><head><meta charset="utf-8">'
|
||||
. '<meta name="viewport" content="width=device-width, initial-scale=1">'
|
||||
. '<title>' . e($title) . ' · Drink it cold</title>'
|
||||
. '<link rel="stylesheet" href="' . e(asset('app.css')) . '"></head>'
|
||||
. '<body class="error-page"><div class="error-card">'
|
||||
. '<img src="' . e(asset('logo-mark.svg')) . '" alt="" width="64" height="46">'
|
||||
. '<p class="eyebrow">Drink it cold · Terminplanung</p>'
|
||||
. '<h1>' . e($title) . '</h1><p>' . e($message) . '</p>'
|
||||
. '<p><a class="btn primary" href="' . e(url('/')) . '">Zur Übersicht</a></p>'
|
||||
. '</div></body></html>';
|
||||
exit;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Datum */
|
||||
|
||||
function today_iso(): string
|
||||
{
|
||||
return date('Y-m-d');
|
||||
}
|
||||
|
||||
function valid_date(?string $iso): bool
|
||||
{
|
||||
if ($iso === null || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $iso)) {
|
||||
return false;
|
||||
}
|
||||
[$y, $m, $d] = array_map('intval', explode('-', $iso));
|
||||
return checkdate($m, $d, $y);
|
||||
}
|
||||
|
||||
function date_obj(string $iso): DateTimeImmutable
|
||||
{
|
||||
return new DateTimeImmutable($iso . ' 12:00:00', new DateTimeZone('Europe/Berlin'));
|
||||
}
|
||||
|
||||
function add_days(string $iso, int $days): string
|
||||
{
|
||||
return date_obj($iso)->modify(($days >= 0 ? '+' : '') . $days . ' days')->format('Y-m-d');
|
||||
}
|
||||
|
||||
function days_between(string $from, string $to): int
|
||||
{
|
||||
return (int) date_obj($from)->diff(date_obj($to))->format('%r%a');
|
||||
}
|
||||
|
||||
function week_start(string $iso): string
|
||||
{
|
||||
$date = date_obj($iso);
|
||||
$weekday = (int) $date->format('N');
|
||||
return $date->modify('-' . ($weekday - 1) . ' days')->format('Y-m-d');
|
||||
}
|
||||
|
||||
function month_start(string $iso): string
|
||||
{
|
||||
return date_obj($iso)->modify('first day of this month')->format('Y-m-d');
|
||||
}
|
||||
|
||||
function month_end(string $iso): string
|
||||
{
|
||||
return date_obj($iso)->modify('last day of this month')->format('Y-m-d');
|
||||
}
|
||||
|
||||
function fmt_date(string $iso): string
|
||||
{
|
||||
return valid_date($iso) ? date_obj($iso)->format('d.m.Y') : '–';
|
||||
}
|
||||
|
||||
function fmt_date_short(string $iso): string
|
||||
{
|
||||
return valid_date($iso) ? date_obj($iso)->format('d.m.y') : '–';
|
||||
}
|
||||
|
||||
function fmt_date_long(string $iso): string
|
||||
{
|
||||
if (!valid_date($iso)) {
|
||||
return '–';
|
||||
}
|
||||
$days = ['', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
|
||||
$months = ['', 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||||
$date = date_obj($iso);
|
||||
return $days[(int) $date->format('N')] . ', ' . (int) $date->format('j') . '. ' . $months[(int) $date->format('n')] . ' ' . $date->format('Y');
|
||||
}
|
||||
|
||||
function fmt_month(string $iso): string
|
||||
{
|
||||
$months = ['', 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||||
return $months[(int) date_obj($iso)->format('n')] . ' ' . date_obj($iso)->format('Y');
|
||||
}
|
||||
|
||||
function fmt_weekday_short(string $iso): string
|
||||
{
|
||||
$days = ['', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
|
||||
return $days[(int) date_obj($iso)->format('N')];
|
||||
}
|
||||
|
||||
function fmt_date_range(string $from, string $to): string
|
||||
{
|
||||
if ($from === $to) {
|
||||
return fmt_date($from);
|
||||
}
|
||||
if (date_obj($from)->format('Y-m') === date_obj($to)->format('Y-m')) {
|
||||
return (int) date_obj($from)->format('j') . '.–' . fmt_date($to);
|
||||
}
|
||||
return fmt_date($from) . ' – ' . fmt_date($to);
|
||||
}
|
||||
|
||||
function fmt_datetime(?string $utc): string
|
||||
{
|
||||
if ($utc === null || $utc === '') {
|
||||
return '–';
|
||||
}
|
||||
try {
|
||||
$date = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
|
||||
return $date->setTimezone(new DateTimeZone('Europe/Berlin'))->format('d.m.Y H:i');
|
||||
} catch (Throwable) {
|
||||
return '–';
|
||||
}
|
||||
}
|
||||
|
||||
function relative_day(string $iso): string
|
||||
{
|
||||
$diff = days_between(today_iso(), $iso);
|
||||
return match (true) {
|
||||
$diff === 0 => 'Heute',
|
||||
$diff === 1 => 'Morgen',
|
||||
$diff === -1 => 'Gestern',
|
||||
$diff < 0 => abs($diff) . ' Tage überfällig',
|
||||
default => 'in ' . $diff . ' Tagen',
|
||||
};
|
||||
}
|
||||
|
||||
function greeting(): string
|
||||
{
|
||||
$hour = (int) date('G');
|
||||
if ($hour < 11) {
|
||||
return 'Guten Morgen';
|
||||
}
|
||||
if ($hour < 18) {
|
||||
return 'Guten Tag';
|
||||
}
|
||||
return 'Guten Abend';
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Geld */
|
||||
|
||||
function fmt_money(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, ',', '.') . ' €';
|
||||
}
|
||||
|
||||
function parse_money(string $value): int
|
||||
{
|
||||
$value = trim($value);
|
||||
$value = str_replace(["\u{00A0}", ' ', '€', 'EUR'], '', $value);
|
||||
$value = preg_replace('/[^0-9,.\-]/u', '', $value) ?? '';
|
||||
if ($value === '' || $value === '-') {
|
||||
return 0;
|
||||
}
|
||||
if (str_contains($value, ',')) {
|
||||
$value = str_replace('.', '', $value);
|
||||
$value = str_replace(',', '.', $value);
|
||||
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $value) === 1) {
|
||||
$value = str_replace('.', '', $value);
|
||||
}
|
||||
return (int) round((float) $value * 100);
|
||||
}
|
||||
|
||||
function due_cents(int $total, int $deposit): int
|
||||
{
|
||||
return $total - $deposit;
|
||||
}
|
||||
|
||||
/** Lesbare Textfarbe für eine Anhängerfarbe. */
|
||||
function contrast_color(string $hex): string
|
||||
{
|
||||
$hex = ltrim($hex, '#');
|
||||
if (strlen($hex) !== 6) {
|
||||
return '#ffffff';
|
||||
}
|
||||
$r = hexdec(substr($hex, 0, 2)) / 255;
|
||||
$g = hexdec(substr($hex, 2, 2)) / 255;
|
||||
$b = hexdec(substr($hex, 4, 2)) / 255;
|
||||
$channel = static function (float $c): float {
|
||||
return $c <= 0.03928 ? $c / 12.92 : (($c + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
$luminance = 0.2126 * $channel($r) + 0.7152 * $channel($g) + 0.0722 * $channel($b);
|
||||
return $luminance > 0.46 ? '#10202c' : '#ffffff';
|
||||
}
|
||||
|
||||
function initials(string $name): string
|
||||
{
|
||||
$parts = preg_split('/\s+/', trim($name)) ?: [];
|
||||
$out = '';
|
||||
foreach (array_slice($parts, 0, 2) as $part) {
|
||||
if ($part !== '') {
|
||||
$out .= mb_strtoupper(mb_substr($part, 0, 1));
|
||||
}
|
||||
}
|
||||
return $out !== '' ? $out : '?';
|
||||
}
|
||||
|
||||
function truncate(string $value, int $length): string
|
||||
{
|
||||
if (mb_strlen($value) <= $length) {
|
||||
return $value;
|
||||
}
|
||||
return mb_substr($value, 0, max(0, $length - 1)) . '…';
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue