feat(documents): Mietvertrag, Auftragsbestätigung und Rechnung zur Buchung
- Mietvertrag als PDF in drei Varianten (Mit Lieferung, Selbstabholer, Truhe), Seite 2+ mit der AGB aus app/agb.php – derselbe Text wie /agb. - Auftragsbestätigung als PDF, ebenfalls in drei Varianten. - PDF-Erzeuger ohne Fremdbibliothek (app/pdf.php, Helvetica + JPEG für die Unterschrift); Layout in app/documents.php. - Unterschrift auf dem Tablet (views/document_sign.php, Canvas -> JPEG) wird ins PDF gesetzt; Unterlagen lassen sich ansehen, drucken und per Mail an den Kunden senden (mail_send_attachment()). - Rechnung aus Lexware als PDF-Upload; Ablage unter storage/documents/<booking_id>/ (per .htaccess gesperrt). - Aufbewahrung: documents_cleanup() im Cron löscht einen Monat nach Mietende (app.document_retention_days), inklusive verwaister Dateien. - Migrationen per HTTP (/migrate?token=…, app/migrate.php), weil das Hosting kein SSH hat; deploy.sh ruft die Route nach dem Sync auf. - Schema: booking_documents (Migration 012, auch in schema.sql), Doku in README/ROADMAP/docs/todo_kundenemail_2026-11-30-unterlagen.md. Enthält außerdem die bislang nicht committeten Anpassungen in bootstrap.php und app.js/pages.php, die im selben Arbeitsstand lagen.
This commit is contained in:
parent
3e34a6c839
commit
2de8e95c15
24 changed files with 2412 additions and 49 deletions
189
app/agb.php
Normal file
189
app/agb.php
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Allgemeine Geschäftsbedingungen als Datenquelle.
|
||||
*
|
||||
* Genutzt von der öffentlichen AGB-Seite (views/legal_agb.php) und von den
|
||||
* Buchungsunterlagen (Mietvertrag, Seite 2). So gibt es nur eine Fassung des
|
||||
* Textes; Änderungen wirken überall.
|
||||
*
|
||||
* Aufbau je Abschnitt:
|
||||
* id – Sprungmarke für das Inhaltsverzeichnis
|
||||
* title – Überschrift ohne Nummer (Nummer ergibt sich aus der Reihenfolge)
|
||||
* blocks – Liste aus ['p' => 'Absatz'] oder ['ul' => ['Punkt', …]]
|
||||
*
|
||||
* @return list<array{id: string, title: string, blocks: list<array<string, mixed>>}>
|
||||
*/
|
||||
function agb_sections(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'id' => 'geltungsbereich',
|
||||
'title' => 'Geltungsbereich',
|
||||
'blocks' => [[
|
||||
'p' => 'Diese AGB gelten für alle Mietverträge über Kühlanhänger und Kühltrühen zwischen '
|
||||
. 'dem Vermieter und dem Mieter. Abweichende Bedingungen gelten nur bei schriftlicher '
|
||||
. 'Zustimmung des Vermieters.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'vertragsabschluss',
|
||||
'title' => 'Vertragsabschluss',
|
||||
'blocks' => [[
|
||||
'p' => 'Der Mietvertrag kommt durch Onlinebuchung und Bestätigung in Textform '
|
||||
. '(z. B. E-Mail oder WhatsApp) zustande.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'mietgegenstand',
|
||||
'title' => 'Mietgegenstand & Zustand',
|
||||
'blocks' => [[
|
||||
'p' => 'Der Mietgegenstand wird sauber und funktionsfähig übergeben. Offensichtliche '
|
||||
. 'Mängel sind bei Übergabe unverzüglich mitzuteilen.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'mietdauer',
|
||||
'title' => 'Mietdauer & Rückgabe',
|
||||
'blocks' => [
|
||||
['p' => 'Die Mietdauer ergibt sich aus dem Vertrag.'],
|
||||
['p' => 'Die Rückgabe hat pünktlich, vollständig, gereinigt und unbeschädigt zu erfolgen. '
|
||||
. 'Bei verspäteter Rückgabe werden mindestens 50 % des Tagesmietpreises je angefangenen '
|
||||
. 'Tag berechnet. Weitergehende Schäden bleiben vorbehalten.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'zahlung',
|
||||
'title' => 'Mietpreis, Kaution & Zahlung',
|
||||
'blocks' => [
|
||||
['p' => 'Es gilt die vereinbarte Preisliste. Eine Kaution von 100 € ist vor oder bei der '
|
||||
. 'Übergabe zu zahlen.'],
|
||||
['p' => 'Der vollständige Mietpreis sowie die Kaution sind bei der Übergabe in bar zu zahlen. '
|
||||
. 'Die Kaution wird bei ordnungsgemäßer Rückgabe selbstverständlich vollständig erstattet.'],
|
||||
['p' => 'Nach Absprache kann auch per Überweisung bezahlt werden – dann jedoch so, dass das '
|
||||
. 'Geld spätestens am Montag der Terminwoche auf dem Konto des Vermieters eingegangen ist.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'lieferung',
|
||||
'title' => 'Lieferung & Abholung',
|
||||
'blocks' => [
|
||||
['p' => 'Lieferung und Abholung erfolgen km-abhängig zum vereinbarten Termin.'],
|
||||
['p' => 'Der Mieter stellt eine befahrbare Zufahrt sowie persönliche Übergabe sicher. '
|
||||
. 'Mehrkosten durch Wartezeiten, falsche Adressen oder Nichtantreffen können berechnet '
|
||||
. 'werden. Die Gefahr geht mit Übergabe auf den Mieter über.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'nutzung',
|
||||
'title' => 'Nutzungspflichten',
|
||||
'blocks' => [[
|
||||
'p' => 'Der Mietgegenstand ist sachgemäß zu benutzen. Stromaggregate sind nicht erlaubt. '
|
||||
. 'Bei unsachgemäßer Nutzung haftet der Mieter für alle Schäden.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'fuehrung',
|
||||
'title' => 'Kühlanhänger – Führung & Sicherung',
|
||||
'blocks' => [[
|
||||
'p' => 'Kühlanhänger dürfen nur von Personen mit gültigem Führerschein geführt werden. '
|
||||
. 'Abgestellte Anhänger sind gegen Wegrollen und Diebstahl zu sichern.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'versicherung',
|
||||
'title' => 'Versicherung',
|
||||
'blocks' => [[
|
||||
'p' => 'Kühlanhänger sind haftpflicht- und vollkaskoversichert (300 € Selbstbeteiligung). '
|
||||
. 'Kein Versicherungsschutz besteht bei grober Fahrlässigkeit oder Verstoß gegen diese AGB.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'haftung',
|
||||
'title' => 'Haftung',
|
||||
'blocks' => [
|
||||
['p' => 'Der Vermieter haftet unbeschränkt bei Vorsatz, grober Fahrlässigkeit sowie bei '
|
||||
. 'Verletzung von Leben, Körper oder Gesundheit.'],
|
||||
['p' => 'Bei Verletzung wesentlicher Vertragspflichten ist die Haftung auf den '
|
||||
. 'vertragstypischen Schaden begrenzt. Im Übrigen ist die Haftung ausgeschlossen.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'schaeden',
|
||||
'title' => 'Schäden & Verlust',
|
||||
'blocks' => [[
|
||||
'p' => 'Der Mieter haftet für alle Schäden, Verlust oder Diebstahl während der Mietzeit, '
|
||||
. 'insbesondere durch Fehlbedienung, Überladung oder unsachgemäßen Gebrauch.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'schadensmeldung',
|
||||
'title' => 'Schadensmeldung',
|
||||
'blocks' => [[
|
||||
'p' => 'Schäden oder Unfälle sind unverzüglich, spätestens bei Rückgabe, schriftlich zu '
|
||||
. 'melden. Bei Unfällen mit Dritten ist ggf. die Polizei zu informieren.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'widerruf',
|
||||
'title' => 'Widerrufsrecht (Verbraucher)',
|
||||
'blocks' => [
|
||||
['p' => 'Bei Onlinebuchung besteht ein 14-tägiges Widerrufsrecht, sofern die Mietleistung '
|
||||
. 'noch nicht begonnen hat.'],
|
||||
['p' => 'Verlangt der Mieter ausdrücklich den Mietbeginn vor Ablauf der Widerrufsfrist, '
|
||||
. 'erlischt das Widerrufsrecht mit Beginn der Mietzeit.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'id' => 'stornierung',
|
||||
'title' => 'Stornierung (nach Widerrufsfrist)',
|
||||
'blocks' => [[
|
||||
'ul' => [
|
||||
'bis 30 Tage vor Mietbeginn: kostenlos',
|
||||
'bis 14 Tage: 30 %',
|
||||
'bis 7 Tage: 50 %',
|
||||
'unter 7 Tage: 60 % des Mietpreises',
|
||||
],
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'hoehere-gewalt',
|
||||
'title' => 'Höhere Gewalt',
|
||||
'blocks' => [[
|
||||
'p' => 'Bei unvorhersehbaren Ereignissen (z. B. Unfall, Diebstahl, Defekt) besteht kein '
|
||||
. 'Schadensersatzanspruch. Bereits gezahlte Beträge werden erstattet.',
|
||||
]],
|
||||
],
|
||||
[
|
||||
'id' => 'schlussbestimmung',
|
||||
'title' => 'Schlussbestimmung',
|
||||
'blocks' => [[
|
||||
'p' => 'Es gilt deutsches Recht. Für Verbraucher gilt der gesetzliche Gerichtsstand. '
|
||||
. 'Sollte eine Klausel unwirksam sein, bleibt die Wirksamkeit der übrigen unberührt.',
|
||||
]],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** Nummerierte Überschrift eines Abschnitts, z. B. "4. Mietdauer & Rückgabe". */
|
||||
function agb_heading(int $index, array $section): string
|
||||
{
|
||||
return ($index + 1) . '. ' . (string) $section['title'];
|
||||
}
|
||||
|
||||
/** Abschnittstext als reine Textzeilen (für PDF und Vorschau). */
|
||||
function agb_plain_blocks(array $section): array
|
||||
{
|
||||
$lines = [];
|
||||
foreach ($section['blocks'] as $block) {
|
||||
if (isset($block['p'])) {
|
||||
$lines[] = ['type' => 'p', 'text' => (string) $block['p']];
|
||||
continue;
|
||||
}
|
||||
foreach ((array) ($block['ul'] ?? []) as $item) {
|
||||
$lines[] = ['type' => 'li', 'text' => (string) $item];
|
||||
}
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
|
@ -30,6 +30,10 @@ require DIC_APP . '/legal.php';
|
|||
require DIC_APP . '/db.php';
|
||||
require DIC_APP . '/webpush.php';
|
||||
require DIC_APP . '/auth.php';
|
||||
require DIC_APP . '/migrate.php';
|
||||
require DIC_APP . '/agb.php';
|
||||
require DIC_APP . '/pdf.php';
|
||||
require DIC_APP . '/documents.php';
|
||||
require DIC_APP . '/data.php';
|
||||
require DIC_APP . '/push.php';
|
||||
require DIC_APP . '/mail.php';
|
||||
|
|
@ -60,6 +64,17 @@ set_exception_handler(static function (Throwable $error): void {
|
|||
. ' · <a style="color:#196abc" href="' . e(url('/datenschutz')) . '">Datenschutz</a></p></body>';
|
||||
});
|
||||
|
||||
// Stillgelegtes Deployment: keine Anwendung, keine Anmeldung, nur der Vermerk.
|
||||
$retiredUrl = trim((string) config('app.retired_url', ''));
|
||||
if ($retiredUrl !== '') {
|
||||
if (PHP_SAPI === 'cli') {
|
||||
fwrite(STDERR, "Dieses Deployment ist stillgelegt: $retiredUrl\n");
|
||||
exit(0);
|
||||
}
|
||||
retired_notice($retiredUrl);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
// Öffentliche Rechtsseiten, Health-Check und Cron brauchen keine Session.
|
||||
// So wird auf Impressum/Datenschutz kein unnötiges Sitzungs-Cookie gesetzt.
|
||||
|
|
|
|||
|
|
@ -38,6 +38,17 @@ return [
|
|||
'inquiry_email' => '',
|
||||
// Token für /cron/reminders?token=…, falls kein CLI-Cron möglich ist.
|
||||
'cron_token' => '',
|
||||
// Stilllegung: Ist hier die URL der aktuellen Seite eingetragen, zeigt
|
||||
// dieses Deployment nur noch einen Umzugsvermerk und lässt keine
|
||||
// Anmeldung mehr zu (z. B. für den alten Test-Deploy).
|
||||
'retired_url' => '',
|
||||
// Buchungsunterlagen (Mietvertrag, Auftragsbestätigung, Rechnung).
|
||||
// Aufbewahrung ab Mietende; danach räumt privacy_cleanup() auf.
|
||||
'document_retention_days' => 30,
|
||||
// Kaution, die im Vertrag aufgeführt wird (in Cent).
|
||||
'document_deposit_cents' => 10000,
|
||||
// Maximale Größe einer hochgeladenen Rechnung (PDF aus Lexware).
|
||||
'document_max_mb' => 10,
|
||||
],
|
||||
// Optional: Angaben für Impressum und Datenschutz überschreiben. Die
|
||||
// Standardwerte stehen in app/legal.php. Hinweis: tools/deploy.sh erzeugt
|
||||
|
|
|
|||
855
app/documents.php
Normal file
855
app/documents.php
Normal file
|
|
@ -0,0 +1,855 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Buchungsunterlagen: Mietvertrag, Auftragsbestätigung und Rechnung.
|
||||
*
|
||||
* Alle Unterlagen werden als PDF in storage/documents/<booking_id>/ abgelegt und
|
||||
* nur über eine angemeldete Route ausgeliefert (der storage-Ordner ist per
|
||||
* .htaccess gesperrt). Mietvertrag und Auftragsbestätigung erzeugt die App
|
||||
* selbst (app/pdf.php), die Rechnung lädt der Admin als PDF aus Lexware hoch.
|
||||
*
|
||||
* Mietvertrag-Varianten: Lieferung, Selbstabholer, Truhe. Die Variante ergibt
|
||||
* sich aus der Buchung (Truhe = Anhängername beginnt mit "Truhe", sonst
|
||||
* Lieferung/Abholung) und lässt sich beim Erzeugen überschreiben.
|
||||
*
|
||||
* Aufbewahrung: einen Monat nach Mietende löscht privacy_cleanup() die Dateien
|
||||
* (app.document_retention_days, Standard 30 Tage).
|
||||
*/
|
||||
|
||||
const DOCUMENT_KIND_CONTRACT = 'contract';
|
||||
const DOCUMENT_KIND_CONFIRMATION = 'confirmation';
|
||||
const DOCUMENT_KIND_INVOICE = 'invoice';
|
||||
|
||||
/** @return array<string, string> */
|
||||
function document_kinds(): array
|
||||
{
|
||||
return [
|
||||
DOCUMENT_KIND_CONTRACT => 'Mietvertrag',
|
||||
DOCUMENT_KIND_CONFIRMATION => 'Auftragsbestätigung',
|
||||
DOCUMENT_KIND_INVOICE => 'Rechnung',
|
||||
];
|
||||
}
|
||||
|
||||
function document_kind_label(string $kind): string
|
||||
{
|
||||
return document_kinds()[$kind] ?? $kind;
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
function document_variants(): array
|
||||
{
|
||||
return [
|
||||
'delivery' => 'Mit Lieferung',
|
||||
'pickup' => 'Selbstabholer',
|
||||
'chest' => 'Truhe',
|
||||
];
|
||||
}
|
||||
|
||||
function document_variant_label(string $variant): string
|
||||
{
|
||||
return document_variants()[$variant] ?? 'Mit Lieferung';
|
||||
}
|
||||
|
||||
/** Passende Variante zur Buchung (Truhe, Lieferung oder Selbstabholer). */
|
||||
function document_variant_default(array $booking): string
|
||||
{
|
||||
$label = (string) ($booking['trailer_label'] ?? '');
|
||||
if ($label !== '' && mb_stripos(trim($label), 'truhe') === 0) {
|
||||
return 'chest';
|
||||
}
|
||||
return (string) ($booking['kind'] ?? 'pickup') === 'delivery' ? 'delivery' : 'pickup';
|
||||
}
|
||||
|
||||
/**
|
||||
* Variantentexte, in app/config.local.php unter `documents` überschreibbar:
|
||||
*
|
||||
* 'documents' => ['delivery' => ['hint' => '…', 'accessories' => ['…']], …]
|
||||
*/
|
||||
function document_texts(string $variant): array
|
||||
{
|
||||
$defaults = [
|
||||
'delivery' => [
|
||||
'subject' => 'Kühlanhänger',
|
||||
'hint' => 'Wichtig zu beachten ist, dass der Kühlanhänger nicht mit einem Stromaggregat '
|
||||
. 'betrieben werden darf. Der Anhänger ist stets gegen Wegrollen und Diebstahl zu sichern.',
|
||||
'accessories' => ['3 Schlüssel', '1 Stromkabel (15 m)', '2 Diebstahlsicherungen (Kupplung & Kralle)'],
|
||||
'pickup_fields' => false,
|
||||
],
|
||||
'pickup' => [
|
||||
'subject' => 'Kühlanhänger',
|
||||
'hint' => 'Wichtig zu beachten ist, dass der Kühlanhänger nicht mit einem Stromaggregat '
|
||||
. 'betrieben werden darf. Der Anhänger ist stets gegen Wegrollen und Diebstahl zu sichern.',
|
||||
'accessories' => ['3 Schlüssel', '1 Stromkabel (15 m)', '2 Diebstahlsicherungen (Kupplung & Kralle)'],
|
||||
'pickup_fields' => true,
|
||||
],
|
||||
'chest' => [
|
||||
'subject' => 'Kühltruhe',
|
||||
'hint' => 'Wichtig zu beachten ist, dass die Kühltruhe nicht mit einem Stromaggregat betrieben '
|
||||
. 'werden darf und nur an einer geerdeten Steckdose angeschlossen wird.',
|
||||
'accessories' => ['1 Stromkabel (15 m)'],
|
||||
'pickup_fields' => true,
|
||||
],
|
||||
];
|
||||
$variant = array_key_exists($variant, $defaults) ? $variant : 'delivery';
|
||||
$merged = $defaults[$variant];
|
||||
$configured = config('documents.' . $variant, []);
|
||||
if (is_array($configured)) {
|
||||
foreach ($configured as $key => $value) {
|
||||
if (is_string($key) && (is_string($value) || is_array($value) || is_bool($value))) {
|
||||
$merged[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
$merged['accessories'] = array_values(array_map('strval', (array) ($merged['accessories'] ?? [])));
|
||||
return $merged;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Speicher */
|
||||
|
||||
/**
|
||||
* Ist die Tabelle für Buchungsunterlagen vorhanden? Solange die Migration
|
||||
* (012_booking_documents.sql) nicht gelaufen ist, bleiben Buchungsseite und
|
||||
* Cron sonst mit einem SQL-Fehler stehen.
|
||||
*/
|
||||
function documents_schema_ready(): bool
|
||||
{
|
||||
static $ready = null;
|
||||
if ($ready !== null) {
|
||||
return $ready;
|
||||
}
|
||||
try {
|
||||
$stmt = db()->query("SHOW TABLES LIKE 'booking_documents'");
|
||||
$ready = $stmt !== false && $stmt->fetchColumn() !== false;
|
||||
} catch (Throwable) {
|
||||
$ready = false;
|
||||
}
|
||||
return $ready;
|
||||
}
|
||||
|
||||
function document_store_root(): string
|
||||
{
|
||||
$storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/');
|
||||
return $storage . '/documents';
|
||||
}
|
||||
|
||||
function document_booking_dir(int $bookingId, bool $create = false): string
|
||||
{
|
||||
$dir = document_store_root() . '/' . $bookingId;
|
||||
if ($create && !is_dir($dir)) {
|
||||
@mkdir($dir, 0775, true);
|
||||
}
|
||||
return $dir;
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
function documents_for_booking(int $bookingId): array
|
||||
{
|
||||
if (!documents_schema_ready()) {
|
||||
return [];
|
||||
}
|
||||
$stmt = db()->prepare('SELECT * FROM booking_documents WHERE booking_id = ? ORDER BY created_at DESC, id DESC');
|
||||
$stmt->execute([$bookingId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function document_find(int $id): ?array
|
||||
{
|
||||
if (!documents_schema_ready()) {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare('SELECT * FROM booking_documents WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
function document_path(array $doc): string
|
||||
{
|
||||
return document_store_root() . '/' . (int) $doc['booking_id'] . '/' . (string) $doc['stored_file'];
|
||||
}
|
||||
|
||||
function document_signature_path(array $doc): ?string
|
||||
{
|
||||
$file = trim((string) ($doc['signature_file'] ?? ''));
|
||||
if ($file === '') {
|
||||
return null;
|
||||
}
|
||||
$path = document_store_root() . '/' . (int) $doc['booking_id'] . '/' . $file;
|
||||
return is_file($path) ? $path : null;
|
||||
}
|
||||
|
||||
function document_file_name(string $kind, string $variant, array $booking): string
|
||||
{
|
||||
$prefix = $kind === DOCUMENT_KIND_CONTRACT ? 'Mietvertrag' : 'Auftragsbestaetigung';
|
||||
$parts = [$prefix];
|
||||
if ($variant !== '') {
|
||||
$parts[] = document_variant_label($variant);
|
||||
}
|
||||
$parts[] = (string) $booking['customer_name'];
|
||||
$parts[] = (string) $booking['start_date'];
|
||||
$name = implode(' ', $parts);
|
||||
$name = (string) preg_replace('/[^A-Za-z0-9äöüÄÖÜß ._-]+/u', '', $name);
|
||||
$name = trim((string) preg_replace('/\s+/', ' ', $name));
|
||||
return mb_substr($name === '' ? $prefix : $name, 0, 120) . '.pdf';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Erzeugen */
|
||||
|
||||
/**
|
||||
* Legt ein Dokument an bzw. erneuert es, wenn es dieselbe Art und Variante
|
||||
* bereits gibt (dann bleibt die Unterschrift erhalten).
|
||||
*/
|
||||
function document_create(array $booking, string $kind, string $variant, ?int $userId): array
|
||||
{
|
||||
if (!array_key_exists($kind, document_kinds()) || $kind === DOCUMENT_KIND_INVOICE) {
|
||||
throw new RuntimeException('Diese Unterlagen-Art wird nicht erzeugt.');
|
||||
}
|
||||
if (!documents_schema_ready()) {
|
||||
throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.');
|
||||
}
|
||||
if (!array_key_exists($variant, document_variants())) {
|
||||
$variant = document_variant_default($booking);
|
||||
}
|
||||
|
||||
foreach (documents_for_booking((int) $booking['id']) as $doc) {
|
||||
if ($doc['kind'] === $kind && $doc['variant'] === $variant && $doc['source'] === 'generated') {
|
||||
return document_regenerate($booking, $doc);
|
||||
}
|
||||
}
|
||||
|
||||
$dir = document_booking_dir((int) $booking['id'], true);
|
||||
$token = bin2hex(random_bytes(8));
|
||||
$stored = $token . '.pdf';
|
||||
$bytes = document_render($booking, $kind, $variant, null, null);
|
||||
if (@file_put_contents($dir . '/' . $stored, $bytes) === false) {
|
||||
throw new RuntimeException('Unterlage konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO booking_documents
|
||||
(booking_id, kind, variant, file_name, stored_file, mime_type, size_bytes, source, created_at, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
(int) $booking['id'],
|
||||
$kind,
|
||||
$variant,
|
||||
document_file_name($kind, $variant, $booking),
|
||||
$stored,
|
||||
'application/pdf',
|
||||
strlen($bytes),
|
||||
'generated',
|
||||
utc_now(),
|
||||
$userId,
|
||||
]);
|
||||
|
||||
return document_find((int) db()->lastInsertId()) ?? [];
|
||||
}
|
||||
|
||||
/** Erzeugt das PDF einer vorhandenen Unterlage neu (z. B. nach dem Unterschreiben). */
|
||||
function document_regenerate(array $booking, array $doc): array
|
||||
{
|
||||
$kind = (string) $doc['kind'];
|
||||
if ($kind === DOCUMENT_KIND_INVOICE) {
|
||||
return $doc;
|
||||
}
|
||||
$variant = (string) ($doc['variant'] ?: document_variant_default($booking));
|
||||
$bytes = document_render(
|
||||
$booking,
|
||||
$kind,
|
||||
$variant,
|
||||
document_signature_path($doc),
|
||||
$doc['signed_at'] !== null ? (string) $doc['signed_at'] : null
|
||||
);
|
||||
$path = document_path($doc);
|
||||
document_booking_dir((int) $doc['booking_id'], true);
|
||||
if (@file_put_contents($path, $bytes) === false) {
|
||||
throw new RuntimeException('Unterlage konnte nicht gespeichert werden.');
|
||||
}
|
||||
db()->prepare('UPDATE booking_documents SET size_bytes = ?, file_name = ? WHERE id = ?')
|
||||
->execute([strlen($bytes), document_file_name($kind, $variant, $booking), (int) $doc['id']]);
|
||||
|
||||
return document_find((int) $doc['id']) ?? $doc;
|
||||
}
|
||||
|
||||
function document_render(
|
||||
array $booking,
|
||||
string $kind,
|
||||
string $variant,
|
||||
?string $signatureFile,
|
||||
?string $signedAt
|
||||
): string {
|
||||
return $kind === DOCUMENT_KIND_CONFIRMATION
|
||||
? document_confirmation_pdf($booking, $variant)
|
||||
: document_contract_pdf($booking, $variant, $signatureFile, $signedAt);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- PDF-Aufbau */
|
||||
|
||||
function document_pdf_footer(PdfDoc $pdf, string $label): void
|
||||
{
|
||||
$w = $pdf->pageWidth();
|
||||
$h = $pdf->pageHeight();
|
||||
$pdf->line(50, $h - 52, $w - 50, $h - 52, 0.5);
|
||||
$pdf->text(50, $h - 38, 7.5, $label);
|
||||
$pdf->text(50, $h - 38, 7.5, 'Seite ' . $pdf->pageNo(), false, 'right', $w - 100);
|
||||
}
|
||||
|
||||
/** Kopfzeile mit Titel und rechtsstehender Kennung. */
|
||||
function document_pdf_title(PdfDoc $pdf, string $title, string $right): void
|
||||
{
|
||||
$w = $pdf->pageWidth();
|
||||
$pdf->text(50, 66, 20, $title, true);
|
||||
$pdf->text(50, 66, 8.5, $right, false, 'right', $w - 100);
|
||||
$pdf->line(50, 76, $w - 50, 76, 1.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zwei Adressblöcke nebeneinander: links der Kunde (Mieter), rechts der Vermieter.
|
||||
*/
|
||||
function document_pdf_parties(PdfDoc $pdf, float $top, array $booking): float
|
||||
{
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$left = 50.0;
|
||||
$right = 310.0;
|
||||
$pdf->text($left, $top, 7.5, 'MIETER', true);
|
||||
$pdf->text($right, $top, 7.5, 'VERMIETER', true);
|
||||
|
||||
$y = $top + 14;
|
||||
$pdf->text($left, $y, 11, (string) $booking['customer_name'], true);
|
||||
$pdf->text($right, $y, 11, $owner, true);
|
||||
$pdf->text($right, $y + 13, 9.5, (string) $legal['business_name']);
|
||||
|
||||
$customer = array_values(array_filter([
|
||||
(string) $booking['street'],
|
||||
(string) $booking['city'],
|
||||
trim((string) $booking['mobile']) !== '' ? 'Tel. ' . (string) $booking['mobile'] : '',
|
||||
(string) $booking['email'],
|
||||
], static fn (string $v): bool => $v !== ''));
|
||||
|
||||
$landlord = array_values(array_filter([
|
||||
(string) $legal['street'],
|
||||
trim((string) $legal['postal_code'] . ' ' . $legal['city']),
|
||||
'Tel. ' . (string) $legal['phone'],
|
||||
(string) $legal['email'],
|
||||
trim((string) ($legal['vat_id'] ?? '')) !== '' ? 'USt-IdNr. ' . (string) $legal['vat_id'] : '',
|
||||
], static fn (string $v): bool => $v !== ''));
|
||||
|
||||
$max = max(count($customer), count($landlord));
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
if (isset($customer[$i])) {
|
||||
$pdf->text($left, $y + 29 + $i * 12.5, 9.5, $customer[$i]);
|
||||
}
|
||||
if (isset($landlord[$i])) {
|
||||
$pdf->text($right, $y + 29 + $i * 12.5, 9.5, $landlord[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
return $y + 29 + $max * 12.5 + 14;
|
||||
}
|
||||
|
||||
/** Abschnittsüberschrift. */
|
||||
function document_pdf_heading(PdfDoc $pdf, float $top, string $title): float
|
||||
{
|
||||
$pdf->text(50, $top + 10, 10, $title, true);
|
||||
return $top + 26;
|
||||
}
|
||||
|
||||
/**
|
||||
* Label/Wert-Zeilen. $rows: Liste aus [label, value] oder [label, value, true]
|
||||
* (fett). Lange Labels und Werte brechen um. Liefert die nächste Grundlinie.
|
||||
*/
|
||||
function document_pdf_rows(PdfDoc $pdf, float $top, array $rows, float $valueX = 200.0): float
|
||||
{
|
||||
$right = $pdf->pageWidth() - 50;
|
||||
$y = $top;
|
||||
foreach ($rows as $row) {
|
||||
$bold = !empty($row[2]);
|
||||
$labelLines = $pdf->wrap((string) $row[0], 9, $valueX - 62, true);
|
||||
$valueLines = $pdf->wrap((string) $row[1], 10, $right - $valueX, $bold);
|
||||
foreach ($labelLines as $i => $line) {
|
||||
$pdf->text(50, $y + $i * 12, 9, $line, true);
|
||||
}
|
||||
foreach ($valueLines as $i => $line) {
|
||||
$pdf->text($valueX, $y + $i * 13, 10, $line, $bold);
|
||||
}
|
||||
$y += max(count($labelLines), count($valueLines)) * 13 + 3;
|
||||
}
|
||||
return $y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bezeichnung des Mietgegenstandes, ohne doppelte Wörter
|
||||
* ("Kühlanhänger 1", "Kühltruhe 1", "Kühlanhänger: WM Meyer").
|
||||
*/
|
||||
function document_subject_line(array $booking, array $texts): string
|
||||
{
|
||||
$label = trim((string) ($booking['trailer_label'] ?? ''));
|
||||
$subject = (string) ($texts['subject'] ?? 'Mietgegenstand');
|
||||
if ($label === '') {
|
||||
return $subject;
|
||||
}
|
||||
if (mb_stripos($label, $subject) !== false) {
|
||||
return $label;
|
||||
}
|
||||
if (mb_stripos($label, 'truhe') === 0) {
|
||||
return 'Kühltruhe' . mb_substr($label, 5);
|
||||
}
|
||||
if (mb_stripos($label, 'anhänger') !== false) {
|
||||
return $label;
|
||||
}
|
||||
return $subject . ': ' . $label;
|
||||
}
|
||||
|
||||
/** Absatz mit fettem Vorspann in einem hellen Kasten. */
|
||||
function document_pdf_note(PdfDoc $pdf, float $top, string $title, string $text): float
|
||||
{
|
||||
$w = $pdf->pageWidth() - 100;
|
||||
$lines = $pdf->wrap($text, 9, $w - 20);
|
||||
$height = count($lines) * 12 + 24;
|
||||
$pdf->rect(50, $top, $w, $height, true);
|
||||
$pdf->text(60, $top + 15, 8.5, $title, true);
|
||||
$y = $top + 29;
|
||||
foreach ($lines as $line) {
|
||||
$pdf->text(60, $y, 9, $line);
|
||||
$y += 12;
|
||||
}
|
||||
return $top + $height + 14;
|
||||
}
|
||||
|
||||
/** Unterschriftfelder für Mieter und Vermieter. */
|
||||
function document_pdf_signatures(PdfDoc $pdf, float $top, array $booking, ?string $signatureFile, ?string $signedAt): void
|
||||
{
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$lineLeft = 50.0;
|
||||
$lineRight = 310.0;
|
||||
$lineWidth = 235.0;
|
||||
|
||||
if ($signatureFile !== null) {
|
||||
$pdf->image($signatureFile, $lineLeft, $top - 52, 150, 50);
|
||||
}
|
||||
$pdf->text($lineRight, $top - 10, 10, $owner . ' · ' . (string) $legal['business_name']);
|
||||
|
||||
$pdf->line($lineLeft, $top, $lineLeft + $lineWidth, $top, 0.7);
|
||||
$pdf->line($lineRight, $top, $lineRight + $lineWidth, $top, 0.7);
|
||||
$pdf->text($lineLeft, $top + 13, 7.5, 'Datum, Unterschrift Mieter');
|
||||
$pdf->text($lineRight, $top + 13, 7.5, 'Datum, Unterschrift Vermieter');
|
||||
|
||||
if ($signedAt !== null && $signatureFile !== null) {
|
||||
$pdf->text($lineLeft, $top - 6, 8.5, 'Unterschrieben am ' . fmt_datetime($signedAt) . ' (Tablet/eSignatur)');
|
||||
}
|
||||
$pdf->text($lineLeft, $top + 30, 8.5, 'Gesamtbetrag bei Übergabe erhalten: ______________________ €');
|
||||
$pdf->text($lineLeft, $top + 46, 8.5, 'Kaution bei Rücknahme zurück erhalten: _____________________ €');
|
||||
}
|
||||
|
||||
/** Mietvertrag als PDF (Variante Lieferung, Selbstabholer oder Truhe). */
|
||||
function document_contract_pdf(array $booking, string $variant, ?string $signatureFile, ?string $signedAt): string
|
||||
{
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$texts = document_texts($variant);
|
||||
$deposit = max(0, (int) config('app.document_deposit_cents', 10000));
|
||||
$rent = (int) ($booking['rent_cents'] ?? $booking['total_cents']);
|
||||
$delivery = (int) ($booking['delivery_cents'] ?? 0);
|
||||
$paid = (int) ($booking['deposit_cents'] ?? 0);
|
||||
$total = (int) $booking['total_cents'];
|
||||
$grand = $total + $deposit;
|
||||
$open = $grand - $paid;
|
||||
|
||||
$pdf = new PdfDoc();
|
||||
document_pdf_title($pdf, 'Mietvertrag', document_variant_label($variant) . ' · Buchung #' . (int) $booking['id']);
|
||||
$y = document_pdf_parties($pdf, 92, $booking);
|
||||
|
||||
$address = trim((string) $booking['street'] . ', ' . (string) $booking['city'], ', ');
|
||||
$period = 'von ' . fmt_date_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||||
. ' bis ' . fmt_date_with_time((string) $booking['end_date'], $booking['end_time'] ?? null);
|
||||
|
||||
$y = document_pdf_heading($pdf, $y, 'Mietgegenstand und Mietzeit');
|
||||
$rows = [['Mietgegenstand', document_subject_line($booking, $texts)]];
|
||||
if ($variant === 'delivery') {
|
||||
$rows[] = ['Lieferadresse', $address !== '' ? $address : 'wie Mieteranschrift'];
|
||||
} else {
|
||||
$rows[] = ['Abholung', 'Selbstabholung bei ' . $owner . ', ' . $legal['street'] . ', ' . trim((string) $legal['postal_code'] . ' ' . $legal['city'])];
|
||||
}
|
||||
$rows[] = ['Mietzeitraum', $period];
|
||||
$y = document_pdf_rows($pdf, $y, $rows);
|
||||
|
||||
$y = document_pdf_heading($pdf, $y + 8, 'Mietzubehör');
|
||||
foreach ((array) $texts['accessories'] as $item) {
|
||||
$pdf->text(60, $y, 10, '• ' . $item);
|
||||
$y += 13;
|
||||
}
|
||||
$y += 8;
|
||||
|
||||
if (!empty($texts['pickup_fields'])) {
|
||||
$y = document_pdf_heading($pdf, $y, 'Angaben zur Abholung (bitte ausfüllen)');
|
||||
foreach (['Name des Abholers', 'Fahrzeug / amtliches Kennzeichen', 'Personalausweis-Nr.', 'Führerschein-Nr.'] as $field) {
|
||||
$pdf->text(50, $y, 9, $field, true);
|
||||
$pdf->line(200, $y + 2, 545, $y + 2, 0.5);
|
||||
$y += 18;
|
||||
}
|
||||
$y += 4;
|
||||
}
|
||||
|
||||
$y = document_pdf_heading($pdf, $y + 6, 'Mietpreis und Zahlung');
|
||||
$priceRows = [['Miete', fmt_money($rent)]];
|
||||
if ($delivery > 0) {
|
||||
$priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)];
|
||||
}
|
||||
if ($deposit > 0) {
|
||||
$priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)'];
|
||||
}
|
||||
if ($paid > 0) {
|
||||
$priceRows[] = ['Anzahlung', '− ' . fmt_money($paid)];
|
||||
}
|
||||
$priceRows[] = ['Gesamtbetrag', fmt_money($grand), true];
|
||||
$priceRows[] = ['Bei Übergabe zu zahlen', fmt_money(max(0, $open)), true];
|
||||
$y = document_pdf_rows($pdf, $y, $priceRows);
|
||||
|
||||
$y = document_pdf_note($pdf, $y + 8, 'Wichtig', (string) $texts['hint']);
|
||||
|
||||
$explain = 'Der Mieter bestätigt, den Mietgegenstand nebst Zubehör in sauberem und funktionsfähigem '
|
||||
. 'Zustand erhalten zu haben. Die Allgemeinen Geschäftsbedingungen des Vermieters (folgende Seiten '
|
||||
. 'dieses Vertrages) sind Bestandteil dieses Mietvertrages und wurden dem Mieter ausgehändigt. '
|
||||
. 'Bei Rückgabe ist der Mietgegenstand gereinigt und vollständig zurückzugeben.';
|
||||
$y = $pdf->paragraph(50, $y + 4, $pdf->pageWidth() - 100, 9, $explain, false, 12.5);
|
||||
|
||||
$signatureTop = $y + 58;
|
||||
if ($signatureTop > 720) {
|
||||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']);
|
||||
$pdf->newPage();
|
||||
$signatureTop = 150;
|
||||
}
|
||||
document_pdf_signatures($pdf, $signatureTop, $booking, $signatureFile, $signedAt);
|
||||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']);
|
||||
|
||||
// Seite 2: AGB (gleiche Fassung wie unter /agb).
|
||||
$pdf->newPage();
|
||||
$y = 70.0;
|
||||
$width = $pdf->pageWidth() - 100;
|
||||
$pdf->text(50, $y, 13, 'Allgemeine Geschäftsbedingungen (AGB)', true);
|
||||
$y += 16;
|
||||
$y = $pdf->paragraph(50, $y, $width, 8.5, 'für die Vermietung von Kühlanhängern und Kühltrühen – ' . $owner
|
||||
. ' – „' . (string) $legal['business_name'] . '“ (nachfolgend „Vermieter“).', false, 11) + 4;
|
||||
|
||||
foreach (agb_sections() as $index => $section) {
|
||||
if ($y > $pdf->pageHeight() - 80) {
|
||||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB');
|
||||
$pdf->newPage();
|
||||
$y = 70.0;
|
||||
}
|
||||
$pdf->text(50, $y, 9.5, agb_heading((int) $index, $section), true);
|
||||
$y += 13;
|
||||
foreach (agb_plain_blocks($section) as $block) {
|
||||
$indent = $block['type'] === 'li' ? 62.0 : 50.0;
|
||||
$prefix = $block['type'] === 'li' ? '– ' : '';
|
||||
$text = $prefix . (string) $block['text'];
|
||||
foreach ($pdf->wrap($text, 8.5, $width - ($indent - 50)) as $line) {
|
||||
if ($y > $pdf->pageHeight() - 70) {
|
||||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB');
|
||||
$pdf->newPage();
|
||||
$y = 70.0;
|
||||
}
|
||||
$pdf->text($indent, $y, 8.5, $line);
|
||||
$y += 11;
|
||||
}
|
||||
$y += 2;
|
||||
}
|
||||
$y += 5;
|
||||
}
|
||||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · AGB');
|
||||
|
||||
return $pdf->output();
|
||||
}
|
||||
|
||||
/** Auftragsbestätigung als PDF. */
|
||||
function document_confirmation_pdf(array $booking, string $variant): string
|
||||
{
|
||||
$legal = legal_data();
|
||||
$texts = document_texts($variant);
|
||||
$deposit = max(0, (int) config('app.document_deposit_cents', 10000));
|
||||
$rent = (int) ($booking['rent_cents'] ?? $booking['total_cents']);
|
||||
$delivery = (int) ($booking['delivery_cents'] ?? 0);
|
||||
$paid = (int) ($booking['deposit_cents'] ?? 0);
|
||||
$total = (int) $booking['total_cents'];
|
||||
$grand = $total + $deposit;
|
||||
|
||||
$pdf = new PdfDoc();
|
||||
document_pdf_title($pdf, 'Auftragsbestätigung', 'Buchung #' . (int) $booking['id'] . ' · ' . fmt_date(today_iso()));
|
||||
$y = document_pdf_parties($pdf, 92, $booking);
|
||||
|
||||
$y = document_pdf_heading($pdf, $y, 'Bestätigte Buchung');
|
||||
$rows = [
|
||||
['Mietgegenstand', document_subject_line($booking, $texts)],
|
||||
['Art', document_variant_label($variant)],
|
||||
['Mietzeitraum', 'von ' . fmt_date_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||||
. ' bis ' . fmt_date_with_time((string) $booking['end_date'], $booking['end_time'] ?? null)],
|
||||
['Übergabe durch', (string) $booking['employee_name']],
|
||||
['Rücknahme durch', booking_return_employee_name($booking)],
|
||||
];
|
||||
if ($variant === 'delivery') {
|
||||
$address = trim((string) $booking['street'] . ', ' . (string) $booking['city'], ', ');
|
||||
$rows[] = ['Lieferadresse', $address !== '' ? $address : (string) $booking['city']];
|
||||
}
|
||||
$y = document_pdf_rows($pdf, $y, $rows);
|
||||
|
||||
$y = document_pdf_heading($pdf, $y + 6, 'Beträge');
|
||||
$priceRows = [['Miete', fmt_money($rent)]];
|
||||
if ($delivery > 0) {
|
||||
$priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)];
|
||||
}
|
||||
if ($deposit > 0) {
|
||||
$priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)'];
|
||||
}
|
||||
if ($paid > 0) {
|
||||
$priceRows[] = ['Anzahlung', '− ' . fmt_money($paid)];
|
||||
}
|
||||
$priceRows[] = ['Gesamtbetrag', fmt_money($grand), true];
|
||||
$priceRows[] = ['Bei Übergabe zu zahlen', fmt_money(max(0, $grand - $paid)), true];
|
||||
$priceRows[] = ['Rechnung', booking_invoice_display($booking)];
|
||||
$y = document_pdf_rows($pdf, $y, $priceRows);
|
||||
|
||||
$note = 'Der Gesamtbetrag ist bei der Übergabe in bar zu zahlen. Nach Absprache ist auch eine '
|
||||
. 'Überweisung möglich – das Geld muss dann spätestens am Montag der Terminwoche eingegangen sein. '
|
||||
. 'Die Kaution wird bei ordnungsgemäßer Rückgabe vollständig erstattet.';
|
||||
$y = document_pdf_note($pdf, $y + 8, 'Zahlung', $note);
|
||||
|
||||
$closing = 'Vielen Dank für die Buchung. Diese Auftragsbestätigung bestätigt den vereinbarten Termin und '
|
||||
. 'die genannten Beträge. Es gelten die Allgemeinen Geschäftsbedingungen des Vermieters. '
|
||||
. 'Bitte prüfen Sie die Angaben und melden Sie sich bei Abweichungen.';
|
||||
$y = $pdf->paragraph(50, $y + 4, $pdf->pageWidth() - 100, 9, $closing, false, 12.5);
|
||||
|
||||
$signatureTop = $y + 50;
|
||||
if ($signatureTop > 720) {
|
||||
document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']);
|
||||
$pdf->newPage();
|
||||
$signatureTop = 150;
|
||||
}
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$pdf->text(310, $signatureTop - 10, 10, $owner . ' · ' . (string) $legal['business_name']);
|
||||
$pdf->line(310, $signatureTop, 545, $signatureTop, 0.7);
|
||||
$pdf->text(310, $signatureTop + 13, 7.5, 'Datum, Unterschrift Vermieter');
|
||||
document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']);
|
||||
|
||||
return $pdf->output();
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- Unterschrift */
|
||||
|
||||
/**
|
||||
* Speichert die Unterschrift vom Tablet (JPEG-Daten-URL) und erzeugt das
|
||||
* Mietvertrags-PDF neu, damit die Unterschrift im Dokument steht.
|
||||
*/
|
||||
function document_save_signature(array $booking, array $doc, string $dataUrl, ?int $userId): array
|
||||
{
|
||||
if ($doc['kind'] !== DOCUMENT_KIND_CONTRACT) {
|
||||
throw new RuntimeException('Nur der Mietvertrag wird unterschrieben.');
|
||||
}
|
||||
if (!preg_match('#^data:image/jpeg;base64,([A-Za-z0-9+/=\s]+)$#', trim($dataUrl), $m)) {
|
||||
throw new RuntimeException('Die Unterschrift konnte nicht gelesen werden.');
|
||||
}
|
||||
$binary = base64_decode((string) preg_replace('/\s+/', '', $m[1]), true);
|
||||
if (!is_string($binary) || strlen($binary) < 500 || strncmp($binary, "\xFF\xD8", 2) !== 0) {
|
||||
throw new RuntimeException('Die Unterschrift ist leer.');
|
||||
}
|
||||
if (strlen($binary) > 1500000) {
|
||||
throw new RuntimeException('Die Unterschrift ist zu groß.');
|
||||
}
|
||||
|
||||
$dir = document_booking_dir((int) $doc['booking_id'], true);
|
||||
$file = 'unterschrift-' . (int) $doc['id'] . '.jpg';
|
||||
if (@file_put_contents($dir . '/' . $file, $binary) === false) {
|
||||
throw new RuntimeException('Die Unterschrift konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
||||
db()->prepare('UPDATE booking_documents SET signature_file = ?, signed_at = ? WHERE id = ?')
|
||||
->execute([$file, utc_now(), (int) $doc['id']]);
|
||||
$doc = document_find((int) $doc['id']) ?? $doc;
|
||||
if (!empty($userId)) {
|
||||
db()->prepare('UPDATE booking_documents SET created_by = COALESCE(created_by, ?) WHERE id = ?')
|
||||
->execute([$userId, (int) $doc['id']]);
|
||||
$doc = document_find((int) $doc['id']) ?? $doc;
|
||||
}
|
||||
|
||||
return document_regenerate($booking, $doc);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Rechnung */
|
||||
|
||||
/**
|
||||
* Nimmt eine Rechnung (PDF aus Lexware) entgegen und legt sie zur Buchung ab.
|
||||
*
|
||||
* @param array{name?: string, tmp_name?: string, error?: int, size?: int} $file
|
||||
*/
|
||||
function document_upload_invoice(array $booking, array $file, ?int $userId): array
|
||||
{
|
||||
if (!documents_schema_ready()) {
|
||||
throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.');
|
||||
}
|
||||
$error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE);
|
||||
if ($error === UPLOAD_ERR_NO_FILE) {
|
||||
throw new RuntimeException('Bitte eine PDF-Datei auswählen.');
|
||||
}
|
||||
if ($error !== UPLOAD_ERR_OK) {
|
||||
throw new RuntimeException('Der Upload ist fehlgeschlagen (Code ' . $error . ').');
|
||||
}
|
||||
$tmp = (string) ($file['tmp_name'] ?? '');
|
||||
if ($tmp === '' || !is_uploaded_file($tmp)) {
|
||||
throw new RuntimeException('Der Upload ist unvollständig.');
|
||||
}
|
||||
$maxMb = max(1, (int) config('app.document_max_mb', 10));
|
||||
$size = (int) filesize($tmp);
|
||||
if ($size < 100) {
|
||||
throw new RuntimeException('Die Datei ist leer.');
|
||||
}
|
||||
if ($size > $maxMb * 1024 * 1024) {
|
||||
throw new RuntimeException('Die Datei ist größer als ' . $maxMb . ' MB.');
|
||||
}
|
||||
$head = (string) file_get_contents($tmp, false, null, 0, 5);
|
||||
if ($head !== '%PDF-') {
|
||||
throw new RuntimeException('Nur PDF-Dateien werden unterstützt.');
|
||||
}
|
||||
$bytes = (string) file_get_contents($tmp);
|
||||
if ($bytes === '') {
|
||||
throw new RuntimeException('Die Datei konnte nicht gelesen werden.');
|
||||
}
|
||||
|
||||
$dir = document_booking_dir((int) $booking['id'], true);
|
||||
$stored = bin2hex(random_bytes(8)) . '.pdf';
|
||||
if (@file_put_contents($dir . '/' . $stored, $bytes) === false) {
|
||||
throw new RuntimeException('Die Rechnung konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
||||
$original = trim((string) ($file['name'] ?? ''));
|
||||
$original = (string) preg_replace('/[^A-Za-z0-9äöüÄÖÜß ._-]+/u', '', basename($original));
|
||||
$name = trim((string) preg_replace('/\s+/', ' ', $original));
|
||||
if ($name === '' || !str_ends_with(mb_strtolower($name), '.pdf')) {
|
||||
$name = 'Rechnung ' . (string) $booking['customer_name'] . '.pdf';
|
||||
}
|
||||
|
||||
db()->prepare(
|
||||
'INSERT INTO booking_documents
|
||||
(booking_id, kind, variant, file_name, stored_file, mime_type, size_bytes, source, created_at, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
(int) $booking['id'],
|
||||
DOCUMENT_KIND_INVOICE,
|
||||
'',
|
||||
mb_substr($name, 0, 120),
|
||||
$stored,
|
||||
'application/pdf',
|
||||
strlen($bytes),
|
||||
'upload',
|
||||
utc_now(),
|
||||
$userId,
|
||||
]);
|
||||
|
||||
return document_find((int) db()->lastInsertId()) ?? [];
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Versand */
|
||||
|
||||
/** Verschickt eine Unterlage als PDF-Anhang an den Kunden. */
|
||||
function document_mail_to_customer(array $booking, array $doc): bool
|
||||
{
|
||||
if (!mail_is_enabled()) {
|
||||
throw new RuntimeException('Der E-Mail-Versand ist nicht aktiviert (app.mail_enabled).');
|
||||
}
|
||||
$to = trim((string) $booking['email']);
|
||||
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||
throw new RuntimeException('Für diese Buchung ist keine gültige E-Mail-Adresse hinterlegt.');
|
||||
}
|
||||
$path = document_path($doc);
|
||||
if (!is_file($path)) {
|
||||
throw new RuntimeException('Die Datei fehlt.');
|
||||
}
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$label = document_kind_label((string) $doc['kind']);
|
||||
$subject = $label . ' zur Buchung #' . (int) $booking['id'] . ' · '
|
||||
. (string) $booking['trailer_label'] . ' · ' . fmt_date_short((string) $booking['start_date']);
|
||||
|
||||
$body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n"
|
||||
. 'anbei erhalten Sie ' . ($doc['kind'] === DOCUMENT_KIND_CONTRACT ? 'den' : 'die') . ' ' . $label
|
||||
. ' zu Ihrer Buchung.' . "\n\n"
|
||||
. 'Mietgegenstand: ' . (string) $booking['trailer_label'] . "\n"
|
||||
. 'Zeitraum: ' . 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) . "\n\n"
|
||||
. 'Bei Fragen einfach auf diese E-Mail antworten.' . "\n\n"
|
||||
. 'Freundliche Grüße' . "\n" . $owner . "\n" . (string) $legal['business_name'] . "\n"
|
||||
. (string) $legal['phone'] . ' · ' . (string) $legal['email'];
|
||||
|
||||
$ok = mail_send_attachment($to, $subject, $body, (string) $doc['file_name'], 'application/pdf', (string) file_get_contents($path));
|
||||
if ($ok) {
|
||||
db()->prepare('UPDATE booking_documents SET mailed_at = ? WHERE id = ?')->execute([utc_now(), (int) $doc['id']]);
|
||||
}
|
||||
return $ok;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- Löschen */
|
||||
|
||||
function document_delete(int $id): void
|
||||
{
|
||||
$doc = document_find($id);
|
||||
if (!$doc) {
|
||||
return;
|
||||
}
|
||||
db()->prepare('DELETE FROM booking_documents WHERE id = ?')->execute([$id]);
|
||||
foreach ([document_path($doc), document_signature_path($doc)] as $path) {
|
||||
if ($path !== null && is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht Unterlagen einen Monat nach dem Mietende sowie verwaiste Dateien.
|
||||
*
|
||||
* @return array{rows: int, files: int}
|
||||
*/
|
||||
function documents_cleanup(): array
|
||||
{
|
||||
$days = max(0, (int) config('app.document_retention_days', 30));
|
||||
$cutoff = add_days(today_iso(), -$days);
|
||||
$result = ['rows' => 0, 'files' => 0];
|
||||
|
||||
if (!documents_schema_ready()) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'SELECT d.* FROM booking_documents d JOIN bookings b ON b.id = d.booking_id WHERE b.end_date < ?'
|
||||
);
|
||||
$stmt->execute([$cutoff]);
|
||||
foreach ($stmt->fetchAll() as $doc) {
|
||||
document_delete((int) $doc['id']);
|
||||
$result['rows']++;
|
||||
}
|
||||
|
||||
// Dateien gelöschter Buchungen und verwaiste Ordner mit aufräumen.
|
||||
$root = document_store_root();
|
||||
if (!is_dir($root)) {
|
||||
return $result;
|
||||
}
|
||||
$known = db()->query('SELECT DISTINCT booking_id FROM booking_documents')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$known = array_map('intval', $known);
|
||||
foreach (scandir($root) ?: [] as $entry) {
|
||||
if ($entry === '.' || $entry === '..' || !ctype_digit($entry)) {
|
||||
continue;
|
||||
}
|
||||
if (in_array((int) $entry, $known, true)) {
|
||||
continue;
|
||||
}
|
||||
foreach (glob($root . '/' . $entry . '/*') ?: [] as $file) {
|
||||
if (is_file($file) && @unlink($file)) {
|
||||
$result['files']++;
|
||||
}
|
||||
}
|
||||
@rmdir($root . '/' . $entry);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
47
app/mail.php
47
app/mail.php
|
|
@ -54,6 +54,53 @@ function mail_send(string $to, string $subject, string $body, array $extraHeader
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt eine Textnachricht mit einem Dateianhang (multipart/mixed).
|
||||
*
|
||||
* Gedacht für Buchungsunterlagen (Mietvertrag, Auftragsbestätigung, Rechnung).
|
||||
* Der Anhang wird Base64-kodiert; Dateiname und MIME-Typ kommen vom Aufrufer.
|
||||
*/
|
||||
function mail_send_attachment(
|
||||
string $to,
|
||||
string $subject,
|
||||
string $body,
|
||||
string $fileName,
|
||||
string $mimeType,
|
||||
string $data
|
||||
): bool {
|
||||
if (!filter_var($to, FILTER_VALIDATE_EMAIL) || $data === '') {
|
||||
return false;
|
||||
}
|
||||
$safeName = trim((string) preg_replace('/[\r\n"]+/', '', $fileName));
|
||||
$safeType = trim((string) preg_replace('/[\r\n]+/', '', $mimeType));
|
||||
$boundary = 'dic-' . bin2hex(random_bytes(12));
|
||||
$headers = [
|
||||
'From: ' . (string) config('app.mail_from', 'Drink it cold <noreply@localhost>'),
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
|
||||
];
|
||||
$parts = [
|
||||
'--' . $boundary,
|
||||
'Content-Type: text/plain; charset=UTF-8',
|
||||
'Content-Transfer-Encoding: 8bit',
|
||||
'',
|
||||
$body,
|
||||
'--' . $boundary,
|
||||
'Content-Type: ' . $safeType . '; name="' . $safeName . '"',
|
||||
'Content-Transfer-Encoding: base64',
|
||||
'Content-Disposition: attachment; filename="' . $safeName . '"',
|
||||
'',
|
||||
chunk_split(base64_encode($data), 76, "\r\n"),
|
||||
'--' . $boundary . '--',
|
||||
];
|
||||
return @mail(
|
||||
$to,
|
||||
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
|
||||
implode("\r\n", $parts),
|
||||
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
|
||||
|
|
|
|||
90
app/migrate.php
Normal file
90
app/migrate.php
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Schema-Migrationen anwenden.
|
||||
*
|
||||
* Wird von tools/migrate.php (CLI) und von der Route /migrate?token=… genutzt.
|
||||
* Letztere gibt es, weil auf dem netcup-Webhosting kein SSH zur Verfügung
|
||||
* steht: Nach `tools/deploy.sh --target netcup --sync` zieht
|
||||
* curl -sS "https://drinkitcold.com/migrate?token=<app.cron_token>"
|
||||
* die ausstehenden Migrationen nach.
|
||||
*
|
||||
* Migrationen sind additiv und werden über schema_migrations genau einmal
|
||||
* ausgeführt; ein erneuter Aufruf ist gefahrlos.
|
||||
*/
|
||||
|
||||
/** @return list<int> */
|
||||
function migrations_applied(): array
|
||||
{
|
||||
return array_map('intval', db()->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
|
||||
}
|
||||
|
||||
/** @return array<string, string> Dateiname => SQL (nur ausstehende) */
|
||||
function migrations_pending(): array
|
||||
{
|
||||
db()->exec(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INT UNSIGNED NOT NULL,
|
||||
applied_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
|
||||
);
|
||||
$applied = migrations_applied();
|
||||
$files = glob(DIC_ROOT . '/sql/migrations/*.sql') ?: [];
|
||||
sort($files, SORT_STRING);
|
||||
|
||||
$pending = [];
|
||||
foreach ($files as $file) {
|
||||
$name = basename($file);
|
||||
if (!preg_match('/^(\d+)_/', $name, $match)) {
|
||||
continue;
|
||||
}
|
||||
if (in_array((int) $match[1], $applied, true)) {
|
||||
continue;
|
||||
}
|
||||
$pending[$name] = (string) file_get_contents($file);
|
||||
}
|
||||
return $pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt alle ausstehenden Migrationen aus.
|
||||
*
|
||||
* @return array{applied: list<string>, skipped: list<string>}
|
||||
*/
|
||||
function migrations_run(): array
|
||||
{
|
||||
$result = ['applied' => [], 'skipped' => []];
|
||||
foreach (migrations_pending() as $name => $sql) {
|
||||
preg_match('/^(\d+)_/', $name, $match);
|
||||
$version = (int) $match[1];
|
||||
// Kommentare entfernen und an Semikola trennen (wie tools/migrate.php).
|
||||
$clean = (string) preg_replace('/^\s*--.*$/m', '', $sql);
|
||||
$statements = array_filter(array_map('trim', explode(';', $clean)));
|
||||
if ($statements === []) {
|
||||
$result['skipped'][] = $name;
|
||||
continue;
|
||||
}
|
||||
foreach ($statements as $statement) {
|
||||
if ($statement === '') {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
db()->exec($statement);
|
||||
} catch (PDOException $error) {
|
||||
// "Gibt es schon": Bei einem frisch installierten Schema sind
|
||||
// Spalten/Tabellen früherer Migrationen bereits vorhanden
|
||||
// (install.php spielt schema.sql ein). Das gilt als erledigt.
|
||||
if (in_array((int) ($error->errorInfo[1] ?? 0), [1050, 1060, 1061, 1091], true)) {
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException($name . ': ' . $error->getMessage(), 0, $error);
|
||||
}
|
||||
}
|
||||
db()->prepare('INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)')
|
||||
->execute([$version, utc_now()]);
|
||||
$result['applied'][] = $name;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
194
app/pages.php
194
app/pages.php
|
|
@ -58,10 +58,14 @@ function page_handle(string $method, string $path): void
|
|||
page_invite($method, $m[1]);
|
||||
return;
|
||||
}
|
||||
if ($path === '/impressum' || $path === '/datenschutz') {
|
||||
if (in_array($path, ['/impressum', '/datenschutz', '/agb'], true)) {
|
||||
legal_page(substr($path, 1));
|
||||
return;
|
||||
}
|
||||
if ($path === '/migrate') {
|
||||
cron_migrate();
|
||||
return;
|
||||
}
|
||||
if ($path === '/anfrage') {
|
||||
page_inquiry($method);
|
||||
return;
|
||||
|
|
@ -139,6 +143,22 @@ function page_handle(string $method, string $path): void
|
|||
page_booking_move($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/documents$#', $path, $m) === 1) {
|
||||
page_booking_documents_create($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/documents/rechnung$#', $path, $m) === 1) {
|
||||
page_booking_document_invoice_upload($user, (int) $m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/documents/(\d+)$#', $path, $m) === 1) {
|
||||
page_booking_document_file($user, (int) $m[1], (int) $m[2]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/bookings/(\d+)/documents/(\d+)/(sign|mail|delete)$#', $path, $m) === 1) {
|
||||
page_booking_document_action($user, $method, (int) $m[1], (int) $m[2], (string) $m[3]);
|
||||
return;
|
||||
}
|
||||
if ($path === '/api/availability') {
|
||||
api_availability();
|
||||
return;
|
||||
|
|
@ -210,10 +230,11 @@ 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 Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
|
||||
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle, %d Buchungsunterlagen entfernt%s.\n",
|
||||
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
|
||||
$cleanup['reminder_mail_log'],
|
||||
$cleanup['reminder_push_log'], $cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
|
||||
$cleanup['reminder_push_log'], $cleanup['booking_documents'],
|
||||
$cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
|
||||
);
|
||||
if (!push_is_configured()) {
|
||||
echo "Push: nicht konfiguriert (VAPID-Schlüssel fehlen).\n";
|
||||
|
|
@ -238,6 +259,35 @@ function cron_reminders(): void
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schema-Migrationen per HTTP anstoßen (Token = app.cron_token).
|
||||
*
|
||||
* Auf dem Webhosting gibt es kein SSH; nach einem Sync ruft das Deployment
|
||||
* diese Route auf, damit neue Migrationen auf der Live-DB landen.
|
||||
*/
|
||||
function cron_migrate(): void
|
||||
{
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
$expected = trim((string) config('app.cron_token', ''));
|
||||
$token = query_string('token');
|
||||
if ($expected === '' || $token === '' || !hash_equals($expected, $token)) {
|
||||
http_response_code(403);
|
||||
echo "Kein Zugriff.\n";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$result = migrations_run();
|
||||
echo $result['applied'] === []
|
||||
? "Keine ausstehenden Migrationen.\n"
|
||||
: 'Migrationen angewendet: ' . implode(', ', $result['applied']) . "\n";
|
||||
} catch (Throwable $error) {
|
||||
error_log('Migration: ' . $error->getMessage());
|
||||
http_response_code(500);
|
||||
echo 'Fehler: ' . $error->getMessage() . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- Anmeldung */
|
||||
|
||||
function page_login(string $method): void
|
||||
|
|
@ -888,6 +938,13 @@ function booking_detail_context(array $booking, array $user): array
|
|||
'canEdit' => auth_can_edit_booking($user),
|
||||
'canCancel' => auth_can_cancel_booking($user),
|
||||
'canEditBilling' => $isAdmin,
|
||||
'documents' => documents_for_booking((int) $booking['id']),
|
||||
'documentVariants' => document_variants(),
|
||||
'documentVariantDefault' => document_variant_default($booking),
|
||||
'canManageDocuments' => auth_can_edit_booking($user),
|
||||
'canDeleteDocuments' => $isAdmin,
|
||||
'documentsMailEnabled' => mail_is_enabled(),
|
||||
'documentsRetentionDays' => max(0, (int) config('app.document_retention_days', 30)),
|
||||
];
|
||||
}
|
||||
|
||||
|
|
@ -992,6 +1049,137 @@ function page_booking_move(array $user, int $id): void
|
|||
json_response($result);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Buchungsunterlagen */
|
||||
|
||||
function booking_or_404(int $id): array
|
||||
{
|
||||
$booking = booking_find($id);
|
||||
if (!$booking) {
|
||||
abort_page(404, 'Buchung nicht gefunden.');
|
||||
}
|
||||
return $booking;
|
||||
}
|
||||
|
||||
/** Erzeugt Mietvertrag oder Auftragsbestätigung in der gewählten Variante. */
|
||||
function page_booking_documents_create(array $user, int $id): void
|
||||
{
|
||||
require_post();
|
||||
$booking = booking_or_404($id);
|
||||
if (!auth_can_edit_booking($user)) {
|
||||
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
|
||||
}
|
||||
$kind = post_string('kind');
|
||||
$variant = post_string('variant');
|
||||
if (!in_array($kind, [DOCUMENT_KIND_CONTRACT, DOCUMENT_KIND_CONFIRMATION], true)) {
|
||||
flash('error', 'Unbekannte Unterlagen-Art.');
|
||||
redirect('/bookings/' . $id . '#unterlagen');
|
||||
}
|
||||
try {
|
||||
document_create($booking, $kind, $variant, (int) $user['id']);
|
||||
flash('success', document_kind_label($kind) . ' erstellt – zum Drucken öffnen oder direkt versenden.');
|
||||
} catch (Throwable $error) {
|
||||
flash('error', $error->getMessage());
|
||||
}
|
||||
redirect('/bookings/' . $id . '#unterlagen');
|
||||
}
|
||||
|
||||
/** Liefert die PDF-Datei einer Unterlage aus (nur angemeldet, nie öffentlich). */
|
||||
function page_booking_document_file(array $user, int $bookingId, int $docId): void
|
||||
{
|
||||
$doc = document_find($docId);
|
||||
if (!$doc || (int) $doc['booking_id'] !== $bookingId) {
|
||||
abort_page(404, 'Unterlage nicht gefunden.');
|
||||
}
|
||||
$path = document_path($doc);
|
||||
if (!is_file($path)) {
|
||||
abort_page(404, 'Die Datei ist nicht mehr vorhanden.');
|
||||
}
|
||||
$download = query_string('download') === '1';
|
||||
$name = (string) preg_replace('/[\r\n"]+/', '', (string) $doc['file_name']);
|
||||
header('Content-Type: ' . (string) $doc['mime_type']);
|
||||
header('Content-Length: ' . (string) filesize($path));
|
||||
header('Content-Disposition: ' . ($download ? 'attachment' : 'inline') . '; filename="' . $name . '"');
|
||||
header('Cache-Control: private, no-store');
|
||||
readfile($path);
|
||||
exit;
|
||||
}
|
||||
|
||||
/** Unterschrift auf dem Tablet, Mailversand und Löschen einer Unterlage. */
|
||||
function page_booking_document_action(array $user, string $method, int $bookingId, int $docId, string $action): void
|
||||
{
|
||||
$booking = booking_or_404($bookingId);
|
||||
$doc = document_find($docId);
|
||||
if (!$doc || (int) $doc['booking_id'] !== $bookingId) {
|
||||
abort_page(404, 'Unterlage nicht gefunden.');
|
||||
}
|
||||
|
||||
if ($action === 'sign') {
|
||||
if (!auth_can_edit_booking($user)) {
|
||||
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
|
||||
}
|
||||
if ($method === 'GET') {
|
||||
render_standalone('document_sign', [
|
||||
'booking' => $booking,
|
||||
'doc' => $doc,
|
||||
'pageTitle' => 'Unterschrift Mietvertrag',
|
||||
], 'Unterschrift · ' . $booking['customer_name']);
|
||||
return;
|
||||
}
|
||||
require_post();
|
||||
try {
|
||||
document_save_signature($booking, $doc, post_string('signature'), (int) $user['id']);
|
||||
flash('success', 'Unterschrift gespeichert und in den Mietvertrag übernommen.');
|
||||
} catch (Throwable $error) {
|
||||
flash('error', $error->getMessage());
|
||||
}
|
||||
redirect('/bookings/' . $bookingId . '#unterlagen');
|
||||
}
|
||||
|
||||
require_post();
|
||||
if ($action === 'mail') {
|
||||
if (!auth_can_edit_booking($user)) {
|
||||
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
|
||||
}
|
||||
try {
|
||||
$sent = document_mail_to_customer($booking, $doc);
|
||||
$sent
|
||||
? flash('success', document_kind_label((string) $doc['kind']) . ' an ' . $booking['email'] . ' gesendet.')
|
||||
: flash('error', 'Die E-Mail konnte nicht verschickt werden.');
|
||||
} catch (Throwable $error) {
|
||||
flash('error', $error->getMessage());
|
||||
}
|
||||
redirect('/bookings/' . $bookingId . '#unterlagen');
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
if (!auth_can_manage($user)) {
|
||||
abort_page(403, 'Unterlagen darf nur der Admin löschen.');
|
||||
}
|
||||
document_delete($docId);
|
||||
flash('success', 'Unterlage gelöscht.');
|
||||
redirect('/bookings/' . $bookingId . '#unterlagen');
|
||||
}
|
||||
|
||||
abort_page(404, 'Diese Aktion gibt es nicht.');
|
||||
}
|
||||
|
||||
/** Rechnung (PDF aus Lexware) zur Buchung hochladen. */
|
||||
function page_booking_document_invoice_upload(array $user, int $id): void
|
||||
{
|
||||
require_post();
|
||||
$booking = booking_or_404($id);
|
||||
if (!auth_can_edit_booking($user)) {
|
||||
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
|
||||
}
|
||||
try {
|
||||
document_upload_invoice($booking, (array) ($_FILES['invoice'] ?? []), (int) $user['id']);
|
||||
flash('success', 'Rechnung abgelegt.');
|
||||
} catch (Throwable $error) {
|
||||
flash('error', $error->getMessage());
|
||||
}
|
||||
redirect('/bookings/' . $id . '#unterlagen');
|
||||
}
|
||||
|
||||
function api_availability(): void
|
||||
{
|
||||
auth_require_login();
|
||||
|
|
|
|||
343
app/pdf.php
Normal file
343
app/pdf.php
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Kleiner PDF-Erzeuger ohne externe Abhängigkeiten.
|
||||
*
|
||||
* Auf dem Hosting steht keine Composer-Bibliothek (mPDF/TCPDF) zur Verfügung,
|
||||
* deshalb erzeugt diese Klasse PDF 1.4 selbst: Helvetica als Kernschrift,
|
||||
* Text in CP1252 (deckt deutsche Umlaute ab), Linien, Rechtecke und eingebettete
|
||||
* JPEG-Bilder (z. B. die Unterschrift vom Tablet).
|
||||
*
|
||||
* Koordinaten werden in Punkten von links oben angegeben; die Umrechnung ins
|
||||
* PDF-Koordinatensystem (Ursprung links unten) passiert intern.
|
||||
*/
|
||||
final class PdfDoc
|
||||
{
|
||||
public const A4_W = 595.28;
|
||||
public const A4_H = 841.89;
|
||||
|
||||
/** Zeichenbreiten Helvetica (Einheiten/1000) für ASCII 32–126. */
|
||||
private const W_REGULAR = [
|
||||
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
|
||||
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
|
||||
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
|
||||
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584,
|
||||
];
|
||||
|
||||
/** Zeichenbreiten Helvetica-Bold (Einheiten/1000) für ASCII 32–126. */
|
||||
private const W_BOLD = [
|
||||
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
|
||||
975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556,
|
||||
333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611,
|
||||
611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
|
||||
];
|
||||
|
||||
private float $width;
|
||||
private float $height;
|
||||
/** @var list<string> */
|
||||
private array $pages = [];
|
||||
private string $stream = '';
|
||||
/** @var array<string, array{data: string, w: int, h: int, gray: bool}> */
|
||||
private array $images = [];
|
||||
|
||||
public function __construct(float $width = self::A4_W, float $height = self::A4_H)
|
||||
{
|
||||
$this->width = $width;
|
||||
$this->height = $height;
|
||||
}
|
||||
|
||||
public function pageWidth(): float
|
||||
{
|
||||
return $this->width;
|
||||
}
|
||||
|
||||
public function pageHeight(): float
|
||||
{
|
||||
return $this->height;
|
||||
}
|
||||
|
||||
/** Nummer der aktuell offenen Seite (1-basiert). */
|
||||
public function pageNo(): int
|
||||
{
|
||||
return count($this->pages) + 1;
|
||||
}
|
||||
|
||||
public function newPage(): void
|
||||
{
|
||||
$this->pages[] = $this->stream;
|
||||
$this->stream = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibt Text. $top ist der Abstand der Grundlinie vom oberen Rand.
|
||||
* $align: left|right|center – bezogen auf $boxWidth ab Position $x.
|
||||
*/
|
||||
public function text(
|
||||
float $x,
|
||||
float $top,
|
||||
float $size,
|
||||
string $text,
|
||||
bool $bold = false,
|
||||
string $align = 'left',
|
||||
?float $boxWidth = null
|
||||
): void {
|
||||
if ($text === '') {
|
||||
return;
|
||||
}
|
||||
$encoded = self::encode($text);
|
||||
if ($align !== 'left' && $boxWidth !== null) {
|
||||
$w = $this->measure($text, $size, $bold);
|
||||
$x += $align === 'right' ? $boxWidth - $w : ($boxWidth - $w) / 2;
|
||||
}
|
||||
$y = $this->height - $top;
|
||||
$font = $bold ? 'F2' : 'F1';
|
||||
$this->stream .= sprintf(
|
||||
"BT /%s %.2F Tf 1 0 0 1 %.2F %.2F Tm (%s) Tj ET\n",
|
||||
$font,
|
||||
$size,
|
||||
$x,
|
||||
$y,
|
||||
self::escape($encoded)
|
||||
);
|
||||
}
|
||||
|
||||
public function measure(string $text, float $size, bool $bold = false): float
|
||||
{
|
||||
$encoded = self::encode($text);
|
||||
$table = $bold ? self::W_BOLD : self::W_REGULAR;
|
||||
$total = 0;
|
||||
$len = strlen($encoded);
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$code = ord($encoded[$i]);
|
||||
$total += ($code >= 32 && $code <= 126) ? $table[$code - 32] : ($bold ? 611 : 556);
|
||||
}
|
||||
return $total * $size / 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bricht Text auf die angegebene Breite um (Wortgrenzen, harte Umbrüche).
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function wrap(string $text, float $size, float $maxWidth, bool $bold = false): array
|
||||
{
|
||||
$limit = $maxWidth * 0.985;
|
||||
$lines = [];
|
||||
foreach (preg_split('/\R/', $text) ?: [] as $rawLine) {
|
||||
$words = preg_split('/\s+/', trim($rawLine)) ?: [];
|
||||
if ($words === []) {
|
||||
$lines[] = '';
|
||||
continue;
|
||||
}
|
||||
$current = '';
|
||||
foreach ($words as $word) {
|
||||
$candidate = $current === '' ? $word : $current . ' ' . $word;
|
||||
if ($current !== '' && $this->measure($candidate, $size, $bold) > $limit) {
|
||||
$lines[] = $current;
|
||||
$current = $word;
|
||||
continue;
|
||||
}
|
||||
$current = $candidate;
|
||||
}
|
||||
$lines[] = $current;
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibt umbrochenen Text ab $top und liefert die nächste freie Grundlinie.
|
||||
*/
|
||||
public function paragraph(
|
||||
float $x,
|
||||
float $top,
|
||||
float $maxWidth,
|
||||
float $size,
|
||||
string $text,
|
||||
bool $bold = false,
|
||||
float $lineHeight = 0.0
|
||||
): float {
|
||||
$leading = $lineHeight > 0 ? $lineHeight : $size * 1.42;
|
||||
$y = $top;
|
||||
foreach ($this->wrap($text, $size, $maxWidth, $bold) as $line) {
|
||||
$this->text($x, $y, $size, $line, $bold);
|
||||
$y += $leading;
|
||||
}
|
||||
return $y;
|
||||
}
|
||||
|
||||
public function line(float $x1, float $top1, float $x2, float $top2, float $lw = 0.6): void
|
||||
{
|
||||
$this->stream .= sprintf(
|
||||
"%.2F w %.2F %.2F m %.2F %.2F l S\n",
|
||||
$lw,
|
||||
$x1,
|
||||
$this->height - $top1,
|
||||
$x2,
|
||||
$this->height - $top2
|
||||
);
|
||||
}
|
||||
|
||||
public function rect(float $x, float $top, float $w, float $h, bool $fill = false, float $lw = 0.6): void
|
||||
{
|
||||
$y = $this->height - $top - $h;
|
||||
$this->stream .= $fill
|
||||
? sprintf("0.94 0.96 0.98 rg %.2F %.2F %.2F %.2F re f 0 0 0 rg\n", $x, $y, $w, $h)
|
||||
: sprintf("%.2F w %.2F %.2F %.2F %.2F re S\n", $lw, $x, $y, $w, $h);
|
||||
}
|
||||
|
||||
/** Bettet ein JPEG ein (für Unterschriften aus dem Browser-Canvas). */
|
||||
public function image(string $file, float $x, float $top, float $w, float $h): bool
|
||||
{
|
||||
$data = @file_get_contents($file);
|
||||
if (!is_string($data) || strncmp($data, "\xFF\xD8", 2) !== 0) {
|
||||
return false;
|
||||
}
|
||||
$size = self::jpeg_size($data);
|
||||
if ($size === null) {
|
||||
return false;
|
||||
}
|
||||
$name = 'Im' . (count($this->images) + 1);
|
||||
$this->images[$name] = [
|
||||
'data' => $data,
|
||||
'w' => $size[0],
|
||||
'h' => $size[1],
|
||||
'gray' => $size[2] === 1,
|
||||
];
|
||||
$this->stream .= sprintf(
|
||||
"q %.2F 0 0 %.2F %.2F %.2F cm /%s Do Q\n",
|
||||
$w,
|
||||
$h,
|
||||
$x,
|
||||
$this->height - $top - $h,
|
||||
$name
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function output(): string
|
||||
{
|
||||
$pages = $this->pages;
|
||||
if (trim($this->stream) !== '' || $pages === []) {
|
||||
$pages[] = $this->stream;
|
||||
}
|
||||
|
||||
$objects = [];
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
|
||||
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
|
||||
|
||||
$next = 5;
|
||||
$imageRefs = [];
|
||||
foreach ($this->images as $name => $image) {
|
||||
$imageRefs[$name] = $next;
|
||||
$objects[$next] = '<< /Type /XObject /Subtype /Image'
|
||||
. ' /Width ' . $image['w'] . ' /Height ' . $image['h']
|
||||
. ' /ColorSpace /' . ($image['gray'] ? 'DeviceGray' : 'DeviceRGB')
|
||||
. ' /BitsPerComponent 8 /Filter /DCTDecode /Length ' . strlen($image['data']) . " >>\nstream\n"
|
||||
. $image['data'] . "\nendstream";
|
||||
$next++;
|
||||
}
|
||||
|
||||
$xobjects = '';
|
||||
foreach ($imageRefs as $name => $id) {
|
||||
$xobjects .= '/' . $name . ' ' . $id . ' 0 R ';
|
||||
}
|
||||
|
||||
$kids = [];
|
||||
foreach ($pages as $content) {
|
||||
$compressed = gzcompress($content, 6);
|
||||
$contentId = $next++;
|
||||
$objects[$contentId] = '<< /Filter /FlateDecode /Length ' . strlen($compressed) . " >>\nstream\n"
|
||||
. $compressed . "\nendstream";
|
||||
$pageId = $next++;
|
||||
$objects[$pageId] = '<< /Type /Page /Parent 2 0 R'
|
||||
. sprintf(' /MediaBox [0 0 %.2F %.2F]', $this->width, $this->height)
|
||||
. ' /Resources << /Font << /F1 3 0 R /F2 4 0 R >> /XObject << ' . $xobjects . '>> >>'
|
||||
. ' /Contents ' . $contentId . ' 0 R >>';
|
||||
$kids[] = $pageId . ' 0 R';
|
||||
}
|
||||
|
||||
$objects[2] = '<< /Type /Pages /Kids [' . implode(' ', $kids) . '] /Count ' . count($kids) . ' >>';
|
||||
ksort($objects);
|
||||
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [];
|
||||
foreach ($objects as $id => $body) {
|
||||
$offsets[$id] = strlen($pdf);
|
||||
$pdf .= $id . " 0 obj\n" . $body . "\nendobj\n";
|
||||
}
|
||||
|
||||
$xref = strlen($pdf);
|
||||
$maxId = max(array_keys($objects));
|
||||
$pdf .= "xref\n0 " . ($maxId + 1) . "\n0000000000 65535 f \n";
|
||||
for ($id = 1; $id <= $maxId; $id++) {
|
||||
$pdf .= isset($offsets[$id]) ? sprintf("%010d 00000 n \n", $offsets[$id]) : "0000000000 65535 f \n";
|
||||
}
|
||||
$pdf .= "trailer\n<< /Size " . ($maxId + 1) . " /Root 1 0 R >>\nstartxref\n" . $xref . "\n%%EOF\n";
|
||||
|
||||
return $pdf;
|
||||
}
|
||||
|
||||
private static function encode(string $text): string
|
||||
{
|
||||
if ($text === '') {
|
||||
return '';
|
||||
}
|
||||
$out = @iconv('UTF-8', 'CP1252//TRANSLIT', $text);
|
||||
if ($out === false) {
|
||||
$out = (string) preg_replace('/[^\x20-\x7E]/', '?', $text);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function escape(string $encoded): string
|
||||
{
|
||||
return str_replace(['\\', '(', ')', "\r", "\n"], ['\\\\', '\\(', '\\)', '', ''], $encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest Breite, Höhe und Farbkanäle eines JPEG aus dem SOF-Segment.
|
||||
*
|
||||
* @return array{0: int, 1: int, 2: int}|null
|
||||
*/
|
||||
private static function jpeg_size(string $data): ?array
|
||||
{
|
||||
$len = strlen($data);
|
||||
$i = 2;
|
||||
while ($i + 3 < $len) {
|
||||
if ($data[$i] !== "\xFF") {
|
||||
$i++;
|
||||
continue;
|
||||
}
|
||||
$marker = ord($data[$i + 1]);
|
||||
if ($marker === 0xD8 || $marker === 0x01 || ($marker >= 0xD0 && $marker <= 0xD7)) {
|
||||
$i += 2;
|
||||
continue;
|
||||
}
|
||||
if ($i + 4 >= $len) {
|
||||
return null;
|
||||
}
|
||||
$length = (ord($data[$i + 2]) << 8) | ord($data[$i + 3]);
|
||||
$isSof = $marker >= 0xC0 && $marker <= 0xCF && !in_array($marker, [0xC4, 0xC8, 0xCC], true);
|
||||
if ($isSof) {
|
||||
if ($i + 9 >= $len) {
|
||||
return null;
|
||||
}
|
||||
$height = (ord($data[$i + 5]) << 8) | ord($data[$i + 6]);
|
||||
$width = (ord($data[$i + 7]) << 8) | ord($data[$i + 8]);
|
||||
$channels = ord($data[$i + 9]);
|
||||
if ($width < 1 || $height < 1) {
|
||||
return null;
|
||||
}
|
||||
return [$width, $height, $channels];
|
||||
}
|
||||
$i += 2 + $length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,7 @@ function privacy_cleanup(): array
|
|||
'user_invites' => 0,
|
||||
'reminder_mail_log' => 0,
|
||||
'reminder_push_log' => 0,
|
||||
'booking_documents' => 0,
|
||||
'log_rotated' => false,
|
||||
];
|
||||
|
||||
|
|
@ -43,6 +44,12 @@ function privacy_cleanup(): array
|
|||
[utc_after(-365 * 86400)]
|
||||
);
|
||||
|
||||
// Buchungsunterlagen (Mietvertrag, Auftragsbestätigung, Rechnung) werden
|
||||
// einen Monat nach dem Mietende gelöscht – so kurz wie mit dem Kunden
|
||||
// vereinbart (app.document_retention_days).
|
||||
$documents = documents_cleanup();
|
||||
$result['booking_documents'] = (int) $documents['rows'];
|
||||
|
||||
$result['log_rotated'] = privacy_rotate_error_log();
|
||||
return $result;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue