drink-it-cold/app/data.php
torsten 7fd77d58d7 Rechnungsnummer zur Buchung ergänzen (Feld „Rechnung" der Vorlage)
Die Vorlage Neuanlage enthält bei „Rechnung" eine Rechnungsnummer
(RE2026054), nicht nur Ja/Nein. Neu:

- bookings.invoice_no (VARCHAR 40, Migration 004)
- Formularfeld „Rechnungsnummer": eine eingetragene Nummer setzt
  „Rechnung" automatisch auf JA (auch serverseitig)
- Detail, Panel und Kopiertext zeigen die Nummer („Rechnung: JA (RE…)")
- Validierung: max. 40 Zeichen, nur Buchstaben, Ziffern und . / - sowie
  Leerzeichen
- Cache-Buster auf Version 11
2026-11-18 21:27:50 +01:00

747 lines
29 KiB
PHP

<?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');
if (array_key_exists('rent_cents', $source) || array_key_exists('delivery_cents', $source)) {
$rent = max(0, (int) ($source['rent_cents'] ?? 0));
$delivery = max(0, (int) ($source['delivery_cents'] ?? 0));
} elseif (array_key_exists('rent', $source) || array_key_exists('delivery', $source)) {
$rent = parse_money((string) ($source['rent'] ?? '0'));
$delivery = parse_money((string) ($source['delivery'] ?? '0'));
} else {
// Aufrufer ohne getrennte Beträge: Gesamtbetrag gilt als Miete.
$rent = parse_money((string) ($source['total'] ?? '0'));
$delivery = 0;
}
$invoiceNo = trim((string) ($source['invoice_no'] ?? ''));
$invoice = $invoiceNo !== '' || ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0;
return [
'trailer_id' => (int) ($source['trailer_id'] ?? 0),
'employee_id' => (int) ($source['employee_id'] ?? 0),
'start_date' => trim((string) ($source['start_date'] ?? '')),
'end_date' => trim((string) ($source['end_date'] ?? '')),
'start_time' => normalize_time($source['start_time'] ?? ''),
'end_time' => normalize_time($source['end_time'] ?? ''),
'deposit_cents' => parse_money((string) ($source['deposit'] ?? '0')),
'rent_cents' => $rent,
'delivery_cents' => $delivery,
'total_cents' => $rent + $delivery,
'invoice' => $invoice,
'invoice_no' => $invoiceNo,
'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'] ?? '')),
];
}
/** Bestehende Buchung als Eingabedaten (Validierung, Verschieben, Wiederherstellen). */
function booking_to_input(array $booking): array
{
return [
'trailer_id' => (int) $booking['trailer_id'],
'employee_id' => (int) $booking['employee_id'],
'start_date' => (string) $booking['start_date'],
'end_date' => (string) $booking['end_date'],
'start_time' => normalize_time($booking['start_time'] ?? ''),
'end_time' => normalize_time($booking['end_time'] ?? ''),
'deposit_cents' => (int) $booking['deposit_cents'],
'rent_cents' => (int) ($booking['rent_cents'] ?? $booking['total_cents']),
'delivery_cents' => (int) ($booking['delivery_cents'] ?? 0),
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'invoice_no' => (string) ($booking['invoice_no'] ?? ''),
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],
'city' => (string) $booking['city'],
'mobile' => (string) $booking['mobile'],
'email' => (string) $booking['email'],
];
}
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.';
}
}
foreach (['start_time' => 'Mietbeginn', 'end_time' => 'Mietende'] as $field => $label) {
if (!valid_time((string) $data[$field])) {
$errors[$field] = 'Bitte für ' . $label . ' eine gültige Uhrzeit angeben (HH:MM).';
}
}
if (!isset($errors['start_time']) && !isset($errors['end_time'])
&& !isset($errors['start_date']) && !isset($errors['end_date'])
&& $data['start_date'] === $data['end_date']
&& $data['start_time'] !== '' && $data['end_time'] !== ''
&& $data['end_time'] <= $data['start_time']
) {
$errors['end_time'] = 'Am selben Tag muss das Mietende nach dem Mietbeginn liegen.';
}
if ($data['customer_name'] === '') {
$errors['customer_name'] = 'Bitte den Kundennamen angeben.';
} elseif (mb_strlen($data['customer_name']) > 190) {
$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.';
}
}
if ($data['invoice_no'] !== '') {
if (mb_strlen($data['invoice_no']) > 40) {
$errors['invoice_no'] = 'Die Rechnungsnummer ist zu lang (max. 40 Zeichen).';
} elseif (preg_match('/^[A-Za-z0-9._\/\- ]+$/', $data['invoice_no']) !== 1) {
$errors['invoice_no'] = 'Die Rechnungsnummer darf nur Buchstaben, Ziffern, Punkt, Schrägstrich, Bindestrich und Leerzeichen enthalten.';
}
}
$maxAmount = 10000000; // 100.000,00 €
if ($data['rent_cents'] < 0 || $data['delivery_cents'] < 0 || $data['deposit_cents'] < 0) {
$errors['rent'] = 'Beträge dürfen nicht negativ sein.';
} elseif ($data['rent_cents'] > $maxAmount || $data['delivery_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
$errors['rent'] = 'Der Betrag ist unrealistisch hoch.';
} elseif ($data['deposit_cents'] > $data['total_cents']) {
$errors['deposit'] = 'Die Anzahlung darf den Gesamtbetrag nicht übersteigen.';
}
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, start_time, end_time, deposit_cents,
rent_cents, delivery_cents, total_cents, invoice, invoice_no, 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'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $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 = ?,
start_time = ?, end_time = ?, deposit_cents = ?, rent_cents = ?, delivery_cents = ?,
total_cents = ?, invoice = ?, invoice_no = ?, 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'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $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]);
db()->prepare('DELETE FROM reminder_push_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(
booking_to_input($booking),
$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 = booking_to_input($booking);
$data['trailer_id'] = $newTrailerId;
$data['start_date'] = $newStart;
$data['end_date'] = $newEnd;
$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';
}
/** Rechnung inklusive Nummer, z. B. "JA (RE2026054)". */
function booking_invoice_display(array $booking): string
{
$label = booking_invoice_label($booking['invoice']);
$number = trim((string) ($booking['invoice_no'] ?? ''));
return $number === '' ? $label : $label . ' (' . $number . ')';
}
/** 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_display($booking),
'Von: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null),
'Bis: ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null),
'Art: ' . booking_kind_label((string) $booking['kind']),
'Name: ' . $booking['customer_name'],
'Straße: ' . $booking['street'],
'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;
}