Merge origin/main: Remote-Stand übernehmen
Konflikte in app/bootstrap.php, app/pages.php, app/privacy.php, app/util.php, tools/send_reminders.php, views/booking_form.php und views/legal_datenschutz.php zugunsten von origin/main aufgelöst (Enthalten u. a. Einladungen, Buchungsformular-Neustrukturierung und die überarbeiteten Rechtsseiten). Eigene Ergänzungen bleiben erhalten, soweit sie nicht ersetzt wurden: README-Abschnitt "Rechtliches / DSGVO", docs/dsgvo.md, docs/architecture.md, app/config.example.php, install.php und web/offline.html.
This commit is contained in:
commit
dd1fba062e
34 changed files with 1784 additions and 256 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -4,3 +4,5 @@ storage/*
|
|||
!storage/.htaccess
|
||||
*.log
|
||||
.DS_Store
|
||||
.~lock.*
|
||||
tools/dumps/
|
||||
|
|
|
|||
67
README.md
67
README.md
|
|
@ -9,12 +9,17 @@ Die Anforderungen stammen aus
|
|||
|
||||
## Was die App kann
|
||||
|
||||
- **Kalender** mit Tages-, Wochen- und Monatsansicht. Alle Anhänger haben
|
||||
- **Kalender** mit Tages-, Wochen- und Monatsansicht (Monat ist Standard). Alle Anhänger haben
|
||||
eine eigene Zeile und sind immer gleichzeitig sichtbar. Jeder Termin ist ein
|
||||
durchgehender, farbiger Balken in der Farbe des Anhängers.
|
||||
- **Buchungen** mit Anfangs- und Endtermin (ganztägig), Anzahlung,
|
||||
Gesamtbetrag, automatisch berechnetem Restbetrag, Rechnung JA/NEIN,
|
||||
Abholung/Lieferung und vollständigen Kundendaten.
|
||||
- **Buchungen** mit Anfangs- und Endtermin (Datum, Uhrzeit optional), Miete,
|
||||
Lieferkosten, automatisch berechnetem Gesamtbetrag und Restbetrag, Anzahlung,
|
||||
Rechnung JA/NEIN samt Rechnungsnummer, Abholung/Lieferung und vollständigen
|
||||
Kundendaten. Das Formular folgt der Reihenfolge der Excel-Vorlage
|
||||
„Neuanlage"; eine kopierte Spalte wird beim Einfügen auf die Felder verteilt.
|
||||
- **Verfügbarkeit prüfen**: Zeitraum wählen, freie und belegte Anhänger/Truhen
|
||||
sehen und mit einem Klick in die neue Buchung springen (Knopf links neben
|
||||
„Kalender" auf der Übersicht).
|
||||
- **Buchungstext kopieren** mit einem Klick – exakt in der geforderten
|
||||
Reihenfolge und mit erhaltenen Zeilenumbrüchen.
|
||||
- **Doppelbelegungsschutz**: Ein Anhänger kann im gleichen Zeitraum nicht
|
||||
|
|
@ -36,7 +41,9 @@ Die Anforderungen stammen aus
|
|||
- **Mitarbeiter verwalten**: anlegen, umbenennen, sortieren, deaktivieren und löschen. Löschen ist nur ohne Buchungen möglich; sonst bleibt der Mitarbeiter deaktivierbar. Mindestens ein aktiver Mitarbeiter muss erhalten bleiben.
|
||||
- **Benutzerverwaltung** wie bei tippspiel2027: Konten werden ausschließlich
|
||||
vom Administrator angelegt. Anmeldung mit Vorname, Nachname und Passwort;
|
||||
keine Selbstregistrierung.
|
||||
keine Selbstregistrierung. Optional geht statt Startpasswort eine
|
||||
**Einladung per E-Mail**: Der Benutzer vergibt sein Passwort selbst über
|
||||
einen Link, der sieben Tage gültig und nur einmal verwendbar ist.
|
||||
- **Übersicht** mit heutiger Auslastung, freien Anhängern, nächsten Übergaben
|
||||
und Rücknahmen sowie offenen Erinnerungen.
|
||||
|
||||
|
|
@ -130,6 +137,46 @@ Für `--install` werden `DIC_ADMIN_FIRST`, `DIC_ADMIN_LAST` und
|
|||
`DIC_ADMIN_PASSWORD` aus der Umgebung gelesen oder interaktiv abgefragt.
|
||||
`install.php` wird nach erfolgreicher Installation vom Server entfernt.
|
||||
|
||||
`--sync` übernimmt VAPID-Schlüssel, Cron-Token und Mail-Einstellungen aus der
|
||||
bestehenden Live-Konfiguration, solange sie nicht per Umgebung überschrieben
|
||||
werden (`VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`, `CRON_TOKEN`,
|
||||
`DIC_MAIL_ENABLED`, `DIC_MAIL_FROM`). Push-Abos und der Cron-Link bleiben damit
|
||||
bei jedem Sync gültig.
|
||||
|
||||
## Datenbank-Dumps (Backups)
|
||||
|
||||
Für den Regelbetrieb gibt es ein eigenständiges Dump-Script:
|
||||
|
||||
```bash
|
||||
./tools/dump_drink_it_cold.py # Dump nach tools/dumps, 14 Stück behalten
|
||||
./tools/dump_drink_it_cold.py --keep 30 # mehr Historie
|
||||
./tools/dump_drink_it_cold.py --keep 0 # nichts aufräumen
|
||||
./tools/dump_drink_it_cold.py --check # nur Verbindung prüfen
|
||||
./tools/dump_drink_it_cold.py --dir /pfad # anderes Zielverzeichnis
|
||||
```
|
||||
|
||||
- Zugangsdaten: `docs/credentials.txt` (`DB_HOST`, `DB_NAME`, `DB_USER`,
|
||||
`DB_PASSWORD`); überschreibbar per `DB_HOST`, `DB_PORT`, `DB_USER`,
|
||||
`DB_PASS`, `DB_NAME`.
|
||||
- Dateiname: `tools/dumps/drink-it-cold_live_<YYYY-MM-DD_HHMMSS>.sql`
|
||||
- Rechte: Verzeichnis `0700`, Datei `0600` (Dumps enthalten Namen, Adressen,
|
||||
Telefonnummern und E-Mail-Adressen).
|
||||
- Aufräumen: standardmäßig bleiben die letzten 14 Dumps; gelöscht werden nur
|
||||
Dateien nach dem Muster `drink-it-cold_live_*.sql`.
|
||||
- `tools/dumps/` ist gitignored.
|
||||
|
||||
Cron-Beispiel (täglich 03:30):
|
||||
|
||||
```
|
||||
30 3 * * * /Users/torsten/repos/drink-it-cold/tools/dump_drink_it_cold.py >> /var/log/drink-it-cold-dump.log 2>&1
|
||||
```
|
||||
|
||||
Zurückspielen (Vorsicht: der Dump enthält `DROP TABLE`/`CREATE TABLE`):
|
||||
|
||||
```bash
|
||||
mysql -h <host> -u <user> -p <datenbank> < tools/dumps/drink-it-cold_live_<...>.sql
|
||||
```
|
||||
|
||||
## Erinnerungen: Push, E-Mail und Cron
|
||||
|
||||
Die Erinnerungen sind immer in der App sichtbar. Zusätzlich gibt es zwei
|
||||
|
|
@ -145,7 +192,9 @@ Versandkanäle:
|
|||
zugeordnet.
|
||||
- **E-Mail (optional):** Ein täglicher Digest geht an Mitarbeiter, deren
|
||||
Benutzerkonto eine E-Mail-Adresse hat. Dafür `DIC_MAIL_ENABLED=true` beim
|
||||
Deployment setzen (Standard: aus).
|
||||
Deployment setzen (Standard: aus). Dieselbe Einstellung steuert den Versand
|
||||
von **Einladungen** neuer Benutzer; bei ausgeschaltetem Versand zeigt das
|
||||
Benutzerformular den Einladungslink einmalig zum Weitergeben an.
|
||||
|
||||
Der Token steht in `docs/credentials.txt` als `DIC_CRON_TOKEN`. **Externer
|
||||
Cron-Endpoint** (token-geschützt, ohne Login, für cron-job.org o. ä.):
|
||||
|
|
@ -188,6 +237,9 @@ Tabellen an. Auf einer bestehenden Installation einmalig ausführen:
|
|||
php tools/migrate.php
|
||||
```
|
||||
|
||||
Neuere Migrationen – etwa `005_user_invites.sql` für die Einladungen – laufen
|
||||
mit demselben Befehl; angewendet werden nur noch nicht eingetragene Dateien.
|
||||
|
||||
Jede Erinnerung wird pro Kanal genau einmal versendet.
|
||||
|
||||
## Sicherheit
|
||||
|
|
@ -196,6 +248,9 @@ Jede Erinnerung wird pro Kanal genau einmal versendet.
|
|||
`SameSite=Lax`, `Secure` unter HTTPS.
|
||||
- CSRF-Schutz für alle Formulare und die Move-API.
|
||||
- Login-Ratenbegrenzung pro IP und Name, generische Fehlermeldungen.
|
||||
- Einladungslinks: 256-Bit-Token, nur als SHA-256-Hash gespeichert, sieben
|
||||
Tage gültig, einmal verwendbar; Einlösen setzt `auth_epoch` hoch und beendet
|
||||
damit alle bestehenden Sitzungen des Kontos.
|
||||
- „Angemeldet bleiben“ über rotierende Tokens; Passwortwechsel und
|
||||
Deaktivierung machen bestehende Sitzungen ungültig.
|
||||
- CSP ohne Inline-JavaScript, `X-Frame-Options: DENY`, `noindex`.
|
||||
|
|
|
|||
|
|
@ -22,6 +22,10 @@ function admin_handle(string $path, array $user): void
|
|||
admin_user_form((int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)/invite$#', $path, $m) === 1) {
|
||||
admin_user_invite((int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)/delete$#', $path, $m) === 1) {
|
||||
admin_user_delete((int) $m[1], $user);
|
||||
return;
|
||||
|
|
@ -48,11 +52,21 @@ function admin_users_list(): void
|
|||
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();
|
||||
|
||||
// Offene Einladungen, damit der Admin sieht, wer noch keinen Zugang hat.
|
||||
$stmt = db()->prepare('SELECT user_id, expires_at FROM user_invites WHERE used_at IS NULL AND expires_at >= ?');
|
||||
$stmt->execute([utc_now()]);
|
||||
$openInvites = [];
|
||||
foreach ($stmt->fetchAll() as $row) {
|
||||
$openInvites[(int) $row['user_id']] = (string) $row['expires_at'];
|
||||
}
|
||||
|
||||
render_page('admin_users', [
|
||||
'users' => $users,
|
||||
'pushCounts' => push_counts_by_user(),
|
||||
'pushLastUpdate' => push_last_update_by_user(),
|
||||
'pushConfigured' => push_is_configured(),
|
||||
'openInvites' => $openInvites,
|
||||
], 'Benutzer');
|
||||
}
|
||||
|
||||
|
|
@ -95,6 +109,8 @@ function admin_user_form(?int $id): void
|
|||
'must_change_password' => post_string('must_change_password') === '1' ? 1 : 0,
|
||||
];
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
// Einladung: Passwort setzt der Benutzer selbst über einen Link.
|
||||
$sendInvite = $id === null && post_string('send_invite') === '1';
|
||||
|
||||
if ($values['first_name'] === '' || mb_strlen($values['first_name']) > 80) {
|
||||
$errors['first_name'] = 'Bitte einen Vornamen angeben (max. 80 Zeichen).';
|
||||
|
|
@ -129,7 +145,14 @@ function admin_user_form(?int $id): void
|
|||
}
|
||||
}
|
||||
|
||||
if ($id === null && mb_strlen($password) < 8) {
|
||||
if ($sendInvite && $values['email'] === '') {
|
||||
$errors['email'] = 'Für die Einladung wird eine E-Mail-Adresse benötigt – oder das Startpasswort selbst vergeben.';
|
||||
}
|
||||
if ($sendInvite && $values['status'] !== 'active') {
|
||||
$errors['status'] = 'Einladungen sind nur für aktive Konten möglich.';
|
||||
}
|
||||
|
||||
if ($id === null && !$sendInvite && mb_strlen($password) < 8) {
|
||||
$errors['password'] = 'Das Startpasswort muss mindestens 8 Zeichen haben.';
|
||||
}
|
||||
if ($id !== null && $password !== '' && mb_strlen($password) < 8) {
|
||||
|
|
@ -163,13 +186,24 @@ function admin_user_form(?int $id): void
|
|||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$values['first_name'], $values['last_name'], $email, hash_password($password),
|
||||
$values['first_name'], $values['last_name'], $email,
|
||||
hash_password($sendInvite ? bin2hex(random_bytes(24)) : $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.');
|
||||
|
||||
$message = 'Benutzer ' . $values['first_name'] . ' ' . $values['last_name'] . ' wurde angelegt.';
|
||||
if ($sendInvite) {
|
||||
// Link erzeugen (und mailen, wenn der Versand aktiv ist).
|
||||
$inviteResult = invite_provision($newId, (int) auth_user()['id']);
|
||||
invite_notice_set($newId, $inviteResult);
|
||||
$message .= $inviteResult['sent']
|
||||
? ' Die Einladung ist an ' . $email . ' unterwegs.'
|
||||
: ' Die Einladung ist erzeugt – der Link steht im Formular.';
|
||||
}
|
||||
flash('success', $message);
|
||||
redirect('/admin/users/' . $newId);
|
||||
}
|
||||
|
||||
|
|
@ -216,9 +250,41 @@ function admin_user_form(?int $id): void
|
|||
'employees' => $employees,
|
||||
'pushCount' => $editing ? push_subscription_count((int) $editing['id']) : 0,
|
||||
'pushAvailable' => push_is_configured(),
|
||||
'mailEnabled' => mail_is_enabled(),
|
||||
'sendInvite' => $id === null && (!is_post() || post_string('send_invite') === '1'),
|
||||
'inviteNotice' => invite_notice_take($id),
|
||||
'openInvite' => $editing ? invite_active_for_user((int) $editing['id']) : null,
|
||||
], $editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen');
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt einen neuen Einladungslink und mailt ihn. Ein bisheriges Passwort
|
||||
* wird dabei ungültig, angemeldete Geräte werden abgemeldet.
|
||||
*/
|
||||
function admin_user_invite(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, 'Für das eigene Konto lässt sich keine Einladung versenden. Bitte das Passwort unter „Mein Konto" ändern.');
|
||||
}
|
||||
if ($target['status'] !== 'active') {
|
||||
flash('error', 'Für ein deaktiviertes Konto kann keine Einladung versendet werden. Bitte das Konto zuerst aktivieren.');
|
||||
redirect('/admin/users/' . $id);
|
||||
}
|
||||
|
||||
$result = invite_provision($id, (int) $actor['id']);
|
||||
invite_notice_set($id, $result);
|
||||
$email = trim((string) ($target['email'] ?? ''));
|
||||
flash('success', $result['sent']
|
||||
? 'Einladung an ' . $email . ' gesendet. Das bisherige Passwort ist jetzt ungültig.'
|
||||
: 'Einladung erzeugt. Das bisherige Passwort ist jetzt ungültig.');
|
||||
redirect('/admin/users/' . $id);
|
||||
}
|
||||
|
||||
function admin_user_delete(int $id, array $actor): void
|
||||
{
|
||||
require_post();
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ require DIC_APP . '/auth.php';
|
|||
require DIC_APP . '/data.php';
|
||||
require DIC_APP . '/push.php';
|
||||
require DIC_APP . '/mail.php';
|
||||
require DIC_APP . '/invite.php';
|
||||
require DIC_APP . '/privacy.php';
|
||||
require DIC_APP . '/pages.php';
|
||||
require DIC_APP . '/admin.php';
|
||||
|
|
|
|||
|
|
@ -29,7 +29,8 @@ return [
|
|||
'login_window_seconds' => 900,
|
||||
'login_max_per_user' => 5,
|
||||
'login_max_per_ip' => 15,
|
||||
// Optionaler täglicher E-Mail-Digest (tools/send_reminders.php).
|
||||
// Optionaler E-Mail-Versand: täglicher Erinnerungs-Digest
|
||||
// (tools/send_reminders.php) und Einladungen für neue Benutzer.
|
||||
'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.
|
||||
|
|
|
|||
155
app/data.php
155
app/data.php
|
|
@ -20,6 +20,12 @@ function trailers_map(bool $activeOnly = false): array
|
|||
return $out;
|
||||
}
|
||||
|
||||
/** Truhen erkennt die App an der Bezeichnung ("Truhe", "Truhe 1", "Truhe 2 (verschrottet)"). */
|
||||
function trailer_is_chest(array $trailer): bool
|
||||
{
|
||||
return mb_stripos(trim((string) $trailer['label']), 'truhe') === 0;
|
||||
}
|
||||
|
||||
function trailer_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM trailers WHERE id = ?');
|
||||
|
|
@ -118,14 +124,34 @@ function booking_conflicts(int $trailerId, string $start, string $end, int $excl
|
|||
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')),
|
||||
'total_cents' => parse_money((string) ($source['total'] ?? '0')),
|
||||
'invoice' => ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 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'] ?? '')),
|
||||
|
|
@ -135,6 +161,31 @@ function booking_input(array $source): array
|
|||
];
|
||||
}
|
||||
|
||||
/** 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 = [];
|
||||
|
|
@ -163,6 +214,20 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
|
|||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
|
@ -182,11 +247,19 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
|
|||
}
|
||||
}
|
||||
|
||||
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['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.';
|
||||
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.';
|
||||
}
|
||||
|
|
@ -234,13 +307,16 @@ function booking_create(array $data, int $userId): int
|
|||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO bookings
|
||||
(trailer_id, employee_id, start_date, end_date, deposit_cents, total_cents, invoice, kind,
|
||||
(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", ?, ?, ?, ?)'
|
||||
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'],
|
||||
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,
|
||||
]);
|
||||
|
|
@ -270,12 +346,15 @@ function booking_update(int $id, array $data, int $userId): void
|
|||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE bookings SET trailer_id = ?, employee_id = ?, start_date = ?, end_date = ?,
|
||||
deposit_cents = ?, total_cents = ?, invoice = ?, kind = ?, customer_name = ?, street = ?,
|
||||
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'],
|
||||
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
|
||||
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,
|
||||
]);
|
||||
|
|
@ -320,21 +399,12 @@ function booking_restore(int $id, int $userId): array
|
|||
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']);
|
||||
$errors = booking_validate(
|
||||
booking_to_input($booking),
|
||||
$id,
|
||||
(int) $booking['trailer_id'],
|
||||
(int) $booking['employee_id']
|
||||
);
|
||||
if ($errors) {
|
||||
return $errors;
|
||||
}
|
||||
|
|
@ -368,21 +438,10 @@ function booking_move(int $id, string $newStart, int $newTrailerId, int $userId)
|
|||
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'],
|
||||
];
|
||||
$data = booking_to_input($booking);
|
||||
$data['trailer_id'] = $newTrailerId;
|
||||
$data['start_date'] = $newStart;
|
||||
$data['end_date'] = $newEnd;
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
|
|
@ -432,6 +491,14 @@ 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
|
||||
{
|
||||
|
|
@ -439,9 +506,9 @@ function booking_copy_text(array $booking): string
|
|||
'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']),
|
||||
'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'],
|
||||
|
|
|
|||
213
app/invite.php
Normal file
213
app/invite.php
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Einladungen für neue Benutzerkonten.
|
||||
*
|
||||
* Der Admin legt das Konto an und erzeugt dabei einen einmaligen Link. Über
|
||||
* diesen Link vergibt der Benutzer sein Passwort selbst – es muss also kein
|
||||
* Startpasswort weitergegeben werden. Gespeichert wird nur der SHA-256-Hash
|
||||
* des Tokens; der Link ist sieben Tage gültig.
|
||||
*
|
||||
* Der Versand per E-Mail ist optional (app.mail_enabled). Ist er aus oder
|
||||
* fehlt die Adresse, zeigt die App den Link im Benutzerformular an, damit der
|
||||
* Admin ihn über einen anderen Weg weitergeben kann.
|
||||
*/
|
||||
|
||||
const DIC_INVITE_SECONDS = 7 * 86400;
|
||||
|
||||
function invite_url(string $token): string
|
||||
{
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
return $base . url('/invite/' . $token);
|
||||
}
|
||||
|
||||
/** Legt einen neuen Einladungslink an; ein älterer Link wird ungültig. */
|
||||
function invite_create(int $userId, ?int $createdBy): array
|
||||
{
|
||||
$token = bin2hex(random_bytes(32));
|
||||
$expiresAt = utc_after(DIC_INVITE_SECONDS);
|
||||
|
||||
db()->prepare('DELETE FROM user_invites WHERE user_id = ?')->execute([$userId]);
|
||||
db()->prepare(
|
||||
'INSERT INTO user_invites (user_id, token_hash, created_by, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)'
|
||||
)->execute([$userId, hash('sha256', $token), $createdBy, utc_now(), $expiresAt]);
|
||||
|
||||
return ['token' => $token, 'url' => invite_url($token), 'expires_at' => $expiresAt];
|
||||
}
|
||||
|
||||
/** Sucht eine offene, noch gültige Einladung zum Token. */
|
||||
function invite_find(string $token): ?array
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT i.*, u.first_name, u.last_name, u.email, u.status
|
||||
FROM user_invites i JOIN users u ON u.id = i.user_id
|
||||
WHERE i.token_hash = ? AND i.used_at IS NULL AND i.expires_at >= ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([hash('sha256', $token), utc_now()]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['user_id'] = (int) $row['user_id'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function invite_active_for_user(int $userId): ?array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT * FROM user_invites WHERE user_id = ? AND used_at IS NULL AND expires_at >= ?
|
||||
ORDER BY id DESC LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$userId, utc_now()]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt Passwort und Session-Sperre für ein Konto zurück, erzeugt einen neuen
|
||||
* Einladungslink und verschickt ihn, wenn E-Mail-Versand aktiv ist.
|
||||
*
|
||||
* @return array{url: string, sent: bool, error: string, expires_at: string}
|
||||
*/
|
||||
function invite_provision(int $userId, ?int $createdBy): array
|
||||
{
|
||||
$user = auth_user_by_id($userId);
|
||||
if (!$user) {
|
||||
throw new RuntimeException('Benutzer nicht gefunden.');
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
// Zufälliges Ersatzpasswort: das bisherige Passwort ist sofort ungültig,
|
||||
// angemeldete Geräte werden abgemeldet.
|
||||
$pdo->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 1,
|
||||
auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?'
|
||||
)->execute([hash_password(bin2hex(random_bytes(24))), utc_now(), utc_now(), $userId]);
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
|
||||
$invite = invite_create($userId, $createdBy);
|
||||
$result = ['url' => $invite['url'], 'sent' => false, 'error' => '', 'expires_at' => $invite['expires_at']];
|
||||
$email = trim((string) ($user['email'] ?? ''));
|
||||
|
||||
if (!mail_is_enabled()) {
|
||||
$result['error'] = 'E-Mail-Versand ist deaktiviert. Bitte den Link selbst weitergeben.';
|
||||
return $result;
|
||||
}
|
||||
if ($email === '') {
|
||||
$result['error'] = 'Für dieses Konto ist keine E-Mail-Adresse hinterlegt. Bitte den Link selbst weitergeben.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
[$subject, $body] = invite_mail_text($user, $invite['url'], $invite['expires_at']);
|
||||
if (!mail_send($email, $subject, $body)) {
|
||||
$result['error'] = 'Versand an ' . $email . ' fehlgeschlagen. Bitte den Link selbst weitergeben.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
$result['sent'] = true;
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return array{0: string, 1: string} Betreff und Text der Einladungs-E-Mail */
|
||||
function invite_mail_text(array $user, string $url, string $expiresAt): array
|
||||
{
|
||||
$firstName = (string) $user['first_name'];
|
||||
$loginUrl = rtrim((string) config('app.public_url', ''), '/') . url('/login');
|
||||
|
||||
$lines = [
|
||||
'Guten Tag ' . $firstName . ',',
|
||||
'',
|
||||
'für Sie wurde ein Zugang zur Terminplanung von Drink it cold angelegt.',
|
||||
'',
|
||||
'Zugang einrichten (Link sieben Tage gültig, einmal nutzbar):',
|
||||
$url,
|
||||
'',
|
||||
'Danach melden Sie sich mit Vorname, Nachname und Ihrem selbst gewählten',
|
||||
'Passwort an: ' . $loginUrl,
|
||||
'',
|
||||
'Der Link verfällt am ' . fmt_datetime($expiresAt) . '. Ist er nicht mehr gültig,',
|
||||
'wenden Sie sich bitte an den Administrator.',
|
||||
'',
|
||||
'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.',
|
||||
];
|
||||
|
||||
return ['Drink it cold – Zugang zur Terminplanung', implode("\n", $lines)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vergibt das Passwort über die Einladung: Passwort speichern, Einladung
|
||||
* verbrauchen, neue Anmeldung mit diesem Konto vorbereiten.
|
||||
*/
|
||||
function invite_accept(array $invite, string $password): array
|
||||
{
|
||||
$userId = (int) $invite['user_id'];
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
// Einmal-Verwendung: nur wer den Eintrag als erster auf „benutzt“ setzt,
|
||||
// darf das Passwort vergeben.
|
||||
$claim = $pdo->prepare('UPDATE user_invites SET used_at = ? WHERE id = ? AND used_at IS NULL');
|
||||
$claim->execute([utc_now(), (int) $invite['id']]);
|
||||
if ($claim->rowCount() === 0) {
|
||||
$pdo->rollBack();
|
||||
throw new RuntimeException('invite_used');
|
||||
}
|
||||
|
||||
$pdo->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, updated_at = ?,
|
||||
must_change_password = 0, auth_epoch = auth_epoch + 1 WHERE id = ?'
|
||||
)->execute([hash_password($password), utc_now(), utc_now(), $userId]);
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
// Weitere offene Einladungen desselben Kontos werden ungültig.
|
||||
$pdo->prepare('DELETE FROM user_invites WHERE user_id = ? AND id <> ?')->execute([$userId, (int) $invite['id']]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
|
||||
$user = auth_user_by_id($userId);
|
||||
if (!$user) {
|
||||
throw new RuntimeException('Benutzer nicht gefunden.');
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- Einladung nach dem Anlegen */
|
||||
|
||||
/** Merkt den Link für genau einen Seitenaufruf im Benutzerformular. */
|
||||
function invite_notice_set(int $userId, array $result): void
|
||||
{
|
||||
$_SESSION['invite_notice'] = [
|
||||
'user_id' => $userId,
|
||||
'url' => (string) $result['url'],
|
||||
'sent' => (bool) $result['sent'],
|
||||
'error' => (string) ($result['error'] ?? ''),
|
||||
'expires_at' => (string) $result['expires_at'],
|
||||
];
|
||||
}
|
||||
|
||||
function invite_notice_take(?int $userId): ?array
|
||||
{
|
||||
$notice = $_SESSION['invite_notice'] ?? null;
|
||||
unset($_SESSION['invite_notice']);
|
||||
if (!is_array($notice) || $userId === null || (int) ($notice['user_id'] ?? 0) !== $userId) {
|
||||
return null;
|
||||
}
|
||||
return $notice;
|
||||
}
|
||||
52
app/mail.php
52
app/mail.php
|
|
@ -2,14 +2,46 @@
|
|||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Optionaler täglicher E-Mail-Digest für fällige Erinnerungen.
|
||||
* E-Mail-Versand: optionaler täglicher Digest für fällige Erinnerungen und
|
||||
* Einladungen für neue Benutzer.
|
||||
*
|
||||
* Die In-App-Erinnerungen sind immer vorhanden. Dieser Versand ist zusätzlich
|
||||
* Die In-App-Erinnerungen sind immer vorhanden. Der Digest 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.
|
||||
*
|
||||
* Eingeschaltet wird der Versand über app.mail_enabled. Ist er aus, bleibt die
|
||||
* App vollständig nutzbar; Einladungslinks zeigt der Admin dann selbst an.
|
||||
*/
|
||||
|
||||
function mail_is_enabled(): bool
|
||||
{
|
||||
return (bool) config('app.mail_enabled', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt eine reine Textnachricht. Absender kommt aus app.mail_from.
|
||||
* Der Aufrufer prüft mail_is_enabled() und die Empfängeradresse.
|
||||
*/
|
||||
function mail_send(string $to, string $subject, string $body): bool
|
||||
{
|
||||
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||
return false;
|
||||
}
|
||||
$headers = [
|
||||
'From: ' . (string) config('app.mail_from', 'Drink it cold <noreply@localhost>'),
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: text/plain; charset=UTF-8',
|
||||
'Content-Transfer-Encoding: 8bit',
|
||||
];
|
||||
return @mail(
|
||||
$to,
|
||||
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
|
||||
$body,
|
||||
implode("\r\n", $headers)
|
||||
);
|
||||
}
|
||||
|
||||
function reminder_mail_recipients(): array
|
||||
{
|
||||
$sql = "SELECT u.employee_id, u.email, u.first_name, u.last_name, e.name AS employee_name
|
||||
|
|
@ -31,7 +63,7 @@ function reminder_mail_recipients(): array
|
|||
*/
|
||||
function reminder_send_due(int $lookbackDays = 7): array
|
||||
{
|
||||
$result = ['enabled' => (bool) config('app.mail_enabled', false), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
|
||||
$result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
|
||||
if (!$result['enabled']) {
|
||||
return $result;
|
||||
}
|
||||
|
|
@ -61,7 +93,6 @@ function reminder_send_due(int $lookbackDays = 7): array
|
|||
$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) {
|
||||
|
|
@ -87,18 +118,7 @@ function reminder_send_due(int $lookbackDays = 7): array
|
|||
$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)
|
||||
);
|
||||
$ok = mail_send((string) $recipient['email'], $subject, $body);
|
||||
if (!$ok) {
|
||||
$result['errors'][] = 'Versand an ' . $recipient['email'] . ' fehlgeschlagen.';
|
||||
continue;
|
||||
|
|
|
|||
160
app/pages.php
160
app/pages.php
|
|
@ -54,6 +54,10 @@ function page_handle(string $method, string $path): void
|
|||
page_login($method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/invite/([a-f0-9]{64})$#', $path, $m) === 1) {
|
||||
page_invite($method, $m[1]);
|
||||
return;
|
||||
}
|
||||
if ($path === '/impressum' || $path === '/datenschutz') {
|
||||
legal_page(substr($path, 1));
|
||||
return;
|
||||
|
|
@ -83,6 +87,10 @@ function page_handle(string $method, string $path): void
|
|||
page_calendar($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/availability') {
|
||||
page_availability($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/bookings/new') {
|
||||
page_booking_new($user, $method);
|
||||
return;
|
||||
|
|
@ -186,8 +194,9 @@ function cron_reminders(): void
|
|||
$mail = reminder_send_due();
|
||||
echo 'Drink it cold – Erinnerungslauf ' . fmt_datetime(utc_now()) . "\n";
|
||||
echo sprintf(
|
||||
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
|
||||
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['reminder_mail_log'],
|
||||
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
|
||||
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
|
||||
$cleanup['reminder_mail_log'],
|
||||
$cleanup['reminder_push_log'], $cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
|
||||
);
|
||||
if (!push_is_configured()) {
|
||||
|
|
@ -264,6 +273,67 @@ function page_login(string $method): void
|
|||
], 'Anmelden');
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Einladung */
|
||||
|
||||
/**
|
||||
* Einmaliger Link aus der Einladungs-E-Mail: Der Benutzer vergibt hier sein
|
||||
* Passwort selbst. Danach wird er bewusst zur Anmeldung geschickt, damit er
|
||||
* das neue Passwort direkt ausprobiert.
|
||||
*/
|
||||
function page_invite(string $method, string $token): void
|
||||
{
|
||||
$invite = invite_find($token);
|
||||
$state = 'form';
|
||||
$error = '';
|
||||
|
||||
if ($invite === null) {
|
||||
$state = 'invalid';
|
||||
http_response_code(410);
|
||||
} elseif ($invite['status'] !== 'active') {
|
||||
$state = 'invalid';
|
||||
http_response_code(403);
|
||||
} elseif ($method === 'POST') {
|
||||
require_post();
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
$repeat = (string) ($_POST['repeat_password'] ?? '');
|
||||
if (mb_strlen($password) < 8) {
|
||||
$error = 'Das Passwort muss mindestens 8 Zeichen haben.';
|
||||
} elseif ($password !== $repeat) {
|
||||
$error = 'Die beiden Passwörter stimmen nicht überein.';
|
||||
} else {
|
||||
try {
|
||||
invite_accept($invite, $password);
|
||||
// Eine bestehende Sitzung dieses Kontos ist durch den neuen
|
||||
// auth_epoch ohnehin ungültig; hier wird sie auch formal beendet.
|
||||
$current = auth_user();
|
||||
if ($current !== null && (int) $current['id'] === (int) $invite['user_id']) {
|
||||
auth_clear_session();
|
||||
}
|
||||
flash('success', 'Ihr Zugang ist eingerichtet. Bitte jetzt mit Vorname, Nachname und dem neuen Passwort anmelden.');
|
||||
redirect('/login');
|
||||
} catch (RuntimeException $e) {
|
||||
if ($e->getMessage() !== 'invite_used') {
|
||||
throw $e;
|
||||
}
|
||||
// Zwei Geräte haben den Link gleichzeitig geöffnet.
|
||||
$state = 'invalid';
|
||||
http_response_code(410);
|
||||
}
|
||||
}
|
||||
if ($state === 'form') {
|
||||
http_response_code(422);
|
||||
}
|
||||
}
|
||||
|
||||
render_standalone('invite', [
|
||||
'state' => $state,
|
||||
'error' => $error,
|
||||
'firstName' => $invite !== null ? (string) $invite['first_name'] : '',
|
||||
'lastName' => $invite !== null ? (string) $invite['last_name'] : '',
|
||||
'email' => $invite !== null ? (string) ($invite['email'] ?? '') : '',
|
||||
], 'Zugang einrichten');
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Übersicht */
|
||||
|
||||
function page_dashboard(array $user): void
|
||||
|
|
@ -327,9 +397,9 @@ function calendar_url(string $date, string $view, int $employeeId, bool $showCan
|
|||
|
||||
function page_calendar(array $user): void
|
||||
{
|
||||
$view = query_string('view', 'week');
|
||||
$view = query_string('view', 'month');
|
||||
if (!in_array($view, ['day', 'week', 'month'], true)) {
|
||||
$view = 'week';
|
||||
$view = 'month';
|
||||
}
|
||||
$date = query_string('date');
|
||||
if (!valid_date($date)) {
|
||||
|
|
@ -374,8 +444,8 @@ function page_calendar(array $user): void
|
|||
$cursor = add_days($cursor, 1);
|
||||
}
|
||||
|
||||
$barBase = ['day' => 76, 'week' => 48, 'month' => 28][$view];
|
||||
$rowMin = ['day' => 104, 'week' => 64, 'month' => 40][$view];
|
||||
$barBase = ['day' => 76, 'week' => 48, 'month' => 34][$view];
|
||||
$rowMin = ['day' => 104, 'week' => 64, 'month' => 44][$view];
|
||||
|
||||
$rows = [];
|
||||
foreach ($trailers as $trailer) {
|
||||
|
|
@ -438,6 +508,66 @@ function page_calendar(array $user): void
|
|||
], 'Kalender');
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- Verfügbarkeit */
|
||||
|
||||
function page_availability(array $user): void
|
||||
{
|
||||
$from = query_string('from');
|
||||
$to = query_string('to');
|
||||
$checked = $from !== '' || $to !== '';
|
||||
$errors = [];
|
||||
|
||||
if (!$checked) {
|
||||
$from = today_iso();
|
||||
$to = add_days($from, 3);
|
||||
} else {
|
||||
if (!valid_date($from)) {
|
||||
$errors['from'] = 'Bitte ein gültiges Startdatum angeben.';
|
||||
}
|
||||
if ($to === '') {
|
||||
$to = $from;
|
||||
}
|
||||
if (!valid_date($to)) {
|
||||
$errors['to'] = 'Bitte ein gültiges Enddatum angeben.';
|
||||
}
|
||||
if (!$errors) {
|
||||
if ($to < $from) {
|
||||
$errors['to'] = 'Das Ende darf nicht vor dem Beginn liegen.';
|
||||
} elseif (days_between($from, $to) > 365) {
|
||||
$errors['to'] = 'Der Zeitraum darf höchstens 365 Tage betragen.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$groups = ['trailer' => [], 'chest' => []];
|
||||
$totals = ['trailer' => 0, 'chest' => 0];
|
||||
$freeCount = 0;
|
||||
if ($checked && !$errors) {
|
||||
foreach (trailers_all() as $trailer) {
|
||||
$key = trailer_is_chest($trailer) ? 'chest' : 'trailer';
|
||||
$totals[$key]++;
|
||||
// Nur tatsächlich freie Fahrzeuge ausweisen; belegte entfallen.
|
||||
if (booking_conflicts((int) $trailer['id'], $from, $to)) {
|
||||
continue;
|
||||
}
|
||||
$freeCount++;
|
||||
$groups[$key][] = ['trailer' => $trailer];
|
||||
}
|
||||
}
|
||||
|
||||
render_page('availability', [
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'checked' => $checked,
|
||||
'errors' => $errors,
|
||||
'groups' => $groups,
|
||||
'totals' => $totals,
|
||||
'freeCount' => $freeCount,
|
||||
'total' => $totals['trailer'] + $totals['chest'],
|
||||
'user' => $user,
|
||||
], 'Verfügbarkeit');
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Buchungen */
|
||||
|
||||
function booking_form_context(array $user, ?array $booking = null, array $values = [], array $errors = []): array
|
||||
|
|
@ -473,9 +603,13 @@ function form_values_from_input(array $data): array
|
|||
'employee_id' => (int) $data['employee_id'],
|
||||
'start_date' => (string) $data['start_date'],
|
||||
'end_date' => (string) $data['end_date'],
|
||||
'start_time' => (string) ($data['start_time'] ?? ''),
|
||||
'end_time' => (string) ($data['end_time'] ?? ''),
|
||||
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
|
||||
'total' => number_format($data['total_cents'] / 100, 2, ',', ''),
|
||||
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
|
||||
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
|
||||
'invoice' => (int) $data['invoice'],
|
||||
'invoice_no' => (string) ($data['invoice_no'] ?? ''),
|
||||
'kind' => (string) $data['kind'],
|
||||
'customer_name' => (string) $data['customer_name'],
|
||||
'street' => (string) $data['street'],
|
||||
|
|
@ -515,9 +649,13 @@ function page_booking_new(array $user, string $method): void
|
|||
'employee_id' => $employeeId,
|
||||
'start_date' => $start,
|
||||
'end_date' => $end,
|
||||
'start_time' => '',
|
||||
'end_time' => '',
|
||||
'deposit' => '',
|
||||
'total' => '',
|
||||
'rent' => '',
|
||||
'delivery' => '',
|
||||
'invoice' => 0,
|
||||
'invoice_no' => '',
|
||||
'kind' => 'pickup',
|
||||
'customer_name' => '',
|
||||
'street' => '',
|
||||
|
|
@ -559,9 +697,13 @@ function page_booking_edit(array $user, int $id, string $method): void
|
|||
'employee_id' => (int) $booking['employee_id'],
|
||||
'start_date' => (string) $booking['start_date'],
|
||||
'end_date' => (string) $booking['end_date'],
|
||||
'start_time' => (string) ($booking['start_time'] ?? ''),
|
||||
'end_time' => (string) ($booking['end_time'] ?? ''),
|
||||
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
|
||||
'total' => number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
|
||||
'rent' => number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
|
||||
'delivery' => number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
|
||||
'invoice' => (int) $booking['invoice'],
|
||||
'invoice_no' => (string) ($booking['invoice_no'] ?? ''),
|
||||
'kind' => (string) $booking['kind'],
|
||||
'customer_name' => (string) $booking['customer_name'],
|
||||
'street' => (string) $booking['street'],
|
||||
|
|
|
|||
|
|
@ -6,13 +6,15 @@ declare(strict_types=1);
|
|||
*
|
||||
* Wird beim täglichen Erinnerungslauf (Cron) ausgeführt und hält die
|
||||
* Speicherdauer kurz, die in der Datenschutzerklärung zugesagt wird:
|
||||
* Login-Fehlversuche, abgelaufene Remember-Tokens und alte Versandprotokolle.
|
||||
* Login-Fehlversuche, abgelaufene Remember-Tokens, verbrauchte Einladungen
|
||||
* und alte Versandprotokolle.
|
||||
*/
|
||||
function privacy_cleanup(): array
|
||||
{
|
||||
$result = [
|
||||
'login_attempts' => 0,
|
||||
'auth_tokens' => 0,
|
||||
'user_invites' => 0,
|
||||
'reminder_mail_log' => 0,
|
||||
'reminder_push_log' => 0,
|
||||
'log_rotated' => false,
|
||||
|
|
@ -27,6 +29,11 @@ function privacy_cleanup(): array
|
|||
'DELETE FROM auth_tokens WHERE expires_at < ?',
|
||||
[utc_now()]
|
||||
);
|
||||
// Einladungen nur bis zum Verfall bzw. nach dem Einlösen aufbewahren.
|
||||
$result['user_invites'] = privacy_delete(
|
||||
'DELETE FROM user_invites WHERE expires_at < ? OR used_at IS NOT NULL',
|
||||
[utc_now()]
|
||||
);
|
||||
$result['reminder_mail_log'] = privacy_delete(
|
||||
'DELETE FROM reminder_mail_log WHERE sent_at < ?',
|
||||
[utc_after(-365 * 86400)]
|
||||
|
|
|
|||
51
app/util.php
51
app/util.php
|
|
@ -89,7 +89,7 @@ function url(string $path = '/'): string
|
|||
}
|
||||
|
||||
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
|
||||
const DIC_ASSET_VERSION = '9';
|
||||
const DIC_ASSET_VERSION = '16';
|
||||
|
||||
function asset(string $path): string
|
||||
{
|
||||
|
|
@ -260,6 +260,55 @@ function date_obj(string $iso): DateTimeImmutable
|
|||
return new DateTimeImmutable($iso . ' 12:00:00', new DateTimeZone('Europe/Berlin'));
|
||||
}
|
||||
|
||||
/** Uhrzeit als "HH:MM" normalisieren; leer bleibt leer (optional). */
|
||||
function normalize_time(mixed $value): string
|
||||
{
|
||||
$text = trim((string) $value);
|
||||
if ($text === '') {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^(\d{1,2}):(\d{2})(?::\d{2})?$/', $text, $match) === 1) {
|
||||
return sprintf('%02d:%02d', (int) $match[1], (int) $match[2]);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
/** Leere Uhrzeit wird in der Datenbank als NULL gespeichert. */
|
||||
function null_if_empty(string $value): ?string
|
||||
{
|
||||
return $value === '' ? null : $value;
|
||||
}
|
||||
|
||||
/** Leere Uhrzeit ist erlaubt – sie ist ein optionales Zusatzfeld. */
|
||||
function valid_time(?string $time): bool
|
||||
{
|
||||
if ($time === null || $time === '') {
|
||||
return true;
|
||||
}
|
||||
return preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) === 1;
|
||||
}
|
||||
|
||||
function fmt_time(?string $time): string
|
||||
{
|
||||
$value = normalize_time($time);
|
||||
return $value !== '' && valid_time($value) ? $value : '';
|
||||
}
|
||||
|
||||
/** Datum mit optionaler Uhrzeit, z. B. "30.11.2026 14:00". */
|
||||
function fmt_date_with_time(string $iso, ?string $time): string
|
||||
{
|
||||
$clock = fmt_time($time);
|
||||
return $clock === '' ? fmt_date($iso) : fmt_date($iso) . ' ' . $clock;
|
||||
}
|
||||
|
||||
/** Kurzform für Listen/Kopiertext: "30.11.26 14:00". */
|
||||
function fmt_date_short_with_time(string $iso, ?string $time): string
|
||||
{
|
||||
$clock = fmt_time($time);
|
||||
return $clock === '' ? fmt_date_short($iso) : fmt_date_short($iso) . ' ' . $clock;
|
||||
}
|
||||
|
||||
|
||||
function add_days(string $iso, int $days): string
|
||||
{
|
||||
return date_obj($iso)->modify(($days >= 0 ? '+' : '') . $days . ' days')->format('Y-m-d');
|
||||
|
|
|
|||
BIN
docs/App Buchhaltung.xlsx
Normal file
BIN
docs/App Buchhaltung.xlsx
Normal file
Binary file not shown.
BIN
docs/App DC.xlsx
Normal file
BIN
docs/App DC.xlsx
Normal file
Binary file not shown.
|
|
@ -31,7 +31,7 @@ Browser
|
|||
| `trailers` | Anhänger mit Bezeichnung, Farbname, Hex-Farbe, Sortierung und Aktiv-Status (Start-Anhänger aus der Anforderung vorinstalliert, weitere im Admin anlegbar) |
|
||||
| `employees` | Mitarbeiter (M. Krücken, N. Jorns, M. Schmitz), aktiv/inaktiv |
|
||||
| `users` | Login-Konten (Vorname, Nachname, Passwort-Hash, Rolle, optional E-Mail, optional Mitarbeiter-Link) |
|
||||
| `bookings` | Buchung inkl. Zeitraum, Beträge, Rechnungsflag, Art, Kundendaten, Status |
|
||||
| `bookings` | Buchung inkl. Zeitraum (Datum + optionale Uhrzeit), Miete/Lieferkosten mit Gesamtbetrag, Anzahlung, Rechnungsflag und Rechnungsnummer, Art, Kundendaten, Status |
|
||||
| `reminder_done` | Abgehakte Erinnerung, Schlüssel `(booking_id, kind, due_date)` |
|
||||
| `reminder_mail_log` | Versandprotokoll, verhindert doppelte E-Mails |
|
||||
| `push_subscriptions` | Web-Push-Abos pro Gerät (Endpoint-Hash, p256dh, auth, letzter Erfolg/Fehler) |
|
||||
|
|
@ -130,6 +130,14 @@ sind die primäre Anzeige und funktionieren ohne Mailversand.
|
|||
werden; das eigene Konto kann nicht deaktiviert werden.
|
||||
- Startpasswort und Passwort-Reset durch den Admin können
|
||||
„Passwort bei nächster Anmeldung ändern“ erzwingen.
|
||||
- **Einladung statt Startpasswort:** Beim Anlegen (oder später über
|
||||
„Einladung erzeugen“) entsteht ein einmaliger Link `/invite/<token>`,
|
||||
sieben Tage gültig. Gespeichert wird nur der SHA-256-Hash in
|
||||
`user_invites`. Wer den Link einlöst, setzt sein Passwort selbst; das
|
||||
bisherige Passwort wird ungültig und alle Sitzungen werden beendet.
|
||||
Der Versand nutzt `mail_send()` (PHP `mail()`, `app.mail_enabled`).
|
||||
Ist der Versand aus, zeigt das Formular den Link einmalig an.
|
||||
Abgelaufene und benutzte Einladungen räumt der Cron-Lauf weg.
|
||||
- Passwortwechsel erhöht `auth_epoch` und löscht Remember-Tokens; andere
|
||||
Geräte müssen sich neu anmelden.
|
||||
|
||||
|
|
@ -141,11 +149,12 @@ sind die primäre Anzeige und funktionieren ohne Mailversand.
|
|||
| Tag/Woche/Monat, Google-ähnlich | `?view=day|week|month`, Navigation, Heute, Datumssprung |
|
||||
| Durchgehende farbige Balken | absolute Balken pro Zeile, Farbe aus `trailers.color_hex` |
|
||||
| Keine ausgeblendeten Termine | alle Buchungen im Zeitraum werden gerendert; Lanes statt „weitere Termine“ |
|
||||
| 3. Ganztägige Mietzeiträume | `DATE` ohne Uhrzeit, inklusive Endtag |
|
||||
| 3. Mietzeiträume | `DATE`-Zeitraum inklusive Endtag; Uhrzeiten (`start_time`, `end_time`) optional, ohne Angabe ganztägig |
|
||||
| Keine Doppelbelegung, Wechseltag erlaubt | strikte Intervallprüfung + Zeilensperre, Wechseltag bewusst erlaubt |
|
||||
| 4. Felder in fester Reihenfolge | Formular und Kopiervorlage in exakt der vorgegebenen Reihenfolge |
|
||||
| 4. Felder in fester Reihenfolge | Formular untereinander in der Reihenfolge der Vorlage „Neuanlage"; Kopiervorlage unverändert. Eine aus Excel kopierte Spalte wird beim Einfügen der Reihe nach auf die Felder verteilt (Gesamt wird übersprungen, weil berechnet) |
|
||||
| Restbetrag automatisch | `total_cents − deposit_cents`, live im Formular und serverseitig berechnet |
|
||||
| Rechnung JA/NEIN, Art Abholer/Lieferung | Radio-Auswahl, Labels wie gefordert |
|
||||
| Miete + Lieferkosten | `rent_cents` + `delivery_cents` = `total_cents`, live im Formular mitgerechnet |
|
||||
| Rechnung JA/NEIN, Art Abholer/Lieferung | Radio-Auswahl, Labels wie gefordert; Rechnungsnummer optional, setzt JA automatisch |
|
||||
| Komplett kopieren | Button nutzt Clipboard-API, Fallback `execCommand`; Text enthält Zeilenumbrüche |
|
||||
| 5. Mitarbeiterzuordnung | `bookings.employee_id`, Auswahl im Formular, änderbar |
|
||||
| 6. Drei automatische Erinnerungen | serverseitig aus den Daten berechnet, an den Mitarbeiter gebunden |
|
||||
|
|
@ -238,5 +247,6 @@ sind die primäre Anzeige und funktionieren ohne Mailversand.
|
|||
- Backups: tägliches `mysqldump` der Datenbank empfohlen; Uploads gibt es keine.
|
||||
- Logs: `storage/logs/php.log` (außerhalb des öffentlichen Zugriffs).
|
||||
- E-Mail: `mail_enabled` ist standardmäßig aus. Der Digest ist optional; die
|
||||
App bleibt ohne Mailserver voll funktionsfähig.
|
||||
App bleibt ohne Mailserver voll funktionsfähig. Einladungen werden dann
|
||||
einmalig als Link im Benutzerformular angezeigt.
|
||||
- Cron: `tools/send_reminders.php` per CLI oder token-geschützter HTTP-Aufruf.
|
||||
|
|
|
|||
14
sql/migrations/003_booking_times_fees.sql
Normal file
14
sql/migrations/003_booking_times_fees.sql
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
-- Uhrzeiten (optional) und getrennte Beträge Miete / Lieferkosten.
|
||||
--
|
||||
-- Die Felder entsprechen der Vorlage „Neuanlage“ aus docs/App DC.xlsx:
|
||||
-- Von/Bis mit Uhrzeit sowie Miete und Lieferkosten, deren Summe der
|
||||
-- Gesamtbetrag ist. Bestehende Buchungen behalten ihren Gesamtbetrag; er
|
||||
-- wird als Miete übernommen, damit Miete + Lieferkosten = Gesamt gilt.
|
||||
|
||||
ALTER TABLE bookings
|
||||
ADD COLUMN start_time TIME NULL DEFAULT NULL AFTER end_date,
|
||||
ADD COLUMN end_time TIME NULL DEFAULT NULL AFTER start_time,
|
||||
ADD COLUMN rent_cents INT UNSIGNED NOT NULL DEFAULT 0 AFTER deposit_cents,
|
||||
ADD COLUMN delivery_cents INT UNSIGNED NOT NULL DEFAULT 0 AFTER rent_cents;
|
||||
|
||||
UPDATE bookings SET rent_cents = total_cents WHERE rent_cents = 0 AND total_cents > 0;
|
||||
9
sql/migrations/004_booking_invoice_no.sql
Normal file
9
sql/migrations/004_booking_invoice_no.sql
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
-- Rechnungsnummer als eigenes Feld (Vorlage „Neuanlage", Feld „Rechnung").
|
||||
--
|
||||
-- Die Vorlage trägt dort keine Ja/Nein-Markierung, sondern die Nummer der
|
||||
-- Rechnung (z. B. RE2026054). Das bisherige Flag `invoice` bleibt als
|
||||
-- Auswertung erhalten: Es ist gesetzt, sobald eine Nummer hinterlegt ist
|
||||
-- oder „Rechnung = JA" gewählt wurde.
|
||||
|
||||
ALTER TABLE bookings
|
||||
ADD COLUMN invoice_no VARCHAR(40) NULL DEFAULT NULL AFTER invoice;
|
||||
20
sql/migrations/005_user_invites.sql
Normal file
20
sql/migrations/005_user_invites.sql
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
-- Einladungen: Ein Admin legt ein Konto an, der Benutzer vergibt sein
|
||||
-- Passwort selbst über einen zeitlich begrenzten Link (7 Tage, einmalig).
|
||||
--
|
||||
-- Gespeichert wird nur der SHA-256-Hash des Tokens. Abgelaufene und benutzte
|
||||
-- Einladungen werden beim täglichen Aufräumen entfernt.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_invites (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
user_id BIGINT UNSIGNED NOT NULL,
|
||||
token_hash CHAR(64) NOT NULL,
|
||||
created_by BIGINT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
used_at DATETIME NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uq_user_invites_token (token_hash),
|
||||
KEY idx_user_invites_user (user_id, expires_at),
|
||||
CONSTRAINT fk_user_invites_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_user_invites_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
|
@ -61,9 +61,14 @@ CREATE TABLE IF NOT EXISTS bookings (
|
|||
employee_id BIGINT UNSIGNED NOT NULL,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
start_time TIME NULL DEFAULT NULL,
|
||||
end_time TIME NULL DEFAULT NULL,
|
||||
deposit_cents INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
rent_cents INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
delivery_cents INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
total_cents INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
invoice TINYINT(1) NOT NULL DEFAULT 0,
|
||||
invoice_no VARCHAR(40) NULL DEFAULT NULL,
|
||||
kind ENUM('pickup', 'delivery') NOT NULL DEFAULT 'pickup',
|
||||
customer_name VARCHAR(190) NOT NULL,
|
||||
street VARCHAR(190) NOT NULL DEFAULT '',
|
||||
|
|
@ -132,6 +137,21 @@ CREATE TABLE IF NOT EXISTS auth_tokens (
|
|||
CONSTRAINT fk_auth_tokens_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_invites (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
user_id BIGINT UNSIGNED NOT NULL,
|
||||
token_hash CHAR(64) NOT NULL,
|
||||
created_by BIGINT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
used_at DATETIME NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uq_user_invites_token (token_hash),
|
||||
KEY idx_user_invites_user (user_id, expires_at),
|
||||
CONSTRAINT fk_user_invites_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_user_invites_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS login_attempts (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
ip VARCHAR(45) NOT NULL,
|
||||
|
|
@ -163,6 +183,8 @@ INSERT IGNORE INTO employees (name, sort_order, created_at) VALUES
|
|||
|
||||
INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (1, UTC_TIMESTAMP());
|
||||
INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (2, UTC_TIMESTAMP());
|
||||
INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (3, UTC_TIMESTAMP());
|
||||
INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (4, UTC_TIMESTAMP());
|
||||
|
||||
-- Web-Push-Abos (VAPID) und Versandprotokoll für Erinnerungen.
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
|
|
|
|||
|
|
@ -37,17 +37,24 @@ done
|
|||
[[ -f "$CREDENTIALS" ]] || { echo "Fehlt: $CREDENTIALS" >&2; exit 1; }
|
||||
|
||||
cred() {
|
||||
grep -m1 "^$1=" "$CREDENTIALS" | cut -d= -f2- | tr -d '\r' | sed 's/[[:space:]]*$//'
|
||||
# Unterstützt "KEY: value" (aktuelles Format) und "KEY=value" (älter).
|
||||
sed -n "s/^$1[:=][[:space:]]*//p" "$CREDENTIALS" | head -1 | tr -d '\r' | sed 's/[[:space:]]*$//'
|
||||
}
|
||||
|
||||
FTP_URL="$(cred FTP_URL)"
|
||||
FTP_USER="$(cred FTP_USER)"
|
||||
FTP_PASSWORD="$(cred FTP_PASSWORD)"
|
||||
DB_HOST="$(cred DB_HOST)"
|
||||
VAPID_PUBLIC_KEY="$(cred VAPID_PUBLIC_KEY)"
|
||||
VAPID_PRIVATE_KEY="$(cred VAPID_PRIVATE_KEY)"
|
||||
VAPID_SUBJECT="$(cred VAPID_SUBJECT)"
|
||||
CRON_TOKEN="$(cred DIC_CRON_TOKEN)"
|
||||
# FTP_HOST ist die Hostadresse, FTP_URL überschreibt sie bei Bedarf komplett.
|
||||
FTP_URL="${FTP_URL:-$(cred FTP_URL)}"
|
||||
if [[ -z "$FTP_URL" ]]; then
|
||||
FTP_HOST_VALUE="$(cred FTP_HOST)"
|
||||
[[ -n "$FTP_HOST_VALUE" ]] && FTP_URL="ftp://$FTP_HOST_VALUE"
|
||||
fi
|
||||
FTP_USER="${FTP_USER:-$(cred FTP_USER)}"
|
||||
FTP_PASSWORD="${FTP_PASSWORD:-$(cred FTP_PASSWORD)}"
|
||||
DB_HOST="${DB_HOST:-$(cred DB_HOST)}"
|
||||
# Push und Cron bleiben erhalten, wenn sie per Umgebung übergeben werden.
|
||||
VAPID_PUBLIC_KEY="${VAPID_PUBLIC_KEY:-$(cred VAPID_PUBLIC_KEY)}"
|
||||
VAPID_PRIVATE_KEY="${VAPID_PRIVATE_KEY:-$(cred VAPID_PRIVATE_KEY)}"
|
||||
VAPID_SUBJECT="${VAPID_SUBJECT:-$(cred VAPID_SUBJECT)}"
|
||||
CRON_TOKEN="${CRON_TOKEN:-$(cred DIC_CRON_TOKEN)}"
|
||||
DB_NAME="$(cred DB_NAME)"
|
||||
DB_USER="$(cred DB_USER)"
|
||||
DB_PASSWORD="$(cred DB_PASSWORD)"
|
||||
|
|
@ -61,7 +68,9 @@ HOST="${HOST%%:*}"
|
|||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/dic-deploy.XXXXXX")"
|
||||
trap 'rm -rf "$TMP_DIR"' EXIT
|
||||
|
||||
CURL=(curl --ssl-reqd --insecure --silent --show-error --connect-timeout 20 --max-time 900 --user "$FTP_USER:$FTP_PASSWORD")
|
||||
# TLS 1.3 bricht bei diesem FTP-Server (KAS) bei Dateien über ~16 KB auf dem
|
||||
# Datenkanal mit "426 Transfer aborted" ab; TLS 1.2 überträgt zuverlässig.
|
||||
CURL=(curl --ssl-reqd --tlsv1.2 --tls-max 1.2 --insecure --silent --show-error --connect-timeout 20 --max-time 900 --user "$FTP_USER:$FTP_PASSWORD")
|
||||
|
||||
ftp_url() {
|
||||
printf 'ftp://%s/%s/%s' "$HOST" "$REMOTE_DIR" "$1"
|
||||
|
|
@ -143,6 +152,34 @@ os.chmod(target, 0o600)
|
|||
PY
|
||||
}
|
||||
|
||||
# Übernimmt Push-Schlüssel, Cron-Token und Mail-Einstellungen aus der
|
||||
# bestehenden Live-Konfiguration, wenn sie nicht per Umgebung gesetzt sind.
|
||||
# So macht ein Sync bestehende Push-Abos und Cron-Aufrufe nicht ungültig.
|
||||
preserve_remote_secrets() {
|
||||
[[ -n "$VAPID_PUBLIC_KEY" && -n "$VAPID_PRIVATE_KEY" && -n "$CRON_TOKEN" && -n "${DIC_MAIL_ENABLED:-}" ]] && return 0
|
||||
local file="$TMP_DIR/current-config.php"
|
||||
ftp_get "app/config.local.php" "$file" 2>/dev/null || return 0
|
||||
eval "$(VAPID_PUBLIC_KEY="$VAPID_PUBLIC_KEY" VAPID_PRIVATE_KEY="$VAPID_PRIVATE_KEY" \
|
||||
VAPID_SUBJECT="$VAPID_SUBJECT" CRON_TOKEN="$CRON_TOKEN" \
|
||||
DIC_MAIL_ENABLED="${DIC_MAIL_ENABLED:-}" DIC_MAIL_FROM="${DIC_MAIL_FROM:-}" \
|
||||
php -r '
|
||||
$c = require $argv[1];
|
||||
$values = [
|
||||
"VAPID_PUBLIC_KEY" => (string) $c["push"]["public_key"],
|
||||
"VAPID_PRIVATE_KEY" => (string) $c["push"]["private_key"],
|
||||
"VAPID_SUBJECT" => (string) $c["push"]["subject"],
|
||||
"CRON_TOKEN" => (string) $c["app"]["cron_token"],
|
||||
"DIC_MAIL_FROM" => (string) $c["app"]["mail_from"],
|
||||
"DIC_MAIL_ENABLED" => !empty($c["app"]["mail_enabled"]) ? "true" : "false",
|
||||
];
|
||||
foreach ($values as $key => $value) {
|
||||
if (getenv($key) === "" && $value !== "") {
|
||||
echo "export ", $key, "=", escapeshellarg($value), "\n";
|
||||
}
|
||||
}
|
||||
' "$file")"
|
||||
}
|
||||
|
||||
upload_tree() {
|
||||
local source_root="$1" remote_prefix="$2"
|
||||
while IFS= read -r file; do
|
||||
|
|
@ -157,6 +194,7 @@ upload_tree() {
|
|||
|
||||
do_sync() {
|
||||
local token cron_token
|
||||
preserve_remote_secrets
|
||||
token="$(openssl rand -hex 24)"
|
||||
cron_token="${CRON_TOKEN:-$(openssl rand -hex 24)}"
|
||||
make_config "$token" "$cron_token"
|
||||
|
|
@ -236,7 +274,7 @@ PY
|
|||
echo >&2
|
||||
exit 1
|
||||
fi
|
||||
"${CURL[@]}" "ftp://$HOST/" -Q "-DELE $REMOTE_DIR/install.php" >/dev/null 2>&1 || true
|
||||
"${CURL[@]}" "ftp://$HOST/" -Q "DELE $REMOTE_DIR/install.php" >/dev/null 2>&1 || true
|
||||
echo "install.php auf dem Server entfernt."
|
||||
}
|
||||
|
||||
|
|
|
|||
228
tools/dump_drink_it_cold.py
Executable file
228
tools/dump_drink_it_cold.py
Executable file
|
|
@ -0,0 +1,228 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Dumpt die Remote-DB von Drink it cold nach tools/dumps.
|
||||
|
||||
Aufruf:
|
||||
./dump_drink_it_cold.py # Dump nach tools/dumps, 14 Dumps behalten
|
||||
./dump_drink_it_cold.py --keep 30 # 30 Dumps behalten
|
||||
./dump_drink_it_cold.py --keep 0 # nichts aufräumen
|
||||
./dump_drink_it_cold.py --dir /pfad # anderes Zielverzeichnis
|
||||
./dump_drink_it_cold.py --check # nur Verbindung/Parameter prüfen
|
||||
|
||||
Zugangsdaten kommen aus docs/credentials.txt (gitignored), überschreibbar per
|
||||
Umgebungsvariablen DB_HOST / DB_PORT / DB_USER / DB_PASS / DB_NAME.
|
||||
|
||||
Die Dumps enthalten personenbezogene Daten (Namen, Adressen, Telefonnummern,
|
||||
E-Mail-Adressen) und werden deshalb mit 0600 in einem 0700-Verzeichnis
|
||||
abgelegt. Alte Dumps werden nur nach dem Muster drink-it-cold_live_*.sql
|
||||
gelöscht.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CRED_FILE = os.path.join(REPO_ROOT, "docs", "credentials.txt")
|
||||
DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps")
|
||||
DUMP_PATTERN = "drink-it-cold_live_*.sql"
|
||||
DEFAULT_KEEP = 14
|
||||
|
||||
|
||||
def log(message=""):
|
||||
print(message, flush=True)
|
||||
|
||||
|
||||
def read_credentials(path):
|
||||
"""Liest KEY: value (credentials.txt) und KEY=value (ältere Dateien)."""
|
||||
creds = {}
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" in line and (":" not in line or line.index("=") < line.index(":")):
|
||||
key, _, value = line.partition("=")
|
||||
elif ":" in line:
|
||||
key, _, value = line.partition(":")
|
||||
else:
|
||||
continue
|
||||
creds[key.strip()] = value.strip()
|
||||
return creds
|
||||
|
||||
|
||||
def connection():
|
||||
if not os.path.isfile(CRED_FILE):
|
||||
raise SystemExit("Fehler: Credentials nicht gefunden: %s" % CRED_FILE)
|
||||
|
||||
creds = read_credentials(CRED_FILE)
|
||||
missing = [key for key in ("DB_HOST", "DB_NAME", "DB_USER", "DB_PASSWORD") if not creds.get(key)]
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
"Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing))
|
||||
)
|
||||
|
||||
return {
|
||||
"host": os.environ.get("DB_HOST") or creds["DB_HOST"],
|
||||
"port": os.environ.get("DB_PORT") or creds.get("DB_PORT") or "3306",
|
||||
"user": os.environ.get("DB_USER") or creds["DB_USER"],
|
||||
"password": os.environ.get("DB_PASS") or creds["DB_PASSWORD"],
|
||||
"name": os.environ.get("DB_NAME") or creds["DB_NAME"],
|
||||
}
|
||||
|
||||
|
||||
def dump_command(conn):
|
||||
return [
|
||||
"mysqldump",
|
||||
"--no-tablespaces",
|
||||
"--column-statistics=0",
|
||||
"--single-transaction",
|
||||
"--quick",
|
||||
"--default-character-set=utf8mb4",
|
||||
"-h", str(conn["host"]),
|
||||
"-P", str(conn["port"]),
|
||||
"-u", str(conn["user"]),
|
||||
str(conn["name"]),
|
||||
]
|
||||
|
||||
|
||||
def ensure_private_dir(path):
|
||||
os.makedirs(path, mode=0o700, exist_ok=True)
|
||||
try:
|
||||
os.chmod(path, 0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def check_connection(conn):
|
||||
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"mysql",
|
||||
"--connect-timeout=15",
|
||||
"--default-character-set=utf8mb4",
|
||||
"-h", str(conn["host"]),
|
||||
"-P", str(conn["port"]),
|
||||
"-u", str(conn["user"]),
|
||||
"-N", "-B", "-e", "SELECT 1;",
|
||||
str(conn["name"]),
|
||||
],
|
||||
env=env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit(
|
||||
"Fehler: Datenbank nicht erreichbar:\n%s"
|
||||
% proc.stderr.decode("utf-8", "replace").strip()
|
||||
)
|
||||
|
||||
|
||||
def dump_database(conn, path):
|
||||
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
||||
with open(path, "wb") as out:
|
||||
proc = subprocess.run(
|
||||
dump_command(conn),
|
||||
env=env,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=out,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit(
|
||||
"Fehler: mysqldump fehlgeschlagen:\n%s"
|
||||
% proc.stderr.decode("utf-8", "replace").strip()
|
||||
)
|
||||
if os.path.getsize(path) == 0:
|
||||
raise SystemExit("Fehler: Dump ist leer: %s" % path)
|
||||
with open(path, "rb") as handle:
|
||||
handle.seek(max(0, os.path.getsize(path) - 200))
|
||||
if b"Dump completed" not in handle.read():
|
||||
raise SystemExit("Fehler: Dump wirkt unvollständig (Abschlusszeile fehlt): %s" % path)
|
||||
os.chmod(path, 0o600)
|
||||
return path
|
||||
|
||||
|
||||
def prune(dump_dir, keep):
|
||||
if keep <= 0:
|
||||
return []
|
||||
dumps = sorted(glob.glob(os.path.join(dump_dir, DUMP_PATTERN)))
|
||||
removed = []
|
||||
for path in dumps[:-keep]:
|
||||
try:
|
||||
os.unlink(path)
|
||||
removed.append(path)
|
||||
except OSError as exc:
|
||||
log(" Warnung: konnte %s nicht löschen: %s" % (path, exc))
|
||||
return removed
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Dumpt die Remote-DB nach tools/dumps und räumt alte Dumps auf.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="Beispiele:\n"
|
||||
" %(prog)s\n"
|
||||
" %(prog)s --keep 30\n"
|
||||
" %(prog)s --keep 0\n"
|
||||
" %(prog)s --check\n",
|
||||
)
|
||||
parser.add_argument("--dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR),
|
||||
help="Zielverzeichnis (Default: %(default)s)")
|
||||
parser.add_argument("--keep", type=int, default=DEFAULT_KEEP,
|
||||
help="Anzahl aufzubewahrender Dumps, 0 = nichts löschen "
|
||||
"(Default: %(default)s)")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="nur Verbindung und Parameter prüfen, keinen Dump schreiben")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.keep < 0:
|
||||
parser.error("--keep darf nicht negativ sein")
|
||||
|
||||
conn = connection()
|
||||
log("Ziel: %s@%s:%s/%s" % (conn["user"], conn["host"], conn["port"], conn["name"]))
|
||||
|
||||
check_connection(conn)
|
||||
log("Login: OK")
|
||||
|
||||
if args.check:
|
||||
log("Check beendet, kein Dump geschrieben.")
|
||||
return 0
|
||||
|
||||
ensure_private_dir(args.dir)
|
||||
stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
final_path = os.path.join(args.dir, "drink-it-cold_live_%s.sql" % stamp)
|
||||
|
||||
fd, tmp_path = tempfile.mkstemp(prefix=".drink-it-cold_dump_", suffix=".tmp", dir=args.dir)
|
||||
os.close(fd)
|
||||
try:
|
||||
dump_database(conn, tmp_path)
|
||||
os.replace(tmp_path, final_path)
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
size_mb = os.path.getsize(final_path) / 1024 / 1024
|
||||
log("Dump: %s (%.1f MB, 0600)" % (final_path, size_mb))
|
||||
|
||||
removed = prune(args.dir, args.keep)
|
||||
for path in removed:
|
||||
log("Alte Datei gelöscht: %s" % path)
|
||||
remaining = sorted(glob.glob(os.path.join(args.dir, DUMP_PATTERN)))
|
||||
log("Vorhanden: %d Dump(s)%s" % (
|
||||
len(remaining),
|
||||
"" if args.keep <= 0 else " (keep=%d)" % args.keep,
|
||||
))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
|
|
@ -25,8 +25,9 @@ $push = push_dispatch_due($lookback);
|
|||
$mail = reminder_send_due($lookback);
|
||||
|
||||
fwrite(STDOUT, sprintf(
|
||||
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
|
||||
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['reminder_mail_log'],
|
||||
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
|
||||
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
|
||||
$cleanup['reminder_mail_log'],
|
||||
$cleanup['reminder_push_log'], $cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
|
||||
));
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,10 @@
|
|||
/** @var array $employees */
|
||||
/** @var int $pushCount */
|
||||
/** @var bool $pushAvailable */
|
||||
/** @var bool $mailEnabled */
|
||||
/** @var bool $sendInvite */
|
||||
/** @var array|null $inviteNotice */
|
||||
/** @var array|null $openInvite */
|
||||
$isSelf = $editing !== null && (int) $editing['id'] === (int) auth_user()['id'];
|
||||
$fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
||||
?>
|
||||
|
|
@ -18,10 +22,34 @@ $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
|||
<div>
|
||||
<p class="eyebrow">Verwaltung · Benutzer</p>
|
||||
<h1><?= $editing ? e($editing['first_name'] . ' ' . $editing['last_name']) : 'Benutzer anlegen' ?></h1>
|
||||
<p class="page-head__lede"><?= $editing ? 'Zugang, Rolle und Mitarbeiterzuordnung bearbeiten.' : 'Der Benutzer meldet sich anschließend mit Vor- und Nachnamen sowie dem Startpasswort an.' ?></p>
|
||||
<p class="page-head__lede"><?= $editing ? 'Zugang, Rolle und Mitarbeiterzuordnung bearbeiten.' : 'Konto anlegen und Zugang geben – mit Startpasswort oder per Einladung, bei der der Benutzer sein Passwort selbst setzt.' ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($inviteNotice): ?>
|
||||
<section class="card card--copy" data-copy-wrap>
|
||||
<div class="card__head card__head--row">
|
||||
<div>
|
||||
<h2>Einladungslink</h2>
|
||||
<p>
|
||||
<?php if ($inviteNotice['sent']): ?>
|
||||
Die Einladung wurde per E-Mail verschickt. Der Link gilt bis
|
||||
<?= e(fmt_datetime($inviteNotice['expires_at'])) ?> und lässt sich nur einmal verwenden.
|
||||
<?php else: ?>
|
||||
<?= e($inviteNotice['error']) ?> Der Link gilt bis
|
||||
<?= e(fmt_datetime($inviteNotice['expires_at'])) ?> und lässt sich nur einmal verwenden.
|
||||
Er wird nur jetzt angezeigt.
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
</div>
|
||||
<button class="btn" type="button" data-copy>
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-copy"/></svg> Link kopieren
|
||||
</button>
|
||||
</div>
|
||||
<textarea class="copy-source copy-source--visible" data-copy-toast="Einladungslink kopiert." readonly rows="2"><?= e($inviteNotice['url']) ?></textarea>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($errors): ?>
|
||||
<div class="alert alert--error" role="alert">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
|
||||
|
|
@ -54,7 +82,7 @@ $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
|||
<?php if ($fieldError('last_name')): ?><em class="field-error"><?= e($fieldError('last_name')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field field--wide<?= $fieldError('email') !== '' ? ' has-error' : '' ?>">
|
||||
<span>E-Mail <small class="optional">(optional, für Erinnerungs-E-Mails)</small></span>
|
||||
<span>E-Mail <small class="optional">(optional, für Erinnerungen und Einladungen)</small></span>
|
||||
<input type="email" name="email" value="<?= e($values['email']) ?>" maxlength="190" autocomplete="off">
|
||||
<?php if ($fieldError('email')): ?><em class="field-error"><?= e($fieldError('email')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
|
@ -63,13 +91,35 @@ $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
|||
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2><?= $editing ? 'Passwort zurücksetzen' : 'Startpasswort' ?></h2>
|
||||
<p><?= $editing ? 'Leer lassen, wenn das Passwort unverändert bleiben soll. Ein neues Passwort macht bestehende Anmeldungen ungültig.' : 'Mindestens 8 Zeichen. Der Benutzer sollte es nach der ersten Anmeldung ändern.' ?></p>
|
||||
<h2><?= $editing ? 'Passwort zurücksetzen' : 'Zugang und Passwort' ?></h2>
|
||||
<p>
|
||||
<?php if ($editing): ?>
|
||||
Leer lassen, wenn das Passwort unverändert bleiben soll. Ein neues Passwort macht bestehende Anmeldungen ungültig.
|
||||
<?php else: ?>
|
||||
Entweder ein Startpasswort vergeben (mind. 8 Zeichen) oder eine Einladung senden – dann vergibt der Benutzer sein Passwort selbst.
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<?php if (!$editing): ?>
|
||||
<div class="field field--wide">
|
||||
<span>Zugang</span>
|
||||
<label class="check check--boxed">
|
||||
<input type="checkbox" name="send_invite" value="1"<?= $sendInvite ? ' checked' : '' ?>>
|
||||
<span><?= $mailEnabled ? 'Einladung per E-Mail senden' : 'Einladungslink erzeugen' ?> – der Benutzer vergibt sein Passwort selbst</span>
|
||||
</label>
|
||||
<em class="muted small">
|
||||
<?php if ($mailEnabled): ?>
|
||||
Der Link gilt sieben Tage und wird zusätzlich im Formular angezeigt.
|
||||
<?php else: ?>
|
||||
E-Mail-Versand ist deaktiviert. Der Link erscheint nach dem Speichern im Formular und muss selbst weitergegeben werden.
|
||||
<?php endif; ?>
|
||||
</em>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<label class="field<?= $fieldError('password') !== '' ? ' has-error' : '' ?>">
|
||||
<span><?= $editing ? 'Neues Passwort' : 'Passwort' ?></span>
|
||||
<input type="password" name="password" autocomplete="new-password" minlength="8"<?= $editing ? '' : ' required' ?>>
|
||||
<span><?= $editing ? 'Neues Passwort' : 'Startpasswort' ?><?php if (!$editing): ?> <small class="optional">(bei Einladung nicht nötig)</small><?php endif; ?></span>
|
||||
<input type="password" name="password" autocomplete="new-password" minlength="8">
|
||||
<?php if ($fieldError('password')): ?><em class="field-error"><?= e($fieldError('password')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<div class="field">
|
||||
|
|
@ -154,6 +204,33 @@ $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
|||
</form>
|
||||
|
||||
<?php if ($editing && !$isSelf): ?>
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2>Zugang per Einladung</h2>
|
||||
<p>
|
||||
Erzeugt einen neuen Link, mit dem <?= e($editing['first_name']) ?> ein eigenes Passwort setzen kann.
|
||||
Das bisherige Passwort wird dabei ungültig, angemeldete Geräte werden abgemeldet.
|
||||
<?php if ($openInvite): ?>
|
||||
Aktuell offen: Link vom <?= e(fmt_datetime($openInvite['created_at'])) ?>, gültig bis <?= e(fmt_datetime($openInvite['expires_at'])) ?>.
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
</div>
|
||||
<form method="post" action="<?= e(url('/admin/users/' . (int) $editing['id'] . '/invite')) ?>"
|
||||
data-confirm="Einladung erzeugen? Das bisherige Passwort wird sofort ungültig.">
|
||||
<?= csrf_field() ?>
|
||||
<button class="btn primary" type="submit"><svg class="ico" aria-hidden="true"><use href="#i-mail"/></svg> Einladung erzeugen<?= $mailEnabled ? ' und senden' : '' ?></button>
|
||||
</form>
|
||||
<p class="muted small">
|
||||
<?php if (trim((string) ($editing['email'] ?? '')) === ''): ?>
|
||||
Für dieses Konto ist keine E-Mail-Adresse hinterlegt. Der Link erscheint nach dem Erzeugen hier zum Weitergeben.
|
||||
<?php elseif ($mailEnabled): ?>
|
||||
Der Link wird an <?= e($editing['email']) ?> gemailt und zusätzlich hier angezeigt.
|
||||
<?php else: ?>
|
||||
E-Mail-Versand ist deaktiviert. Der Link erscheint nach dem Erzeugen hier zum Weitergeben.
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="card card--danger">
|
||||
<div class="card__head">
|
||||
<h2>Benutzer löschen</h2>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
/** @var array $pushCounts */
|
||||
/** @var array $pushLastUpdate */
|
||||
/** @var bool $pushConfigured */
|
||||
/** @var array $openInvites */
|
||||
?>
|
||||
<div class="page-head page-head--compact">
|
||||
<div>
|
||||
|
|
@ -45,7 +46,11 @@
|
|||
<span class="table-person">
|
||||
<span class="avatar avatar--small"><?= e(initials($row['first_name'] . ' ' . $row['last_name'])) ?></span>
|
||||
<span><strong><?= e($row['first_name'] . ' ' . $row['last_name']) ?></strong>
|
||||
<small><?= e($row['email'] ?: 'keine E-Mail hinterlegt') ?></small></span>
|
||||
<small><?= e($row['email'] ?: 'keine E-Mail hinterlegt') ?></small>
|
||||
<?php if (isset($openInvites[(int) $row['id']])): ?>
|
||||
<small class="invite-open">Einladung offen bis <?= e(fmt_datetime($openInvites[(int) $row['id']])) ?></small>
|
||||
<?php endif; ?>
|
||||
</span>
|
||||
</span>
|
||||
</td>
|
||||
<td><span class="pill <?= $row['role'] === 'admin' ? 'pill--blue' : 'pill--grey' ?>"><?= $row['role'] === 'admin' ? 'Administrator' : 'Mitarbeiter' ?></span></td>
|
||||
|
|
|
|||
121
views/availability.php
Normal file
121
views/availability.php
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
<?php
|
||||
/** @var string $from */
|
||||
/** @var string $to */
|
||||
/** @var bool $checked */
|
||||
/** @var array $errors */
|
||||
/** @var array $groups */
|
||||
/** @var int $freeCount */
|
||||
/** @var int $total */
|
||||
$fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
||||
$bookingUrl = static fn (array $trailer): string => '/bookings/new?trailer=' . (int) $trailer['id']
|
||||
. '&start=' . rawurlencode($from) . '&end=' . rawurlencode($to);
|
||||
$groupMeta = [
|
||||
'trailer' => [
|
||||
'title' => 'Anhänger',
|
||||
'empty' => 'Keine Anhänger hinterlegt.',
|
||||
'none_free' => 'Im Zeitraum ist kein Anhänger frei.',
|
||||
],
|
||||
'chest' => [
|
||||
'title' => 'Truhen',
|
||||
'empty' => 'Keine Truhen hinterlegt.',
|
||||
'none_free' => 'Im Zeitraum ist keine Truhe frei.',
|
||||
],
|
||||
];
|
||||
?>
|
||||
<div class="page-head page-head--compact">
|
||||
<div>
|
||||
<p class="eyebrow">Übersicht</p>
|
||||
<h1>Verfügbarkeit</h1>
|
||||
<p class="page-head__lede">Zeitraum wählen – die App zeigt, welche Anhänger und Truhen in dieser Zeit frei sind.</p>
|
||||
</div>
|
||||
<div class="page-head__actions">
|
||||
<a class="btn" href="<?= e(url('/calendar?view=month&date=' . $from)) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-calendar"/></svg> Im Kalender
|
||||
</a>
|
||||
<a class="btn" href="<?= e(url('/')) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-grid"/></svg> Zur Übersicht
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2>Zeitraum</h2>
|
||||
<p>Ein Wechseltag ist erlaubt: Endet eine Buchung am Tag des neuen Beginns, gilt das Fahrzeug als frei.</p>
|
||||
</div>
|
||||
<form method="get" action="<?= e(url('/availability')) ?>" class="form-grid">
|
||||
<label class="field<?= $fieldError('from') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Von</span>
|
||||
<input type="date" name="from" value="<?= e($from) ?>" required>
|
||||
<?php if ($fieldError('from')): ?><em class="field-error"><?= e($fieldError('from')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field<?= $fieldError('to') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Bis</span>
|
||||
<input type="date" name="to" value="<?= e($to) ?>" required>
|
||||
<?php if ($fieldError('to')): ?><em class="field-error"><?= e($fieldError('to')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<div class="field field--wide">
|
||||
<button class="btn primary" type="submit">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-search"/></svg> Verfügbarkeit prüfen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<?php if ($checked && !$errors): ?>
|
||||
<section class="card">
|
||||
<div class="card__head card__head--row">
|
||||
<div>
|
||||
<h2>Ergebnis</h2>
|
||||
<p><?= e(fmt_date_range($from, $to)) ?> · <?= (int) $freeCount ?> von <?= (int) $total ?> frei</p>
|
||||
</div>
|
||||
<a class="btn small" href="<?= e(url('/bookings/new?start=' . rawurlencode($from) . '&end=' . rawurlencode($to))) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-plus"/></svg> Neue Buchung
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="availability-grid">
|
||||
<?php foreach ($groupMeta as $key => $meta): ?>
|
||||
<?php
|
||||
$rows = $groups[$key];
|
||||
$groupTotal = (int) ($totals[$key] ?? 0);
|
||||
?>
|
||||
<div class="availability-group">
|
||||
<h3>
|
||||
<?= e($meta['title']) ?>
|
||||
<span class="muted small"><?= count($rows) ?> von <?= $groupTotal ?> frei</span>
|
||||
</h3>
|
||||
<?php if (!$rows): ?>
|
||||
<p class="muted small"><?= e($groupTotal === 0 ? $meta['empty'] : $meta['none_free']) ?></p>
|
||||
<?php else: ?>
|
||||
<ul class="availability-list">
|
||||
<?php foreach ($rows as $row): ?>
|
||||
<?php $trailer = $row['trailer']; ?>
|
||||
<li class="availability-row is-free">
|
||||
<span class="availability-row__name">
|
||||
<span class="trailer-chip" style="--trailer: <?= e($trailer['color_hex']) ?>; --trailer-text: <?= e(contrast_color($trailer['color_hex'])) ?>">
|
||||
<span class="trailer-dot" style="--trailer: <?= e($trailer['color_hex']) ?>"></span>
|
||||
<?= e($trailer['label']) ?>
|
||||
</span>
|
||||
</span>
|
||||
<a class="btn small primary" href="<?= e(url($bookingUrl($trailer))) ?>">Buchen</a>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</section>
|
||||
<?php elseif ($checked): ?>
|
||||
<div class="alert alert--error" role="alert">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
|
||||
<div><strong>Bitte den Zeitraum prüfen.</strong>
|
||||
<?php foreach ($errors as $message): ?><p><?= e($message) ?></p><?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="empty-state small">
|
||||
<p>Zeitraum wählen und „Verfügbarkeit prüfen" – danach kannst du direkt buchen.</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
|
@ -20,7 +20,8 @@ $returnTo = '/bookings/' . (int) $booking['id'];
|
|||
<div class="page-head page-head--compact">
|
||||
<div>
|
||||
<p class="eyebrow">
|
||||
<?= e(fmt_date_range($booking['start_date'], $booking['end_date'])) ?> ·
|
||||
<?= e(fmt_date_with_time($booking['start_date'], $booking['start_time'] ?? null)) ?> –
|
||||
<?= e(fmt_date_with_time($booking['end_date'], $booking['end_time'] ?? null)) ?> ·
|
||||
<?= e($booking['trailer_label']) ?> · <?= e($booking['employee_name']) ?>
|
||||
</p>
|
||||
<h1><?= e($booking['customer_name']) ?>
|
||||
|
|
@ -143,20 +144,25 @@ $returnTo = '/bookings/' . (int) $booking['id'];
|
|||
<dd>
|
||||
<span class="trailer-chip" style="--trailer: <?= e($booking['trailer_color']) ?>; --trailer-text: <?= e(contrast_color($booking['trailer_color'])) ?>">
|
||||
<span class="trailer-dot" style="--trailer: <?= e($booking['trailer_color']) ?>"></span>
|
||||
<?= e($booking['trailer_label']) ?> · <?= e($booking['trailer_color_name']) ?>
|
||||
<?= e($booking['trailer_label']) ?>
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div><dt>Mitarbeiter</dt><dd><?= e($booking['employee_name']) ?></dd></div>
|
||||
<div><dt>Von</dt><dd><?= e(fmt_date_long($booking['start_date'])) ?></dd></div>
|
||||
<div><dt>Bis</dt><dd><?= e(fmt_date_long($booking['end_date'])) ?></dd></div>
|
||||
<div><dt>Von</dt><dd><?= e(fmt_date_long($booking['start_date'])) ?><?php if (fmt_time($booking['start_time'] ?? null) !== ''): ?> · <?= e(fmt_time($booking['start_time'])) ?> Uhr<?php endif; ?></dd></div>
|
||||
<div><dt>Bis</dt><dd><?= e(fmt_date_long($booking['end_date'])) ?><?php if (fmt_time($booking['end_time'] ?? null) !== ''): ?> · <?= e(fmt_time($booking['end_time'])) ?> Uhr<?php endif; ?></dd></div>
|
||||
<div><dt>Art</dt><dd><span class="pill pill--blue"><?= e(booking_kind_label((string) $booking['kind'])) ?></span></dd></div>
|
||||
<div><dt>Rechnung</dt><dd><span class="pill <?= (int) $booking['invoice'] === 1 ? 'pill--green' : 'pill--grey' ?>"><?= e(booking_invoice_label($booking['invoice'])) ?></span></dd></div>
|
||||
<?php if (trim((string) ($booking['invoice_no'] ?? '')) !== ''): ?>
|
||||
<div><dt>Rechnungsnummer</dt><dd><?= e((string) $booking['invoice_no']) ?></dd></div>
|
||||
<?php endif; ?>
|
||||
</dl>
|
||||
<hr>
|
||||
<dl class="money-list">
|
||||
<div><dt>Anzahlung</dt><dd><?= e(fmt_money((int) $booking['deposit_cents'])) ?></dd></div>
|
||||
<div><dt>Miete</dt><dd><?= e(fmt_money((int) $booking['rent_cents'])) ?></dd></div>
|
||||
<div><dt>Lieferkosten</dt><dd><?= e(fmt_money((int) $booking['delivery_cents'])) ?></dd></div>
|
||||
<div><dt>Gesamtbetrag</dt><dd><?= e(fmt_money((int) $booking['total_cents'])) ?></dd></div>
|
||||
<div><dt>Anzahlung</dt><dd><?= e(fmt_money((int) $booking['deposit_cents'])) ?></dd></div>
|
||||
<div class="is-strong"><dt>Noch zu zahlen</dt><dd><?= e(fmt_money($due)) ?></dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
|
|
|||
|
|
@ -63,44 +63,16 @@ $backUrl = $isEdit ? '/bookings/' . (int) $booking['id'] : '/calendar';
|
|||
<div class="form-main">
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2>Mietzeitraum & Zuständigkeit</h2>
|
||||
<p>Ganztägig – Uhrzeiten sind nicht nötig. Ein Wechseltag am Ende und Anfang ist erlaubt.</p>
|
||||
<h2>Buchungsdaten</h2>
|
||||
<p>
|
||||
Reihenfolge wie in der Excel-Vorlage „Neuanlage". Werte in der Tabelle untereinander
|
||||
markieren, kopieren und hier in ein beliebiges Feld einfügen – sie werden der Reihe nach
|
||||
eingesetzt. Uhrzeiten sind optional, ohne Angabe gilt der Termin ganztägig.
|
||||
</p>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<label class="field<?= $fieldError('trailer_id') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Kühlanhänger</span>
|
||||
<select name="trailer_id" required data-trailer-select>
|
||||
<?php foreach ($trailers as $trailer): ?>
|
||||
<option value="<?= (int) $trailer['id'] ?>" data-color="<?= e($trailer['color_hex']) ?>" data-color-name="<?= e($trailer['color_name']) ?>"<?= (int) $values['trailer_id'] === (int) $trailer['id'] ? ' selected' : '' ?>>
|
||||
<?= e($trailer['label'] . ' · ' . $trailer['color_name']) ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php if ($fieldError('trailer_id')): ?><em class="field-error"><?= e($fieldError('trailer_id')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<div class="field field--trailer-preview" aria-hidden="true">
|
||||
<span>Farbe im Kalender</span>
|
||||
<span class="trailer-preview" data-trailer-preview
|
||||
style="--trailer: <?= e($selectedTrailer['color_hex'] ?? '#196abc') ?>; --trailer-text: <?= e(contrast_color($selectedTrailer['color_hex'] ?? '#196abc')) ?>">
|
||||
<span class="trailer-dot" style="--trailer: <?= e($selectedTrailer['color_hex'] ?? '#196abc') ?>"></span>
|
||||
<span data-trailer-preview-label><?= e($selectedTrailer['label'] ?? '') ?> · <?= e($selectedTrailer['color_name'] ?? '') ?></span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label class="field<?= $fieldError('start_date') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Mietbeginn (Von)</span>
|
||||
<input type="date" name="start_date" value="<?= e($values['start_date']) ?>" required data-date-start>
|
||||
<?php if ($fieldError('start_date')): ?><em class="field-error"><?= e($fieldError('start_date')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field<?= $fieldError('end_date') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Mietende (Bis)</span>
|
||||
<input type="date" name="end_date" value="<?= e($values['end_date']) ?>" required data-date-end>
|
||||
<?php if ($fieldError('end_date')): ?><em class="field-error"><?= e($fieldError('end_date')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('employee_id') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Zuständiger Mitarbeiter</span>
|
||||
<div class="form-grid form-grid--single" data-paste-targets>
|
||||
<label class="field" data-paste-field="employee_id">
|
||||
<span>Fahrer</span>
|
||||
<select name="employee_id" required>
|
||||
<?php foreach ($employees as $employee): ?>
|
||||
<option value="<?= (int) $employee['id'] ?>"<?= (int) $values['employee_id'] === (int) $employee['id'] ? ' selected' : '' ?>>
|
||||
|
|
@ -111,19 +83,112 @@ $backUrl = $isEdit ? '/bookings/' . (int) $booking['id'] : '/calendar';
|
|||
<?php if ($fieldError('employee_id')): ?><em class="field-error"><?= e($fieldError('employee_id')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<div class="field field--wide">
|
||||
<div class="conflict-hint" data-conflict hidden></div>
|
||||
<div class="field<?= $fieldError('trailer_id') !== '' ? ' has-error' : '' ?>" data-paste-field="trailer_id">
|
||||
<span>Kühlanhänger</span>
|
||||
<div class="field-with-aside">
|
||||
<select name="trailer_id" required data-trailer-select>
|
||||
<?php foreach ($trailers as $trailer): ?>
|
||||
<option value="<?= (int) $trailer['id'] ?>" data-color="<?= e($trailer['color_hex']) ?>"<?= (int) $values['trailer_id'] === (int) $trailer['id'] ? ' selected' : '' ?>>
|
||||
<?= e($trailer['label']) ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<span class="trailer-preview" data-trailer-preview aria-hidden="true"
|
||||
style="--trailer: <?= e($selectedTrailer['color_hex'] ?? '#196abc') ?>; --trailer-text: <?= e(contrast_color($selectedTrailer['color_hex'] ?? '#196abc')) ?>">
|
||||
<span class="trailer-dot" style="--trailer: <?= e($selectedTrailer['color_hex'] ?? '#196abc') ?>"></span>
|
||||
<span data-trailer-preview-label><?= e($selectedTrailer['label'] ?? '') ?></span>
|
||||
</span>
|
||||
</div>
|
||||
<?php if ($fieldError('trailer_id')): ?><em class="field-error"><?= e($fieldError('trailer_id')) ?></em><?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2>Beträge & Rechnung</h2>
|
||||
<p>„Noch zu zahlen“ wird automatisch aus Gesamtbetrag minus Anzahlung berechnet.</p>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<label class="field<?= $fieldError('deposit') !== '' ? ' has-error' : '' ?>">
|
||||
<div class="field" data-paste-field="kind">
|
||||
<span>Art</span>
|
||||
<div class="segmented-radio">
|
||||
<label><input type="radio" name="kind" value="pickup"<?= $values['kind'] === 'pickup' ? ' checked' : '' ?>><span>Abholer</span></label>
|
||||
<label><input type="radio" name="kind" value="delivery"<?= $values['kind'] === 'delivery' ? ' checked' : '' ?>><span>Lieferung</span></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="field<?= $fieldError('start_date') !== '' ? ' has-error' : '' ?>" data-paste-field="start_date">
|
||||
<span>Von</span>
|
||||
<input type="date" name="start_date" value="<?= e($values['start_date']) ?>" required data-date-start>
|
||||
<?php if ($fieldError('start_date')): ?><em class="field-error"><?= e($fieldError('start_date')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('start_time') !== '' ? ' has-error' : '' ?>" data-paste-field="start_time">
|
||||
<span>Uhrzeit</span>
|
||||
<input type="time" name="start_time" value="<?= e(fmt_time($values['start_time'])) ?>" data-time-start>
|
||||
<?php if ($fieldError('start_time')): ?><em class="field-error"><?= e($fieldError('start_time')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('end_date') !== '' ? ' has-error' : '' ?>" data-paste-field="end_date">
|
||||
<span>Bis</span>
|
||||
<input type="date" name="end_date" value="<?= e($values['end_date']) ?>" required data-date-end>
|
||||
<?php if ($fieldError('end_date')): ?><em class="field-error"><?= e($fieldError('end_date')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('end_time') !== '' ? ' has-error' : '' ?>" data-paste-field="end_time">
|
||||
<span>Uhrzeit</span>
|
||||
<input type="time" name="end_time" value="<?= e(fmt_time($values['end_time'])) ?>" data-time-end>
|
||||
<?php if ($fieldError('end_time')): ?><em class="field-error"><?= e($fieldError('end_time')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('customer_name') !== '' ? ' has-error' : '' ?>" data-paste-field="customer_name">
|
||||
<span>Name</span>
|
||||
<input type="text" name="customer_name" value="<?= e($values['customer_name']) ?>" autocomplete="name" required data-customer-name>
|
||||
<?php if ($fieldError('customer_name')): ?><em class="field-error"><?= e($fieldError('customer_name')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('street') !== '' ? ' has-error' : '' ?>" data-paste-field="street">
|
||||
<span>Strasse</span>
|
||||
<input type="text" name="street" value="<?= e($values['street']) ?>" autocomplete="street-address">
|
||||
<?php if ($fieldError('street')): ?><em class="field-error"><?= e($fieldError('street')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('city') !== '' ? ' has-error' : '' ?>" data-paste-field="city">
|
||||
<span>Ort</span>
|
||||
<input type="text" name="city" value="<?= e($values['city']) ?>" autocomplete="address-level2" placeholder="z. B. 41569 Rommerskirchen">
|
||||
<?php if ($fieldError('city')): ?><em class="field-error"><?= e($fieldError('city')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('mobile') !== '' ? ' has-error' : '' ?>" data-paste-field="mobile">
|
||||
<span>Telefon</span>
|
||||
<input type="tel" name="mobile" value="<?= e($values['mobile']) ?>" autocomplete="tel">
|
||||
<?php if ($fieldError('mobile')): ?><em class="field-error"><?= e($fieldError('mobile')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('email') !== '' ? ' has-error' : '' ?>" data-paste-field="email">
|
||||
<span>Mail</span>
|
||||
<input type="email" name="email" value="<?= e($values['email']) ?>" autocomplete="email">
|
||||
<?php if ($fieldError('email')): ?><em class="field-error"><?= e($fieldError('email')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('rent') !== '' ? ' has-error' : '' ?>" data-paste-field="rent">
|
||||
<span>Miete</span>
|
||||
<span class="money-input">
|
||||
<input type="text" name="rent" value="<?= e($values['rent']) ?>" inputmode="decimal" placeholder="0,00" data-money="rent">
|
||||
<span>€</span>
|
||||
</span>
|
||||
<?php if ($fieldError('rent')): ?><em class="field-error"><?= e($fieldError('rent')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $fieldError('delivery') !== '' ? ' has-error' : '' ?>" data-paste-field="delivery">
|
||||
<span>Lieferkosten</span>
|
||||
<span class="money-input">
|
||||
<input type="text" name="delivery" value="<?= e($values['delivery']) ?>" inputmode="decimal" placeholder="0,00" data-money="delivery">
|
||||
<span>€</span>
|
||||
</span>
|
||||
<?php if ($fieldError('delivery')): ?><em class="field-error"><?= e($fieldError('delivery')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<div class="field" data-paste-field="__computed__">
|
||||
<span>Gesamt</span>
|
||||
<output class="due-output" data-total-output><?= e(fmt_money(parse_money((string) $values['rent']) + parse_money((string) $values['delivery']))) ?></output>
|
||||
<em class="muted small">Wird aus Miete + Lieferkosten berechnet; ein mitkopierter Wert wird ignoriert.</em>
|
||||
</div>
|
||||
|
||||
<label class="field<?= $fieldError('deposit') !== '' ? ' has-error' : '' ?>" data-paste-field="deposit">
|
||||
<span>Anzahlung</span>
|
||||
<span class="money-input">
|
||||
<input type="text" name="deposit" value="<?= e($values['deposit']) ?>" inputmode="decimal" placeholder="0,00" data-money="deposit">
|
||||
|
|
@ -131,71 +196,33 @@ $backUrl = $isEdit ? '/bookings/' . (int) $booking['id'] : '/calendar';
|
|||
</span>
|
||||
<?php if ($fieldError('deposit')): ?><em class="field-error"><?= e($fieldError('deposit')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field<?= $fieldError('total') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Gesamtbetrag</span>
|
||||
<span class="money-input">
|
||||
<input type="text" name="total" value="<?= e($values['total']) ?>" inputmode="decimal" placeholder="0,00" data-money="total">
|
||||
<span>€</span>
|
||||
</span>
|
||||
<?php if ($fieldError('total')): ?><em class="field-error"><?= e($fieldError('total')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<div class="field<?= $fieldError('invoice_no') !== '' ? ' has-error' : '' ?>" data-paste-field="invoice_no">
|
||||
<span>Rechnung</span>
|
||||
<div class="field-with-aside">
|
||||
<input type="text" name="invoice_no" value="<?= e($values['invoice_no']) ?>" maxlength="40" placeholder="z. B. RE2026054" data-invoice-no>
|
||||
<span class="segmented-radio segmented-radio--compact">
|
||||
<label><input type="radio" name="invoice" value="0"<?= (int) $values['invoice'] === 0 ? ' checked' : '' ?>><span>NEIN</span></label>
|
||||
<label><input type="radio" name="invoice" value="1"<?= (int) $values['invoice'] === 1 ? ' checked' : '' ?>><span>JA</span></label>
|
||||
</span>
|
||||
</div>
|
||||
<?php if ($fieldError('invoice_no')): ?><em class="field-error"><?= e($fieldError('invoice_no')) ?></em><?php endif; ?>
|
||||
<em class="muted small">Nummer eintragen setzt „Rechnung: JA" automatisch. „Nein" bleibt ohne Nummer.</em>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<span>Noch zu zahlen</span>
|
||||
<output class="due-output" data-due><?= e(fmt_money(due_cents(parse_money((string) $values['total']), parse_money((string) $values['deposit'])))) ?></output>
|
||||
<output class="due-output" data-due><?= e(fmt_money(due_cents(parse_money((string) $values['rent']) + parse_money((string) $values['delivery']), parse_money((string) $values['deposit'])))) ?></output>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<span>Rechnung</span>
|
||||
<div class="segmented-radio">
|
||||
<label><input type="radio" name="invoice" value="0"<?= (int) $values['invoice'] === 0 ? ' checked' : '' ?>><span>NEIN</span></label>
|
||||
<label><input type="radio" name="invoice" value="1"<?= (int) $values['invoice'] === 1 ? ' checked' : '' ?>><span>JA</span></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Art</span>
|
||||
<div class="segmented-radio">
|
||||
<label><input type="radio" name="kind" value="pickup"<?= $values['kind'] === 'pickup' ? ' checked' : '' ?>><span>Abholer</span></label>
|
||||
<label><input type="radio" name="kind" value="delivery"<?= $values['kind'] === 'delivery' ? ' checked' : '' ?>><span>Lieferung</span></label>
|
||||
</div>
|
||||
<div class="conflict-hint" data-conflict hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card__head">
|
||||
<h2>Kundendaten</h2>
|
||||
<p>
|
||||
Erscheint in genau dieser Reihenfolge im kopierbaren Buchungstext.
|
||||
Kunden bitte auf die <a href="<?= e(url('/datenschutz')) ?>">Datenschutzhinweise</a> hinweisen.
|
||||
</p>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<label class="field field--wide<?= $fieldError('customer_name') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Name</span>
|
||||
<input type="text" name="customer_name" value="<?= e($values['customer_name']) ?>" autocomplete="name" required data-customer-name>
|
||||
<?php if ($fieldError('customer_name')): ?><em class="field-error"><?= e($fieldError('customer_name')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field field--wide<?= $fieldError('street') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Straße</span>
|
||||
<input type="text" name="street" value="<?= e($values['street']) ?>" autocomplete="street-address">
|
||||
<?php if ($fieldError('street')): ?><em class="field-error"><?= e($fieldError('street')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field<?= $fieldError('city') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Ort</span>
|
||||
<input type="text" name="city" value="<?= e($values['city']) ?>" autocomplete="address-level2" placeholder="z. B. 41569 Rommerskirchen">
|
||||
<?php if ($fieldError('city')): ?><em class="field-error"><?= e($fieldError('city')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field<?= $fieldError('mobile') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Handy</span>
|
||||
<input type="tel" name="mobile" value="<?= e($values['mobile']) ?>" autocomplete="tel">
|
||||
<?php if ($fieldError('mobile')): ?><em class="field-error"><?= e($fieldError('mobile')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
<label class="field field--wide<?= $fieldError('email') !== '' ? ' has-error' : '' ?>">
|
||||
<span>E-Mail</span>
|
||||
<input type="email" name="email" value="<?= e($values['email']) ?>" autocomplete="email">
|
||||
<?php if ($fieldError('email')): ?><em class="field-error"><?= e($fieldError('email')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
</div>
|
||||
<p class="muted small">
|
||||
Es gilt: Gesamt = Miete + Lieferkosten, „Noch zu zahlen" = Gesamt − Anzahlung.
|
||||
Kunden bitte auf die <a href="<?= e(url('/datenschutz')) ?>">Datenschutzhinweise</a> hinweisen.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
|
|
@ -204,11 +231,13 @@ $backUrl = $isEdit ? '/bookings/' . (int) $booking['id'] : '/calendar';
|
|||
<h2>Übersicht</h2>
|
||||
<dl class="summary-list">
|
||||
<div><dt>Kühlanhänger</dt><dd><span class="trailer-dot" style="--trailer: <?= e($selectedTrailer['color_hex'] ?? '#196abc') ?>"></span> <span data-summary-trailer><?= e($selectedTrailer['label'] ?? '–') ?></span></dd></div>
|
||||
<div><dt>Zeitraum</dt><dd data-summary-dates><?= e(fmt_date_range($values['start_date'], $values['end_date'])) ?></dd></div>
|
||||
<div><dt>Zeitraum</dt><dd data-summary-dates><?= e(fmt_date_with_time($values['start_date'], $values['start_time']) . ' – ' . fmt_date_with_time($values['end_date'], $values['end_time'])) ?></dd></div>
|
||||
<div><dt>Mitarbeiter</dt><dd><span data-summary-employee><?= e($selectedEmployee['name'] ?? '–') ?></span></dd></div>
|
||||
<div><dt>Gesamtbetrag</dt><dd data-summary-total><?= e(fmt_money(parse_money((string) $values['total']))) ?></dd></div>
|
||||
<div><dt>Miete</dt><dd data-summary-rent><?= e(fmt_money(parse_money((string) $values['rent']))) ?></dd></div>
|
||||
<div><dt>Lieferkosten</dt><dd data-summary-delivery><?= e(fmt_money(parse_money((string) $values['delivery']))) ?></dd></div>
|
||||
<div><dt>Gesamtbetrag</dt><dd data-summary-total><?= e(fmt_money(parse_money((string) $values['rent']) + parse_money((string) $values['delivery']))) ?></dd></div>
|
||||
<div><dt>Anzahlung</dt><dd data-summary-deposit><?= e(fmt_money(parse_money((string) $values['deposit']))) ?></dd></div>
|
||||
<div class="is-strong"><dt>Noch zu zahlen</dt><dd data-summary-due><?= e(fmt_money(due_cents(parse_money((string) $values['total']), parse_money((string) $values['deposit'])))) ?></dd></div>
|
||||
<div class="is-strong"><dt>Noch zu zahlen</dt><dd data-summary-due><?= e(fmt_money(due_cents(parse_money((string) $values['rent']) + parse_money((string) $values['delivery']), parse_money((string) $values['deposit'])))) ?></dd></div>
|
||||
</dl>
|
||||
<div class="form-actions">
|
||||
<button class="btn primary btn--block" type="submit">
|
||||
|
|
|
|||
|
|
@ -21,11 +21,12 @@ foreach ($reminders as $reminder) {
|
|||
<div class="panel-head__main">
|
||||
<div class="panel-head__trailer">
|
||||
<span class="trailer-dot" style="--trailer: <?= e($booking['trailer_color']) ?>"></span>
|
||||
<?= e($booking['trailer_label']) ?> · <?= e($booking['trailer_color_name']) ?>
|
||||
<?= e($booking['trailer_label']) ?>
|
||||
</div>
|
||||
<h2><?= e($booking['customer_name']) ?></h2>
|
||||
<p>
|
||||
<?= e(fmt_date_range($booking['start_date'], $booking['end_date'])) ?>
|
||||
<?= e(fmt_date_with_time($booking['start_date'], $booking['start_time'] ?? null)) ?>
|
||||
– <?= e(fmt_date_with_time($booking['end_date'], $booking['end_time'] ?? null)) ?>
|
||||
· <?= e($booking['employee_name']) ?>
|
||||
<span class="pill <?= $cancelled ? 'pill--grey' : 'pill--green' ?>"><?= $cancelled ? 'storniert' : 'aktiv' ?></span>
|
||||
</p>
|
||||
|
|
@ -55,12 +56,14 @@ foreach ($reminders as $reminder) {
|
|||
|
||||
<section class="panel-meta">
|
||||
<dl class="meta-list meta-list--compact">
|
||||
<div><dt>Anhänger</dt><dd><?= e($booking['trailer_label'] . ' · ' . $booking['trailer_color_name']) ?></dd></div>
|
||||
<div><dt>Anhänger</dt><dd><?= e($booking['trailer_label']) ?></dd></div>
|
||||
<div><dt>Mitarbeiter</dt><dd><?= e($booking['employee_name']) ?></dd></div>
|
||||
<div><dt>Art</dt><dd><?= e(booking_kind_label((string) $booking['kind'])) ?></dd></div>
|
||||
<div><dt>Rechnung</dt><dd><?= e(booking_invoice_label($booking['invoice'])) ?></dd></div>
|
||||
<div><dt>Anzahlung</dt><dd><?= e(fmt_money((int) $booking['deposit_cents'])) ?></dd></div>
|
||||
<div><dt>Rechnung</dt><dd><?= e(booking_invoice_display($booking)) ?></dd></div>
|
||||
<div><dt>Miete</dt><dd><?= e(fmt_money((int) $booking['rent_cents'])) ?></dd></div>
|
||||
<div><dt>Lieferkosten</dt><dd><?= e(fmt_money((int) $booking['delivery_cents'])) ?></dd></div>
|
||||
<div><dt>Gesamt</dt><dd><?= e(fmt_money((int) $booking['total_cents'])) ?></dd></div>
|
||||
<div><dt>Anzahlung</dt><dd><?= e(fmt_money((int) $booking['deposit_cents'])) ?></dd></div>
|
||||
<div class="is-strong"><dt>Noch zu zahlen</dt><dd><?= e(fmt_money($due)) ?></dd></div>
|
||||
</dl>
|
||||
<?php if ($openReminder): ?>
|
||||
|
|
|
|||
|
|
@ -106,7 +106,7 @@ $minWidth = match ($view) {
|
|||
<span class="trailer-dot" style="--trailer: <?= e($trailer['color_hex']) ?>"></span>
|
||||
<span class="cal-label__text">
|
||||
<strong><?= e($trailer['label']) ?></strong>
|
||||
<small><?= e($trailer['color_name']) ?><?= (int) $trailer['active'] === 1 ? '' : ' · inaktiv' ?></small>
|
||||
<?php if ((int) $trailer['active'] !== 1): ?><small>inaktiv</small><?php endif; ?>
|
||||
</span>
|
||||
<a class="cal-label__add" href="<?= e(url('/bookings/new?trailer=' . (int) $trailer['id'] . '&start=' . $date)) ?>" aria-label="Neue Buchung für <?= e($trailer['label']) ?>">+</a>
|
||||
</div>
|
||||
|
|
@ -125,10 +125,11 @@ $minWidth = match ($view) {
|
|||
$booking = $bar['booking'];
|
||||
$geo = $bar['geo'];
|
||||
$cancelled = $booking['status'] === 'cancelled';
|
||||
$showMeta = $view === 'day' || ($view === 'week' && $geo['span'] >= 2);
|
||||
$showMeta = $view === 'day' || $geo['span'] >= 2;
|
||||
$label = $view === 'month' ? truncate((string) $booking['customer_name'], 18) : (string) $booking['customer_name'];
|
||||
$aria = $booking['customer_name'] . ', ' . $booking['trailer_label'] . ', '
|
||||
. fmt_date($booking['start_date']) . ' bis ' . fmt_date($booking['end_date'])
|
||||
. fmt_date_with_time($booking['start_date'], $booking['start_time'] ?? null) . ' bis '
|
||||
. fmt_date_with_time($booking['end_date'], $booking['end_time'] ?? null)
|
||||
. ', ' . $booking['employee_name'] . ($cancelled ? ', storniert' : '');
|
||||
?>
|
||||
<a class="cal-bar<?= $cancelled ? ' is-cancelled' : '' ?><?= $geo['cut_start'] ? ' is-cut-start' : '' ?><?= $geo['cut_end'] ? ' is-cut-end' : '' ?><?= $geo['span'] <= 1 ? ' is-tiny' : '' ?>"
|
||||
|
|
@ -141,10 +142,10 @@ $minWidth = match ($view) {
|
|||
data-days="<?= days_between($booking['start_date'], $booking['end_date']) + 1 ?>"
|
||||
style="--left: <?= number_format($geo['left'], 5, '.', '') ?>%; --width: <?= number_format($geo['width'], 5, '.', '') ?>%; --top: <?= number_format($geo['top'], 5, '.', '') ?>%; --height: <?= number_format($geo['height'], 5, '.', '') ?>%; --bar: <?= e($booking['trailer_color']) ?>; --bar-text: <?= e(contrast_color($booking['trailer_color'])) ?>;"
|
||||
aria-label="<?= e($aria) ?>"
|
||||
title="<?= e($booking['customer_name'] . ' · ' . fmt_date_range($booking['start_date'], $booking['end_date']) . ' · ' . $booking['employee_name'] . ($cancelled ? ' · storniert' : '')) ?>">
|
||||
title="<?= e($booking['customer_name'] . ' · ' . fmt_date_with_time($booking['start_date'], $booking['start_time'] ?? null) . ' – ' . fmt_date_with_time($booking['end_date'], $booking['end_time'] ?? null) . ' · ' . $booking['employee_name'] . ($cancelled ? ' · storniert' : '')) ?>">
|
||||
<span class="cal-bar__name"><?= e($label) ?></span>
|
||||
<?php if ($showMeta): ?>
|
||||
<span class="cal-bar__meta"><?= e($view === 'day' ? fmt_date_range($booking['start_date'], $booking['end_date']) : $booking['employee_name']) ?><?= $view === 'day' ? ' · ' . e($booking['employee_name']) : '' ?></span>
|
||||
<span class="cal-bar__meta"><?= e($view === 'day' ? fmt_date_with_time($booking['start_date'], $booking['start_time'] ?? null) . ' – ' . fmt_date_with_time($booking['end_date'], $booking['end_time'] ?? null) : $booking['employee_name']) ?><?= $view === 'day' ? ' · ' . e($booking['employee_name']) : '' ?></span>
|
||||
<?php endif; ?>
|
||||
<?php if ($view === 'day'): ?>
|
||||
<span class="cal-bar__meta cal-bar__meta--soft"><?= e(booking_kind_label((string) $booking['kind'])) ?> · <?= e(fmt_money((int) $booking['total_cents'])) ?></span>
|
||||
|
|
|
|||
|
|
@ -7,13 +7,31 @@
|
|||
/** @var int $openReminderCount */
|
||||
/** @var int $handoverCount */
|
||||
/** @var int $employeeScope */
|
||||
$rentedToday = 0;
|
||||
$rentedTrailers = 0;
|
||||
$rentedChests = 0;
|
||||
$freeTrailers = 0;
|
||||
$freeChests = 0;
|
||||
$totalTrailers = 0;
|
||||
$totalChests = 0;
|
||||
foreach ($roadmap as $row) {
|
||||
$isChest = trailer_is_chest($row['trailer']);
|
||||
if ($isChest) {
|
||||
$totalChests++;
|
||||
} else {
|
||||
$totalTrailers++;
|
||||
}
|
||||
if ($row['bookings']) {
|
||||
$rentedToday++;
|
||||
if ($isChest) {
|
||||
$rentedChests++;
|
||||
} else {
|
||||
$rentedTrailers++;
|
||||
}
|
||||
} elseif ($isChest) {
|
||||
$freeChests++;
|
||||
} else {
|
||||
$freeTrailers++;
|
||||
}
|
||||
}
|
||||
$freeToday = count($trailers) - $rentedToday;
|
||||
$isEmployeeView = $employeeScope > 0;
|
||||
?>
|
||||
<div class="page-head">
|
||||
|
|
@ -23,8 +41,8 @@ $isEmployeeView = $employeeScope > 0;
|
|||
<p class="page-head__lede">Was heute ansteht – und wer sich um welche Übergabe kümmert.</p>
|
||||
</div>
|
||||
<div class="page-head__actions">
|
||||
<a class="btn" href="<?= e(url('/calendar')) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-calendar"/></svg> Kalender
|
||||
<a class="btn" href="<?= e(url('/availability')) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-search"/></svg> Verfügbarkeit
|
||||
</a>
|
||||
<a class="btn primary" href="<?= e(url('/bookings/new')) ?>">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-plus"/></svg> Neue Buchung
|
||||
|
|
@ -35,11 +53,19 @@ $isEmployeeView = $employeeScope > 0;
|
|||
<section class="kpi-grid" aria-label="Kennzahlen">
|
||||
<article class="kpi">
|
||||
<span class="kpi__icon kpi__icon--blue"><svg class="ico" aria-hidden="true"><use href="#i-truck"/></svg></span>
|
||||
<div><strong><?= $rentedToday ?> von <?= count($trailers) ?></strong><span>Heute vermietet</span></div>
|
||||
<div><strong><?= $rentedTrailers ?> von <?= $totalTrailers ?></strong><span>Vermietete Anhänger</span></div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="kpi__icon kpi__icon--blue"><svg class="ico" aria-hidden="true"><use href="#i-snow"/></svg></span>
|
||||
<div><strong><?= $rentedChests ?> von <?= $totalChests ?></strong><span>Vermietete Truhen</span></div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="kpi__icon kpi__icon--green"><svg class="ico" aria-hidden="true"><use href="#i-check"/></svg></span>
|
||||
<div><strong><?= $freeToday ?></strong><span>Heute frei</span></div>
|
||||
<div><strong><?= $freeTrailers ?> von <?= $totalTrailers ?></strong><span>Freie Anhänger</span></div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="kpi__icon kpi__icon--green"><svg class="ico" aria-hidden="true"><use href="#i-snow"/></svg></span>
|
||||
<div><strong><?= $freeChests ?> von <?= $totalChests ?></strong><span>Freie Truhen</span></div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="kpi__icon kpi__icon--amber"><svg class="ico" aria-hidden="true"><use href="#i-clock"/></svg></span>
|
||||
|
|
@ -79,7 +105,6 @@ $isEmployeeView = $employeeScope > 0;
|
|||
<span class="trailer-dot"></span>
|
||||
<div class="trailer-card__name">
|
||||
<strong><?= e($trailer['label']) ?></strong>
|
||||
<small><?= e($trailer['color_name']) ?></small>
|
||||
</div>
|
||||
<span class="pill <?= $bookings ? 'pill--red' : 'pill--green' ?>"><?= $bookings ? 'vermietet' : 'frei' ?></span>
|
||||
</div>
|
||||
|
|
|
|||
129
views/invite.php
Normal file
129
views/invite.php
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
<?php
|
||||
/** @var string $state form|invalid */
|
||||
/** @var string $error */
|
||||
/** @var string $firstName */
|
||||
/** @var string $lastName */
|
||||
/** @var string $email */
|
||||
$isForm = $state === 'form';
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#196abc">
|
||||
<meta name="color-scheme" content="light">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Zugang einrichten · Drink it cold</title>
|
||||
<link rel="icon" type="image/svg+xml" href="<?= e(asset('favicon.svg')) ?>">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="<?= e(asset('icons/icon-32.png')) ?>">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="<?= e(asset('icons/apple-touch-icon-180.png')) ?>">
|
||||
<link rel="preload" as="font" type="font/woff2" href="<?= e(asset('fonts/manrope-latin.woff2')) ?>" crossorigin>
|
||||
<link rel="stylesheet" href="<?= e(asset('app.css')) ?>">
|
||||
<script src="<?= e(asset('app.js')) ?>" defer></script>
|
||||
</head>
|
||||
<body class="auth-page">
|
||||
<div class="auth-shell">
|
||||
<section class="auth-visual" aria-label="Drink it cold – Kühlanhänger-Vermietung">
|
||||
<img class="auth-visual__bg"
|
||||
src="<?= e(asset('img/hero-1280.webp')) ?>"
|
||||
srcset="<?= e(asset('img/hero-800.webp')) ?> 800w, <?= e(asset('img/hero-1280.webp')) ?> 1280w"
|
||||
sizes="50vw" alt="Kühlanhänger von Drink it cold">
|
||||
<div class="auth-visual__shade"></div>
|
||||
<div class="auth-visual__content">
|
||||
<div class="auth-brand">
|
||||
<img src="<?= e(asset('logo-mark.svg')) ?>" alt="" width="56" height="40">
|
||||
<span>
|
||||
<strong>Drink it cold</strong>
|
||||
<small>Kühlanhänger-Vermietung</small>
|
||||
</span>
|
||||
</div>
|
||||
<div class="auth-visual__claim">
|
||||
<p class="eyebrow">Terminplanung</p>
|
||||
<h2>Alle Anhänger.<br>Ein Blick.</h2>
|
||||
<p>Buchungen, Übergaben und Erinnerungen zentral – damit niemand mehr im Kalender blättern muss.</p>
|
||||
</div>
|
||||
<p class="auth-visual__foot">Zum Kühlen. Für Feste. Seit jeher.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="auth-panel">
|
||||
<div class="auth-card">
|
||||
<a class="auth-card__mobilebrand" href="<?= e(url('/')) ?>" aria-label="Drink it cold">
|
||||
<img src="<?= e(asset('logo-mark.svg')) ?>" alt="" width="44" height="32">
|
||||
<span>Drink it cold</span>
|
||||
</a>
|
||||
|
||||
<?php if ($isForm): ?>
|
||||
<p class="eyebrow">Einladung</p>
|
||||
<h1>Zugang einrichten</h1>
|
||||
<p class="auth-card__lede">
|
||||
Hallo <?= e($firstName) ?>, bitte vergeben Sie jetzt ein eigenes Passwort.
|
||||
Angemeldet wird anschließend mit <strong><?= e($firstName . ' ' . $lastName) ?></strong><?php if ($email !== ''): ?>
|
||||
(<?= e($email) ?>)<?php endif; ?>.
|
||||
</p>
|
||||
|
||||
<?php if ($error !== ''): ?>
|
||||
<div class="flash flash--error" role="alert">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
|
||||
<span><?= e($error) ?></span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" action="<?= e(url(current_path())) ?>" class="auth-form">
|
||||
<?= csrf_field() ?>
|
||||
<label class="field">
|
||||
<span>Neues Passwort</span>
|
||||
<input type="password" name="password" autocomplete="new-password" minlength="8" required autofocus>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Neues Passwort wiederholen</span>
|
||||
<input type="password" name="repeat_password" autocomplete="new-password" minlength="8" required>
|
||||
</label>
|
||||
<button class="btn primary btn--block" type="submit">Passwort speichern</button>
|
||||
</form>
|
||||
|
||||
<p class="auth-card__hint">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-snow"/></svg>
|
||||
Mindestens 8 Zeichen. Der Link ist sieben Tage gültig und nur einmal verwendbar.
|
||||
</p>
|
||||
<?php else: ?>
|
||||
<p class="eyebrow">Einladung</p>
|
||||
<h1>Link nicht mehr gültig</h1>
|
||||
<p class="auth-card__lede">
|
||||
Dieser Einladungslink ist abgelaufen oder wurde bereits verwendet.
|
||||
Bitte wenden Sie sich an den Administrator, damit er einen neuen Link erzeugt.
|
||||
</p>
|
||||
<p class="auth-card__hint">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-snow"/></svg>
|
||||
Bereits ein Passwort gesetzt? Dann geht es hier zur Anmeldung.
|
||||
</p>
|
||||
<p><a class="btn primary btn--block" href="<?= e(url('/login')) ?>">Zur Anmeldung</a></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<p class="auth-card__legal">
|
||||
<a href="<?= e(url('/impressum')) ?>">Impressum</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<a href="<?= e(url('/datenschutz')) ?>">Datenschutz</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>Nur technisch notwendige Cookies, kein Tracking.</span>
|
||||
</p>
|
||||
</div>
|
||||
<footer class="auth-foot">
|
||||
<span>© <?= date('Y') ?> Drink it cold · Neuss</span>
|
||||
<nav aria-label="Rechtliches">
|
||||
<a href="<?= e(url('/impressum')) ?>">Impressum</a>
|
||||
<a href="<?= e(url('/datenschutz')) ?>">Datenschutz</a>
|
||||
</nav>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<svg width="0" height="0" aria-hidden="true" style="position:absolute">
|
||||
<defs>
|
||||
<symbol id="i-alert" viewBox="0 0 24 24"><path d="M12 3.5 2.5 20.5h19z"/><path d="M12 9.5v5M12 17.6v.4"/></symbol>
|
||||
<symbol id="i-snow" viewBox="0 0 24 24"><path d="M12 2v20M4.5 6.8l15 10.4M19.5 6.8 4.5 17.2M12 6.4 9.6 4M12 6.4 14.4 4M12 17.6 9.6 20M12 17.6l2.4 2.4"/></symbol>
|
||||
</defs>
|
||||
</svg>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -132,6 +132,11 @@ $rememberDays = (int) $info['remember_days'];
|
|||
einen Selector und den Hash eines Tokens mit Ablaufdatum; das eigentliche Token liegt nur im Cookie des
|
||||
Geräts.
|
||||
</p>
|
||||
<p>
|
||||
Legt der Administrator ein Konto per Einladung an, speichern wir sieben Tage lang den Hash eines
|
||||
Einladungs-Tokens sowie die Kennung des einladenden Kontos. Der Link selbst liegt nur in der E-Mail
|
||||
beziehungsweise im Einmal-Hinweis des Formulars. Nach dem Einlösen oder Ablauf wird der Eintrag gelöscht.
|
||||
</p>
|
||||
<p>
|
||||
Zur Abwehr von Angriffsversuchen speichern wir bei fehlgeschlagenen Anmeldungen die IP-Adresse, einen
|
||||
Schlüssel aus dem eingegebenen Namen und den Zeitpunkt. Diese Einträge werden spätestens nach
|
||||
|
|
@ -285,6 +290,7 @@ $rememberDays = (int) $info['remember_days'];
|
|||
<li><strong>Stornierte Buchungen:</strong> Löschung, sobald kein Aufbewahrungsgrund mehr besteht.</li>
|
||||
<li><strong>Mitarbeiterkonten:</strong> für die Dauer des Beschäftigungsverhältnisses; danach Löschung, sobald keine gesetzlichen Aufbewahrungspflichten entgegenstehen.</li>
|
||||
<li><strong>Login-Fehlversuche:</strong> 24 Stunden.</li>
|
||||
<li><strong>Einladungen:</strong> 7 Tage oder bis zum Einlösen.</li>
|
||||
<li><strong>Remember-Tokens:</strong> <?= $rememberDays ?> Tage oder bis zur Abmeldung.</li>
|
||||
<li><strong>Push-Abos:</strong> bis zum Widerruf oder zur Löschung des Kontos; abgelaufene Abos werden entfernt.</li>
|
||||
<li><strong>Versandprotokolle:</strong> 1 Jahr.</li>
|
||||
|
|
|
|||
|
|
@ -33,15 +33,14 @@ foreach ($rows as $row) {
|
|||
<h1>Was als Nächstes ansteht</h1>
|
||||
<p class="page-head__lede">Automatisch aus Mietbeginn und Mietende berechnet – für den zuständigen Mitarbeiter.</p>
|
||||
</div>
|
||||
<div class="page-head__actions">
|
||||
<?php if ($isAdmin && ($mailEnabled || $pushEnabled)): ?>
|
||||
<?php if ($isAdmin && ($mailEnabled || $pushEnabled)): ?>
|
||||
<div class="page-head__actions">
|
||||
<form method="post" action="<?= e(url('/admin/reminders/send')) ?>" data-confirm="Fällige Erinnerungen jetzt per Push und E-Mail senden?">
|
||||
<?= csrf_field() ?>
|
||||
<button class="btn" type="submit"><svg class="ico" aria-hidden="true"><use href="#i-bell"/></svg> Erinnerungen jetzt senden</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
<a class="btn primary" href="<?= e(url('/calendar')) ?>"><svg class="ico" aria-hidden="true"><use href="#i-calendar"/></svg> Kalender</a>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="reminder-toolbar">
|
||||
|
|
|
|||
|
|
@ -324,7 +324,7 @@ a .ico, button .ico { pointer-events: none; }
|
|||
.list-summary { font-size: .84rem; color: var(--muted); margin: -4px 0 16px; }
|
||||
|
||||
/* --------------------------------------------------------------- KPI + Dashboard */
|
||||
.kpi-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 18px; }
|
||||
.kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; margin-bottom: 18px; }
|
||||
.kpi {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
background: #fff; border: 1px solid var(--line); border-radius: var(--radius);
|
||||
|
|
@ -342,8 +342,26 @@ a .ico, button .ico { pointer-events: none; }
|
|||
.kpi strong { display: block; font-family: var(--font-display); font-size: 1.3rem; color: var(--ink); line-height: 1.1; }
|
||||
.kpi span { font-size: .78rem; color: var(--muted); }
|
||||
|
||||
.dash-grid { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(300px, .85fr); gap: 18px; align-items: start; }
|
||||
.dash-main, .dash-side { display: grid; gap: 18px; min-width: 0; }
|
||||
/* ---------------------------------------------------------- Verfügbarkeit */
|
||||
.availability-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
|
||||
.availability-group h3 {
|
||||
display: flex; align-items: baseline; justify-content: space-between; gap: 10px;
|
||||
margin: 0 0 8px; font-size: .95rem;
|
||||
}
|
||||
.availability-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
|
||||
.availability-row {
|
||||
display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
|
||||
padding: 9px 11px; border: 1px solid var(--line); border-radius: 10px; background: #fff;
|
||||
}
|
||||
.availability-row.is-free { border-color: #bfe3bf; background: #f8fdf8; }
|
||||
.availability-row.is-busy { background: #fbfcfd; }
|
||||
.availability-row__name { flex: 1 1 auto; min-width: 0; }
|
||||
.availability-row__hint { flex: 1 1 100%; }
|
||||
@media (max-width: 760px) {
|
||||
.availability-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
.dash-grid { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(300px, .85fr); gap: 18px; align-items: start; }.dash-main, .dash-side { display: grid; gap: 18px; min-width: 0; }
|
||||
.trailer-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.trailer-card {
|
||||
border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 13px;
|
||||
|
|
@ -540,7 +558,11 @@ a .ico, button .ico { pointer-events: none; }
|
|||
.form-main { display: grid; gap: 16px; min-width: 0; }
|
||||
.form-side { display: grid; gap: 16px; position: sticky; top: calc(var(--topbar-h) + 16px); }
|
||||
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 16px; }
|
||||
.form-grid--single { grid-template-columns: minmax(0, 1fr); gap: 12px; }
|
||||
.field-with-aside { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; }
|
||||
.segmented-radio--compact span { min-width: 52px; padding: 6px 9px; font-size: .76rem; }
|
||||
.field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
|
||||
.field-pair { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); gap: 8px; }
|
||||
.field--wide { grid-column: 1 / -1; }
|
||||
.field > span, .field > label > span { font-size: .8rem; font-weight: 600; color: var(--ink-2); }
|
||||
.field input, .field select, .field textarea {
|
||||
|
|
@ -597,6 +619,13 @@ a .ico, button .ico { pointer-events: none; }
|
|||
.detail-meta { margin: 0; }
|
||||
.card--copy { overflow: hidden; }
|
||||
.copy-source { position: absolute; left: -9999px; width: 1px; height: 1px; opacity: 0; }
|
||||
.copy-source--visible {
|
||||
position: static; width: 100%; height: auto; min-height: 54px; opacity: 1;
|
||||
padding: 10px 12px; resize: vertical;
|
||||
border: 1px solid var(--line-soft); border-radius: 9px; background: var(--ice-50);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .8rem; color: var(--ink-2);
|
||||
word-break: break-all;
|
||||
}
|
||||
.copy-list { margin: 0; display: grid; grid-template-columns: 1fr; gap: 0; border-top: 1px solid var(--line-soft); }
|
||||
.copy-list__row { display: grid; grid-template-columns: minmax(120px, 190px) 1fr; gap: 14px; padding: 9px 2px; border-bottom: 1px solid var(--line-soft); }
|
||||
.copy-list__row:last-child { border-bottom: 0; }
|
||||
|
|
@ -732,6 +761,7 @@ a .ico, button .ico { pointer-events: none; }
|
|||
.table-person > span:last-child { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.table-person strong { color: var(--ink); font-size: .85rem; }
|
||||
.table-person small { color: var(--muted); font-size: .72rem; }
|
||||
.table-person .invite-open { color: var(--brand-700); font-weight: 600; }
|
||||
.admin-split { display: grid; grid-template-columns: 380px minmax(0, 1fr); gap: 16px; align-items: start; }
|
||||
.trailer-admin { display: grid; gap: 0; border-top: 1px solid var(--line-soft); }
|
||||
.trailer-admin__head, .trailer-admin__row {
|
||||
|
|
|
|||
|
|
@ -126,7 +126,7 @@
|
|||
if (!source) return;
|
||||
try {
|
||||
await copyToClipboard(source.value);
|
||||
toast('Buchungstext kopiert.');
|
||||
toast(source.dataset.copyToast || 'Buchungstext kopiert.');
|
||||
const original = button.innerHTML;
|
||||
button.innerHTML = '<svg class="ico" aria-hidden="true"><use href="#i-check"/></svg> Kopiert';
|
||||
window.setTimeout(() => { button.innerHTML = original; }, 1800);
|
||||
|
|
@ -194,7 +194,11 @@
|
|||
const startInput = bookingForm.querySelector('[data-date-start]');
|
||||
const endInput = bookingForm.querySelector('[data-date-end]');
|
||||
const depositInput = bookingForm.querySelector('[data-money="deposit"]');
|
||||
const totalInput = bookingForm.querySelector('[data-money="total"]');
|
||||
const rentInput = bookingForm.querySelector('[data-money="rent"]');
|
||||
const deliveryInput = bookingForm.querySelector('[data-money="delivery"]');
|
||||
const totalOutput = bookingForm.querySelector('[data-total-output]');
|
||||
const startTimeInput = bookingForm.querySelector('[data-time-start]');
|
||||
const endTimeInput = bookingForm.querySelector('[data-time-end]');
|
||||
const dueOutput = bookingForm.querySelector('[data-due]');
|
||||
const conflictBox = bookingForm.querySelector('[data-conflict]');
|
||||
const availabilityUrl = bookingForm.dataset.availabilityUrl;
|
||||
|
|
@ -218,9 +222,13 @@
|
|||
const [y, m, d] = iso.split('-');
|
||||
return `${d}.${m}.${y}`;
|
||||
};
|
||||
const formatRange = (a, b) => {
|
||||
const formatDateTime = (iso, time) => {
|
||||
const date = formatDate(iso);
|
||||
return time ? `${date} ${time}` : date;
|
||||
};
|
||||
const formatRange = (a, b, aTime, bTime) => {
|
||||
if (!a || !b) return '–';
|
||||
return a === b ? formatDate(a) : `${formatDate(a)} – ${formatDate(b)}`;
|
||||
return a === b ? formatDateTime(a, aTime) : `${formatDateTime(a, aTime)} – ${formatDateTime(b, bTime)}`;
|
||||
};
|
||||
const contrast = (hex) => {
|
||||
const clean = String(hex || '').replace('#', '');
|
||||
|
|
@ -238,8 +246,7 @@
|
|||
const option = trailerSelect.selectedOptions[0];
|
||||
if (!option) return;
|
||||
const color = option.dataset.color || '#196abc';
|
||||
const name = option.dataset.colorName || '';
|
||||
const label = option.textContent.split('·')[0].trim();
|
||||
const label = option.textContent.trim();
|
||||
const preview = bookingForm.querySelector('[data-trailer-preview]');
|
||||
if (preview) {
|
||||
preview.style.setProperty('--trailer', color);
|
||||
|
|
@ -247,20 +254,27 @@
|
|||
const dot = preview.querySelector('.trailer-dot');
|
||||
if (dot) dot.style.setProperty('--trailer', color);
|
||||
const text = preview.querySelector('[data-trailer-preview-label]');
|
||||
if (text) text.textContent = `${label} · ${name}`;
|
||||
if (text) text.textContent = label;
|
||||
}
|
||||
const summary = bookingForm.querySelector('[data-summary-trailer]');
|
||||
if (summary) summary.textContent = label;
|
||||
};
|
||||
|
||||
const updateTotals = () => {
|
||||
const rent = parseMoney(rentInput?.value);
|
||||
const delivery = parseMoney(deliveryInput?.value);
|
||||
const total = rent + delivery;
|
||||
const deposit = parseMoney(depositInput?.value);
|
||||
const total = parseMoney(totalInput?.value);
|
||||
const due = total - deposit;
|
||||
if (totalOutput) totalOutput.textContent = formatMoney(total);
|
||||
if (dueOutput) dueOutput.textContent = formatMoney(due);
|
||||
const totalSummary = bookingForm.querySelector('[data-summary-total]');
|
||||
const rentSummary = bookingForm.querySelector('[data-summary-rent]');
|
||||
const deliverySummary = bookingForm.querySelector('[data-summary-delivery]');
|
||||
const depositSummary = bookingForm.querySelector('[data-summary-deposit]');
|
||||
const dueSummary = bookingForm.querySelector('[data-summary-due]');
|
||||
if (rentSummary) rentSummary.textContent = formatMoney(rent);
|
||||
if (deliverySummary) deliverySummary.textContent = formatMoney(delivery);
|
||||
if (totalSummary) totalSummary.textContent = formatMoney(total);
|
||||
if (depositSummary) depositSummary.textContent = formatMoney(deposit);
|
||||
if (dueSummary) dueSummary.textContent = formatMoney(due);
|
||||
|
|
@ -268,7 +282,7 @@
|
|||
|
||||
const updateSummary = () => {
|
||||
const dates = bookingForm.querySelector('[data-summary-dates]');
|
||||
if (dates) dates.textContent = formatRange(startInput?.value, endInput?.value);
|
||||
if (dates) dates.textContent = formatRange(startInput?.value, endInput?.value, startTimeInput?.value, endTimeInput?.value);
|
||||
const employee = bookingForm.querySelector('[data-summary-employee]');
|
||||
if (employee && employeeSelect) {
|
||||
employee.textContent = employeeSelect.selectedOptions[0]?.textContent.trim() || '–';
|
||||
|
|
@ -342,7 +356,125 @@
|
|||
});
|
||||
endInput?.addEventListener('change', () => { updateSummary(); checkAvailability(); });
|
||||
depositInput?.addEventListener('input', updateTotals);
|
||||
totalInput?.addEventListener('input', updateTotals);
|
||||
rentInput?.addEventListener('input', updateTotals);
|
||||
deliveryInput?.addEventListener('input', updateTotals);
|
||||
startTimeInput?.addEventListener('input', updateSummary);
|
||||
endTimeInput?.addEventListener('input', updateSummary);
|
||||
|
||||
// Rechnungsnummer gesetzt -> "Rechnung: JA" mitziehen.
|
||||
const invoiceNoInput = bookingForm.querySelector('[data-invoice-no]');
|
||||
const invoiceYes = bookingForm.querySelector('input[name="invoice"][value="1"]');
|
||||
invoiceNoInput?.addEventListener('input', () => {
|
||||
if (invoiceNoInput.value.trim() !== '' && invoiceYes) invoiceYes.checked = true;
|
||||
});
|
||||
|
||||
/* Einfügen aus Excel: Spalte untereinander -> Felder der Reihe nach füllen. */
|
||||
const pasteHost = bookingForm.querySelector('[data-paste-targets]');
|
||||
if (pasteHost) {
|
||||
const pasteRows = Array.from(pasteHost.querySelectorAll('[data-paste-field]')).map((row) => ({
|
||||
row,
|
||||
name: row.dataset.pasteField,
|
||||
control: row.querySelector('select, output, input:not([type="hidden"]):not([type="radio"])'),
|
||||
}));
|
||||
|
||||
const normalizeDate = (value) => {
|
||||
const text = String(value || '').trim();
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(text)) return text;
|
||||
const dotted = /^(\d{1,2})[.\/](\d{1,2})[.\/](\d{2,4})$/.exec(text);
|
||||
if (!dotted) return '';
|
||||
const year = dotted[3].length === 2 ? `20${dotted[3]}` : dotted[3];
|
||||
return `${year}-${dotted[2].padStart(2, '0')}-${dotted[1].padStart(2, '0')}`;
|
||||
};
|
||||
const normalizeTime = (value) => {
|
||||
const match = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(value || '').trim());
|
||||
return match ? `${match[1].padStart(2, '0')}:${match[2]}` : '';
|
||||
};
|
||||
const normalizeMoney = (value) => String(value || '').replace(/€/g, '').trim();
|
||||
const alias = { niklas: 'n. jorns', 'krücken': 'm. krücken', kruecken: 'm. krücken', schmitz: 'm. schmitz' };
|
||||
const chooseOption = (select, value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return false;
|
||||
const options = Array.from(select.options);
|
||||
const hit = options.find((o) => o.value.toLowerCase() === text)
|
||||
|| options.find((o) => o.textContent.trim().toLowerCase() === text)
|
||||
|| options.find((o) => o.textContent.toLowerCase().includes(text))
|
||||
|| options.find((o) => alias[text] && o.textContent.toLowerCase().includes(alias[text]));
|
||||
if (!hit) return false;
|
||||
select.value = hit.value;
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyPaste = (text, startIndex) => {
|
||||
const clean = text.replace(/\r/g, '');
|
||||
const values = /\n/.test(clean.trim()) ? clean.split('\n') : clean.split('\t');
|
||||
while (values.length && values[values.length - 1].trim() === '') values.pop();
|
||||
if (values.length < 2) return 0;
|
||||
|
||||
let index = startIndex;
|
||||
let filled = 0;
|
||||
for (const raw of values) {
|
||||
if (index >= pasteRows.length) break;
|
||||
const field = pasteRows[index];
|
||||
index += 1;
|
||||
const value = raw.trim();
|
||||
if (field.name === '__computed__') continue; // Gesamt wird berechnet
|
||||
|
||||
if (field.name === 'kind') {
|
||||
const lower = value.toLowerCase();
|
||||
const target = lower.includes('liefer') ? 'delivery' : lower.includes('abhol') ? 'pickup' : '';
|
||||
if (target) {
|
||||
const radio = bookingForm.querySelector(`input[name="kind"][value="${target}"]`);
|
||||
if (radio) radio.checked = true;
|
||||
filled += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const control = field.control;
|
||||
if (!control || control.tagName === 'OUTPUT') continue;
|
||||
|
||||
let next = value;
|
||||
if (control.type === 'date') next = normalizeDate(value);
|
||||
else if (control.type === 'time') next = normalizeTime(value);
|
||||
else if (['rent', 'delivery', 'deposit'].includes(field.name)) next = normalizeMoney(value);
|
||||
else if (field.name === 'invoice_no') {
|
||||
if (value.toLowerCase() === 'nein') {
|
||||
next = '';
|
||||
const no = bookingForm.querySelector('input[name="invoice"][value="0"]');
|
||||
if (no) no.checked = true;
|
||||
} else if (value) {
|
||||
const yes = bookingForm.querySelector('input[name="invoice"][value="1"]');
|
||||
if (yes) yes.checked = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (control.tagName === 'SELECT') {
|
||||
if (next && chooseOption(control, next)) filled += 1;
|
||||
continue;
|
||||
}
|
||||
control.value = next;
|
||||
filled += 1;
|
||||
control.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
control.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
return filled;
|
||||
};
|
||||
|
||||
pasteHost.addEventListener('paste', (event) => {
|
||||
const clipboard = event.clipboardData || window.clipboardData;
|
||||
const text = clipboard ? clipboard.getData('text') : '';
|
||||
if (!/[\t\n]/.test(text.trim())) return; // einzelner Wert: Standardverhalten
|
||||
const targetRow = event.target.closest?.('[data-paste-field]');
|
||||
let startIndex = pasteRows.findIndex((field) => field.row === targetRow);
|
||||
if (startIndex < 0) startIndex = 0;
|
||||
if (applyPaste(text, startIndex) > 0) {
|
||||
event.preventDefault();
|
||||
updateTotals();
|
||||
updateSummary();
|
||||
checkAvailability();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateTrailer();
|
||||
updateTotals();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue