Kundenwunsch vom 04.12.2026 (docs/auftraege): - Kaution je Buchung (bookings.deposit_amount_cents, Standard 100 €, 0 = keine) statt globaler Konfiguration; Voreinstellungen im Formular angepasst. - Auftragsbestätigung rechnet Kaution nicht mehr in Gesamt/Restbetrag ein, zeigt sie als "in bar"-Hinweis unter dem Zahlungseingang, Verwendungszweck "#Buchungsnummer Name", Hinweis auf Anruf 8–10 Tage vor dem Termin. - Mietvertrag mit drei Unterschriften (Migration 021, document_signatures): Mitarbeiter bestätigt Zahlungseingang, Kunde Übernahme, Kunde Kautionsrückgabe; Zusatzvereinbarungen werden im Vertrag abgedruckt. - Zahlungserinnerung ebenfalls ohne Kaution im Betrag. - Mail-Fuß mit Signaturblock und Antwort-Sperrhinweis, Betreffzeilen mit Buchungsnummer und Mietgegenstand (ohne Anhängernummer), Wochentag in Datumsangaben. - Aufbewahrung: ohne Rechnung 30 Tage, mit Rechnung Mietvertrag 8 Jahre; Jahresarchiv der Mietverträge (app/export.php, Verwaltung → Sicherungen). - Automatische Bewertungsmail eine Woche nach Rückgabe (Migration 022). - Mehrfachvermietung: "Weiterer Anhänger für diesen Kunden" (/bookings/new?from=ID). Migrationen 020–022 sind lokal gelaufen; PDF-Erzeugung, Unterschrifts-Lebenszyklus und Jahresexport getestet.
1800 lines
70 KiB
PHP
1800 lines
70 KiB
PHP
<?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: documents_cleanup() löscht die Dateien abhängig von der Art
|
||
* gestaffelt nach dem Mietende (app.document_retention_days, siehe
|
||
* document_retention_days()).
|
||
*/
|
||
|
||
const DOCUMENT_KIND_CONTRACT = 'contract';
|
||
const DOCUMENT_KIND_CONFIRMATION = 'confirmation';
|
||
const DOCUMENT_KIND_INVOICE = 'invoice';
|
||
const DOCUMENT_KIND_REMINDER = 'reminder';
|
||
|
||
/**
|
||
* Rollen der Unterschriften im Mietvertrag (Tabelle document_signatures).
|
||
* handover = Mitarbeiter bei der Übergabe (Zahlung erhalten),
|
||
* customer = Kunde bei der Übernahme, return = Kunde bei der Rückgabe
|
||
* (Kaution zurückerhalten).
|
||
*/
|
||
const DOCUMENT_SIGN_HANDOVER = 'handover';
|
||
const DOCUMENT_SIGN_CUSTOMER = 'customer';
|
||
const DOCUMENT_SIGN_RETURN = 'return';
|
||
|
||
/** @return array<string, string> */
|
||
function document_sign_roles(): array
|
||
{
|
||
return [
|
||
DOCUMENT_SIGN_HANDOVER => 'Übergabe: Zahlung erhalten (Mitarbeiter)',
|
||
DOCUMENT_SIGN_CUSTOMER => 'Übernahme Mietgegenstand (Kunde)',
|
||
DOCUMENT_SIGN_RETURN => 'Rückgabe: Kaution zurück (Kunde)',
|
||
];
|
||
}
|
||
|
||
function document_sign_role_label(string $role): string
|
||
{
|
||
return document_sign_roles()[$role] ?? $role;
|
||
}
|
||
|
||
/** Kurzform für Status-Pills: Übergabe, Übernahme, Rückgabe. */
|
||
function document_sign_role_short(string $role): string
|
||
{
|
||
return match ($role) {
|
||
DOCUMENT_SIGN_HANDOVER => 'Übergabe',
|
||
DOCUMENT_SIGN_CUSTOMER => 'Übernahme',
|
||
default => 'Rückgabe',
|
||
};
|
||
}
|
||
|
||
function document_sign_role_valid(string $role): bool
|
||
{
|
||
return array_key_exists($role, document_sign_roles());
|
||
}
|
||
|
||
/** Ist die Tabelle für die Unterschriften-Rollen vorhanden (Migration 021)? */
|
||
function document_signatures_schema_ready(): bool
|
||
{
|
||
static $ready = null;
|
||
if ($ready !== null) {
|
||
return $ready;
|
||
}
|
||
try {
|
||
$stmt = db()->query("SHOW TABLES LIKE 'document_signatures'");
|
||
$ready = $stmt !== false && $stmt->fetchColumn() !== false;
|
||
} catch (Throwable) {
|
||
$ready = false;
|
||
}
|
||
return $ready;
|
||
}
|
||
|
||
/**
|
||
* Unterschriften einer Unterlage, nach Rolle. Fällt auf die Kundensignatur in
|
||
* booking_documents zurück, solange Migration 021 noch nicht gelaufen ist.
|
||
*
|
||
* @return array<string, array<string, mixed>>
|
||
*/
|
||
function document_signatures(array $doc): array
|
||
{
|
||
$docId = (int) $doc['id'];
|
||
$result = [];
|
||
if (document_signatures_schema_ready()) {
|
||
$stmt = db()->prepare('SELECT * FROM document_signatures WHERE document_id = ?');
|
||
$stmt->execute([$docId]);
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$result[(string) $row['role']] = $row;
|
||
}
|
||
}
|
||
if (!isset($result[DOCUMENT_SIGN_CUSTOMER]) && trim((string) ($doc['signature_file'] ?? '')) !== '') {
|
||
$result[DOCUMENT_SIGN_CUSTOMER] = [
|
||
'role' => DOCUMENT_SIGN_CUSTOMER,
|
||
'signature_file' => (string) $doc['signature_file'],
|
||
'signed_at' => (string) ($doc['signed_at'] ?? ''),
|
||
'signed_via' => (string) ($doc['signed_via'] ?? 'tablet'),
|
||
];
|
||
}
|
||
return $result;
|
||
}
|
||
|
||
/** @return array<string, string> */
|
||
function document_kinds(): array
|
||
{
|
||
return [
|
||
DOCUMENT_KIND_CONTRACT => 'Mietvertrag',
|
||
DOCUMENT_KIND_CONFIRMATION => 'Auftragsbestätigung',
|
||
DOCUMENT_KIND_REMINDER => 'Zahlungserinnerung',
|
||
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 = match ($kind) {
|
||
DOCUMENT_KIND_CONTRACT => 'Mietvertrag',
|
||
DOCUMENT_KIND_REMINDER => 'Zahlungserinnerung',
|
||
default => '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 ($kind === DOCUMENT_KIND_REMINDER) {
|
||
// Zahlungserinnerungen hängen nicht an der Mietvertrags-Variante; ein
|
||
// fehlendes Bankkonto fällt hier sofort auf und nicht erst im PDF.
|
||
$variant = '';
|
||
document_reminder_account($booking);
|
||
} elseif (!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);
|
||
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));
|
||
if ($kind === DOCUMENT_KIND_REMINDER) {
|
||
$variant = ''; // Erinnerungen haben keine Mietvertrags-Variante.
|
||
}
|
||
$bytes = document_render($booking, $kind, $variant, $doc);
|
||
$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,
|
||
?array $doc = null
|
||
): string {
|
||
return match ($kind) {
|
||
DOCUMENT_KIND_CONFIRMATION => document_confirmation_pdf($booking, $variant),
|
||
DOCUMENT_KIND_REMINDER => document_reminder_pdf($booking),
|
||
default => document_contract_pdf(
|
||
$booking,
|
||
$variant,
|
||
$doc !== null ? document_signatures($doc) : []
|
||
),
|
||
};
|
||
}
|
||
|
||
/* ----------------------------------------------------------- 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);
|
||
}
|
||
|
||
/**
|
||
* Logo-Datei für die PDF-Kopfzeile (PNG mit Transparenz) oder null.
|
||
*
|
||
* Im Repository liegen die Assets unter web/assets/…, auf dem Hosting ist der
|
||
* Inhalt von web/ der DocumentRoot – deshalb beide Pfade prüfen.
|
||
*/
|
||
function document_logo_path(): ?string
|
||
{
|
||
$candidates = [
|
||
'/web/assets/img/logo-drink-it-cold-480.png',
|
||
'/assets/img/logo-drink-it-cold-480.png',
|
||
'/web/assets/img/logo-drink-it-cold.png',
|
||
'/assets/img/logo-drink-it-cold.png',
|
||
];
|
||
foreach ($candidates as $candidate) {
|
||
if (is_file(DIC_ROOT . $candidate)) {
|
||
return DIC_ROOT . $candidate;
|
||
}
|
||
}
|
||
error_log('Dokument: Logo fehlt (gesucht in ' . implode(', ', $candidates) . ' unter ' . DIC_ROOT . ').');
|
||
return null;
|
||
}
|
||
|
||
/** Kopfzeile: Logo oben rechts, Titel links, Kennung rechts über der Linie. */
|
||
function document_pdf_title(PdfDoc $pdf, string $title, string $right): void
|
||
{
|
||
$w = $pdf->pageWidth();
|
||
$logo = document_logo_path();
|
||
if ($logo !== null) {
|
||
// Seitenverhältnis des Logos 480:267 – Breite 54 pt, Höhe passend.
|
||
$pdf->image($logo, $w - 50 - 54.0, 22.0, 54.0, 30.0);
|
||
}
|
||
$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;
|
||
// Lange Firmennamen umbrechen, damit sie nicht in die rechte Spalte laufen.
|
||
$nameLines = $pdf->wrap((string) $booking['customer_name'], 11, $right - $left - 24, true);
|
||
$ownerLines = $pdf->wrap($owner, 11, $pdf->pageWidth() - 50 - $right, true);
|
||
foreach ($nameLines as $i => $line) {
|
||
$pdf->text($left, $y + $i * 13, 11, $line, true);
|
||
}
|
||
foreach ($ownerLines as $i => $line) {
|
||
$pdf->text($right, $y + $i * 13, 11, $line, true);
|
||
}
|
||
$y += (max(count($nameLines), count($ownerLines)) - 1) * 13;
|
||
$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);
|
||
// 10 pt Luft zum Rand: sonst wirkt eine lange Zeile wie abgeschnitten.
|
||
$valueLines = $pdf->wrap((string) $row[1], 10, $right - $valueX - 10, $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;
|
||
}
|
||
|
||
/**
|
||
* Anzahlungskonten (Verwaltung → Konten), sortiert.
|
||
*
|
||
* Der Stamm liegt in der Tabelle deposit_accounts und wird vom Administrator
|
||
* gepflegt; die Auftragsbestätigung druckt das in der Buchung gewählte Konto.
|
||
*
|
||
* @return list<array{id: int, label: string, holder: string, bank: string, iban: string, sort_order: int}>
|
||
*/
|
||
function deposit_accounts(bool $refresh = false): array
|
||
{
|
||
static $cache = null;
|
||
if ($refresh) {
|
||
$cache = null;
|
||
}
|
||
if (is_array($cache)) {
|
||
return $cache;
|
||
}
|
||
$cache = [];
|
||
try {
|
||
$rows = db()->query('SELECT id, label, holder, bank, iban, sort_order FROM deposit_accounts ORDER BY sort_order, id')
|
||
->fetchAll();
|
||
} catch (Throwable) {
|
||
return $cache; // Tabelle fehlt noch (Migration ausstehend)
|
||
}
|
||
foreach ($rows as $row) {
|
||
$cache[] = [
|
||
'id' => (int) $row['id'],
|
||
'label' => (string) $row['label'],
|
||
'holder' => (string) $row['holder'],
|
||
'bank' => (string) $row['bank'],
|
||
'iban' => (string) $row['iban'],
|
||
'sort_order' => (int) $row['sort_order'],
|
||
];
|
||
}
|
||
return $cache;
|
||
}
|
||
|
||
/** Einzelnes Konto; ohne gültige Kennung null. */
|
||
function deposit_account(int $id): ?array
|
||
{
|
||
foreach (deposit_accounts() as $account) {
|
||
if ((int) $account['id'] === $id) {
|
||
return $account;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** Anzeigename inklusive IBAN-Ende, damit zwei Konten unterscheidbar sind. */
|
||
function deposit_account_label(array $account): string
|
||
{
|
||
$iban = preg_replace('/\s+/', '', (string) $account['iban']) ?? '';
|
||
return (string) $account['label'] . ($iban !== '' ? ' (…' . substr($iban, -4) . ')' : '');
|
||
}
|
||
|
||
/** Verzeichnis für die hinterlegte Unterschrift des Vermieters. */
|
||
function owner_signature_dir(): string
|
||
{
|
||
$storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/');
|
||
return $storage . '/signature';
|
||
}
|
||
|
||
/** Pfad der hinterlegten Unterschrift (JPEG) oder null. */
|
||
function owner_signature_path(): ?string
|
||
{
|
||
$file = owner_signature_dir() . '/unterschrift-vermieter.jpg';
|
||
return is_file($file) ? $file : null;
|
||
}
|
||
|
||
function owner_signature_time(): ?string
|
||
{
|
||
$file = owner_signature_path();
|
||
if ($file === null) {
|
||
return null;
|
||
}
|
||
return gmdate('Y-m-d H:i:s', (int) filemtime($file));
|
||
}
|
||
|
||
/**
|
||
* Speichert die im Browser gezeichnete Unterschrift (data:image/jpeg;base64,…).
|
||
* Gilt für alle neu erzeugten Auftragsbestätigungen.
|
||
*/
|
||
function owner_signature_save(string $dataUrl): void
|
||
{
|
||
if (!preg_match('#^data:image/jpeg;base64,([A-Za-z0-9+/=\s]+)$#', trim($dataUrl), $match)) {
|
||
throw new RuntimeException('Die Unterschrift konnte nicht gelesen werden.');
|
||
}
|
||
$binary = base64_decode((string) preg_replace('/\s+/', '', $match[1]), true);
|
||
if (!is_string($binary) || strlen($binary) < 500 || strncmp($binary, "\xFF\xD8", 2) !== 0) {
|
||
throw new RuntimeException('Bitte zuerst unterschreiben.');
|
||
}
|
||
if (strlen($binary) > 1500000) {
|
||
throw new RuntimeException('Die Unterschrift ist zu groß.');
|
||
}
|
||
$dir = owner_signature_dir();
|
||
if (!is_dir($dir) && !@mkdir($dir, 0700, true) && !is_dir($dir)) {
|
||
throw new RuntimeException('Das Verzeichnis für die Unterschrift fehlt.');
|
||
}
|
||
$file = $dir . '/unterschrift-vermieter.jpg';
|
||
if (@file_put_contents($file, $binary) === false) {
|
||
throw new RuntimeException('Die Unterschrift konnte nicht gespeichert werden.');
|
||
}
|
||
@chmod($file, 0600);
|
||
}
|
||
|
||
function owner_signature_delete(): bool
|
||
{
|
||
$file = owner_signature_path();
|
||
return $file !== null && @unlink($file);
|
||
}
|
||
|
||
/** Eingabewerte eines Anzahlungskontos normalisieren. */
|
||
function deposit_account_input(array $source): array
|
||
{
|
||
return [
|
||
'label' => trim((string) ($source['label'] ?? '')),
|
||
'holder' => trim((string) ($source['holder'] ?? '')),
|
||
'bank' => trim((string) ($source['bank'] ?? '')),
|
||
'iban' => mb_strtoupper(trim((string) ($source['iban'] ?? ''))),
|
||
'sort_order' => (int) ($source['sort_order'] ?? 0),
|
||
];
|
||
}
|
||
|
||
/** @return array<string, string> */
|
||
function deposit_account_validate(array $data): array
|
||
{
|
||
$errors = [];
|
||
if ($data['label'] === '') {
|
||
$errors['label'] = 'Bitte eine Bezeichnung angeben (z. B. „Postbank – Michael Schmitz“).';
|
||
} elseif (mb_strlen($data['label']) > 80) {
|
||
$errors['label'] = 'Die Bezeichnung ist zu lang (max. 80 Zeichen).';
|
||
}
|
||
if ($data['holder'] === '') {
|
||
$errors['holder'] = 'Bitte den Kontoinhaber angeben.';
|
||
} elseif (mb_strlen($data['holder']) > 120) {
|
||
$errors['holder'] = 'Der Kontoinhaber ist zu lang (max. 120 Zeichen).';
|
||
}
|
||
if (mb_strlen($data['bank']) > 80) {
|
||
$errors['bank'] = 'Der Bankname ist zu lang (max. 80 Zeichen).';
|
||
}
|
||
$iban = preg_replace('/\s+/', '', $data['iban']) ?? '';
|
||
if ($iban === '') {
|
||
$errors['iban'] = 'Bitte die IBAN angeben.';
|
||
} elseif (mb_strlen($iban) < 15 || mb_strlen($iban) > 34 || preg_match('/^[A-Z]{2}[0-9A-Z]+$/', $iban) !== 1) {
|
||
$errors['iban'] = 'Die IBAN sieht nicht gültig aus (z. B. DE12 1001 0010 0464 1261 30).';
|
||
}
|
||
return $errors;
|
||
}
|
||
|
||
function deposit_account_create(array $data): int
|
||
{
|
||
$errors = deposit_account_validate($data);
|
||
if ($errors !== []) {
|
||
throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE));
|
||
}
|
||
$stmt = db()->prepare(
|
||
'INSERT INTO deposit_accounts (label, holder, bank, iban, sort_order, created_at, updated_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||
);
|
||
$stmt->execute([
|
||
$data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'],
|
||
utc_now(), utc_now(),
|
||
]);
|
||
$id = (int) db()->lastInsertId(); // vor dem Neuladen der Liste lesen
|
||
deposit_accounts(true);
|
||
return $id;
|
||
}
|
||
|
||
function deposit_account_update(int $id, array $data): void
|
||
{
|
||
$errors = deposit_account_validate($data);
|
||
if ($errors !== []) {
|
||
throw new InvalidArgumentException((string) json_encode($errors, JSON_UNESCAPED_UNICODE));
|
||
}
|
||
db()->prepare(
|
||
'UPDATE deposit_accounts SET label = ?, holder = ?, bank = ?, iban = ?, sort_order = ?, updated_at = ?
|
||
WHERE id = ?'
|
||
)->execute([
|
||
$data['label'], $data['holder'], $data['bank'], $data['iban'], $data['sort_order'], utc_now(), $id,
|
||
]);
|
||
deposit_accounts(true);
|
||
}
|
||
|
||
/** Anzahl der Buchungen, die dieses Konto verwenden. */
|
||
function deposit_account_usage(int $id): int
|
||
{
|
||
$stmt = db()->prepare('SELECT COUNT(*) FROM bookings WHERE deposit_account_id = ?');
|
||
$stmt->execute([$id]);
|
||
return (int) $stmt->fetchColumn();
|
||
}
|
||
|
||
/** Löscht ein Konto – nur solange keine Buchung darauf verweist. */
|
||
function deposit_account_delete(int $id): bool
|
||
{
|
||
if (deposit_account_usage($id) > 0) {
|
||
return false;
|
||
}
|
||
db()->prepare('DELETE FROM deposit_accounts WHERE id = ?')->execute([$id]);
|
||
deposit_accounts(true);
|
||
return true;
|
||
}
|
||
|
||
/** Frist für die Anzahlung in Werktagen (Mo–Sa, ohne gesetzliche Feiertage). */
|
||
function deposit_due_working_days(): int
|
||
{
|
||
return max(1, min(60, (int) config('app.deposit_due_working_days', 7)));
|
||
}
|
||
|
||
/**
|
||
* Fälligkeitsdatum der Anzahlung: n Werktage ab heute (Mo–Sa, NRW-Feiertage
|
||
* zählen nicht mit).
|
||
*/
|
||
function deposit_due_date(?string $fromIso = null): string
|
||
{
|
||
$date = $fromIso !== null && valid_date($fromIso) ? $fromIso : today_iso();
|
||
$remaining = deposit_due_working_days();
|
||
$guard = 0;
|
||
$cursor = date_obj($date);
|
||
while ($remaining > 0 && $guard < 400) {
|
||
$cursor = $cursor->modify('+1 day');
|
||
$guard++;
|
||
$iso = $cursor->format('Y-m-d');
|
||
$weekday = $cursor->format('N');
|
||
if ($weekday === '7') {
|
||
continue; // Sonntag ist kein Werktag
|
||
}
|
||
if (holiday_name($iso) !== null) {
|
||
continue;
|
||
}
|
||
$remaining--;
|
||
}
|
||
return $cursor->format('Y-m-d');
|
||
}
|
||
|
||
/**
|
||
* Lieferadresse für die Auftragsbestätigung: abweichende Adresse, sonst die
|
||
* Kundenanschrift (Straße, Ort).
|
||
*/
|
||
function document_delivery_address(array $booking): string
|
||
{
|
||
$address = trim(
|
||
trim((string) ($booking['delivery_street'] ?? '')) . ', ' . trim((string) ($booking['delivery_city'] ?? '')),
|
||
', '
|
||
);
|
||
if ($address !== '') {
|
||
return $address;
|
||
}
|
||
$address = trim((string) $booking['street'] . ', ' . (string) $booking['city'], ', ');
|
||
return $address !== '' ? $address : (string) $booking['city'];
|
||
}
|
||
|
||
/**
|
||
* Nur die Gattung des Mietgegenstandes – ohne Anhänger-/Truhennummer.
|
||
* Für die Auftragsbestätigung: „Kühlanhänger“ oder „Truhe“.
|
||
*/
|
||
function document_subject_plain(array $booking): string
|
||
{
|
||
$label = (string) ($booking['trailer_label'] ?? '');
|
||
return mb_stripos($label, 'truhe') !== false ? 'Truhe' : 'Kühlanhänger';
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
*
|
||
* $signedVia: tablet (vor Ort übergeben), link (Unterschriftslink des Kunden)
|
||
* oder null, wenn noch nicht unterschrieben wurde.
|
||
*/
|
||
/** Pfad einer Signaturdatei im Buchungsordner (null, wenn nicht vorhanden). */
|
||
function document_signature_file_path(int $bookingId, string $file): ?string
|
||
{
|
||
$file = trim($file);
|
||
if ($file === '') {
|
||
return null;
|
||
}
|
||
$path = document_store_root() . '/' . $bookingId . '/' . $file;
|
||
return is_file($path) ? $path : null;
|
||
}
|
||
|
||
/**
|
||
* Unterschriftenblock des Mietvertrags: drei Zeilen in der Reihenfolge des
|
||
* Papiervertrags – Mitarbeiter (Zahlung erhalten), Mieter (Übernahme), Mieter
|
||
* (Kaution bei Rückgabe zurückerhalten).
|
||
*
|
||
* @param array<string, array<string, mixed>> $signatures Rolle => Datensatz
|
||
* @return float Unterkante des Blocks
|
||
*/
|
||
function document_pdf_signatures(PdfDoc $pdf, float $top, array $booking, array $signatures): float
|
||
{
|
||
$legal = legal_data();
|
||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||
$blocks = [
|
||
DOCUMENT_SIGN_HANDOVER => [
|
||
'Übergabe: Der Mitarbeiter bestätigt, dass die Zahlung eingegangen ist.',
|
||
'Datum, Unterschrift Mitarbeiter – ' . $owner,
|
||
],
|
||
DOCUMENT_SIGN_CUSTOMER => [
|
||
'Übernahme: Der Mieter bestätigt, den Mietgegenstand übernommen zu haben.',
|
||
'Datum, Unterschrift Mieter',
|
||
],
|
||
DOCUMENT_SIGN_RETURN => [
|
||
'Rückgabe: Der Mieter bestätigt, die Kaution zurückerhalten zu haben.',
|
||
'Datum, Unterschrift Mieter',
|
||
],
|
||
];
|
||
|
||
foreach ($blocks as $role => [$heading, $caption]) {
|
||
$row = $signatures[$role] ?? null;
|
||
$file = $row !== null
|
||
? document_signature_file_path((int) $booking['id'], (string) ($row['signature_file'] ?? ''))
|
||
: null;
|
||
$pdf->text(50, $top, 8.5, $heading);
|
||
if ($file !== null) {
|
||
$pdf->image($file, 50, $top + 6, 140, 33);
|
||
}
|
||
$lineY = $top + 46;
|
||
$pdf->line(50, $lineY, 545, $lineY, 0.7);
|
||
$pdf->text(50, $lineY + 11, 7.5, $caption);
|
||
if ($row !== null && trim((string) ($row['signed_at'] ?? '')) !== '') {
|
||
$via = (string) ($row['signed_via'] ?? '') === 'link' ? 'per Unterschriftslink' : 'auf dem Tablet';
|
||
$pdf->text(320, $lineY + 11, 7.5, 'Unterschrieben am ' . fmt_datetime((string) $row['signed_at']) . ' (' . $via . ')');
|
||
}
|
||
$top = $lineY + 26;
|
||
}
|
||
|
||
return $top;
|
||
}
|
||
|
||
/** Mietvertrag als PDF (Variante Lieferung, Selbstabholer oder Truhe). */
|
||
function document_contract_pdf(
|
||
array $booking,
|
||
string $variant,
|
||
array $signatures = []
|
||
): string {
|
||
$legal = legal_data();
|
||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||
$texts = document_texts($variant);
|
||
$deposit = booking_deposit_amount($booking);
|
||
$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);
|
||
|
||
$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', document_delivery_address($booking)];
|
||
} 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) . ' (in bar bei Übergabe, 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);
|
||
|
||
// Zusatzvereinbarungen aus der Buchung gehören in den Vertrag (der Kunde
|
||
// unterschreibt sie damit mit).
|
||
$agreements = trim((string) ($booking['agreements'] ?? ''));
|
||
if ($agreements !== '') {
|
||
$y = document_pdf_heading($pdf, $y + 6, 'Zusatzvereinbarungen');
|
||
foreach (preg_split('/\R/', $agreements) ?: [] as $line) {
|
||
if (trim($line) === '') {
|
||
continue;
|
||
}
|
||
foreach ($pdf->wrap(trim($line), 9, $pdf->pageWidth() - 100) as $wrappedLine) {
|
||
if ($y > 700) {
|
||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']);
|
||
$pdf->newPage();
|
||
$y = 90.0;
|
||
}
|
||
$pdf->text(50, $y, 9, $wrappedLine);
|
||
$y += 12.5;
|
||
}
|
||
}
|
||
}
|
||
|
||
$signatureTop = $y + 24;
|
||
if ($signatureTop + 220 > 762) {
|
||
document_pdf_footer($pdf, 'Mietvertrag · Buchung #' . (int) $booking['id'] . ' · ' . (string) $booking['customer_name']);
|
||
$pdf->newPage();
|
||
$signatureTop = 90.0;
|
||
}
|
||
document_pdf_signatures($pdf, $signatureTop, $booking, $signatures);
|
||
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 = booking_deposit_amount($booking);
|
||
$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'];
|
||
// Die Kaution ist keine zahlbare Summe: sie wird bei der Übergabe in bar
|
||
// hinterlegt und bei der Rückgabe vollständig erstattet. Deshalb steht in
|
||
// der Auftragsbestätigung überall die Summe ohne Kaution.
|
||
$grand = $total;
|
||
|
||
$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_plain($booking)],
|
||
['Art', document_variant_label($variant)],
|
||
['Mietzeitraum', 'von ' . fmt_date_weekday_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||
. ' bis ' . fmt_date_weekday_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') {
|
||
$rows[] = ['Lieferadresse', document_delivery_address($booking)];
|
||
}
|
||
$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)];
|
||
}
|
||
// Anzahlung: vereinbart (Häkchen in der Buchung) und Betrag > 0.
|
||
$depositRequired = (int) ($booking['deposit_required'] ?? 0) === 1;
|
||
$transfer = booking_balance_transfer($booking);
|
||
$account = ($depositRequired && $paid > 0) || $transfer ? booking_money_account($booking) : null;
|
||
$dueDate = $account !== null ? deposit_due_date() : null;
|
||
$workingDays = deposit_due_working_days();
|
||
$balanceDue = booking_balance_due_date($booking);
|
||
$open = max(0, $grand - $paid);
|
||
if ($paid > 0) {
|
||
$priceRows[] = [
|
||
$account !== null ? 'Anzahlung (bis ' . fmt_date((string) $dueDate) . ')' : 'Anzahlung',
|
||
'− ' . fmt_money($paid),
|
||
];
|
||
}
|
||
$priceRows[] = ['Gesamtbetrag', fmt_money($grand), true];
|
||
$priceRows[] = [$transfer ? 'Restbetrag per Überweisung' : 'Bei Übergabe in bar zu zahlen', fmt_money($open), true];
|
||
if ($transfer) {
|
||
$priceRows[] = ['Zahlungseingang bis', fmt_date_weekday($balanceDue) . ' (' . document_reminder_days()
|
||
. ' Tage vor Mietbeginn)'];
|
||
}
|
||
if ($deposit > 0) {
|
||
// Steht bewusst unter dem Zahlungseingang: die Kaution ist keine
|
||
// zahlbare Summe, sie wird bei der Übergabe in bar hinterlegt.
|
||
$priceRows[] = ['Kaution (in bar bei Übergabe)', fmt_money($deposit) . ' · wird zurückgegeben'];
|
||
}
|
||
$y = document_pdf_rows($pdf, $y, $priceRows);
|
||
|
||
if ($account !== null) {
|
||
$y = document_pdf_heading(
|
||
$pdf,
|
||
$y + 6,
|
||
$paid > 0 ? 'Anzahlung und verbindliche Reservierung' : 'Zahlung per Überweisung'
|
||
);
|
||
if ($paid > 0) {
|
||
$intro = 'Zur verbindlichen Reservierung ist eine Anzahlung in Höhe von ' . fmt_money($paid)
|
||
. ' innerhalb von ' . $workingDays . ' Werktagen nach Erhalt dieser Auftragsbestätigung – also bis '
|
||
. 'spätestens ' . fmt_date((string) $dueDate) . ' – auf folgendes Konto zu überweisen:';
|
||
$y = $pdf->paragraph(50, $y + 2, $pdf->pageWidth() - 100, 9.5, $intro, false, 13);
|
||
} else {
|
||
$intro = 'Bitte überweisen Sie ' . ($transfer ? 'den Gesamtbetrag' : 'die Anzahlung') . ' von '
|
||
. fmt_money($transfer ? $open : $paid) . ' bis spätestens ' . fmt_date($balanceDue)
|
||
. ' auf folgendes Konto:';
|
||
$y = $pdf->paragraph(50, $y + 2, $pdf->pageWidth() - 100, 9.5, $intro, false, 13);
|
||
}
|
||
$y = document_pdf_rows($pdf, $y + 4, [
|
||
['Kontoinhaber', $account['holder']],
|
||
['Bank', $account['bank']],
|
||
['IBAN', $account['iban']],
|
||
['Verwendungszweck', '#' . (int) $booking['id'] . ' ' . (string) $booking['customer_name']],
|
||
], 168.0);
|
||
if ($paid > 0) {
|
||
$warning = 'Bitte beachten: Erst nach Eingang der Anzahlung auf dem genannten Konto ist der Termin '
|
||
. 'verbindlich reserviert. Erfolgt innerhalb der Frist kein Zahlungseingang, behalten wir uns vor, '
|
||
. 'den Termin wieder freizugeben.';
|
||
$y = $pdf->paragraph(50, $y + 4, $pdf->pageWidth() - 100, 9.5, $warning, false, 13);
|
||
}
|
||
}
|
||
|
||
// Zahlungshinweis und Schlusstext in einem Block – hält die Seite einseitig.
|
||
$depositText = $deposit > 0
|
||
? 'Die Kaution von ' . fmt_money($deposit) . ' ist bei der Übergabe in bar zu zahlen und wird bei '
|
||
. 'ordnungsgemäßer Rückgabe vollständig erstattet. '
|
||
: '';
|
||
if ($transfer && $account !== null) {
|
||
$payment = 'Der Restbetrag von ' . fmt_money($open) . ' ist bis spätestens ' . fmt_date($balanceDue)
|
||
. ' auf das genannte Konto zu überweisen; ' . transfer_reminder_days() . ' Tage vor dem Termin erhalten '
|
||
. 'Sie dazu noch eine Zahlungserinnerung. ' . $depositText;
|
||
} elseif ($account !== null) {
|
||
$payment = 'Der Restbetrag von ' . fmt_money($open) . ' ist bei der Übergabe in bar fällig. ' . $depositText;
|
||
} else {
|
||
$payment = $transfer
|
||
? 'Der Restbetrag von ' . fmt_money($open) . ' ist bis spätestens ' . fmt_date($balanceDue)
|
||
. ' zu überweisen; die Bankverbindung erhalten Sie mit der Zahlungserinnerung. ' . $depositText
|
||
: 'Der Gesamtbetrag ist bei der Übergabe in bar zu zahlen; nach Absprache auch per Überweisung '
|
||
. '(Geld bis spätestens Montag der Terminwoche). ' . $depositText;
|
||
}
|
||
$closing = 'Vielen Dank für die Buchung. Diese Auftragsbestätigung bestätigt den vereinbarten Termin und '
|
||
. 'die genannten Beträge. ' . $payment
|
||
. 'Ein Mitarbeiter von uns meldet sich 8–10 Tage vor dem Termin, um die genaue Übergabezeit abzusprechen. '
|
||
. '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 + 8, $pdf->pageWidth() - 100, 9, $closing, false, 12.5);
|
||
|
||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||
$signatureFile = owner_signature_path();
|
||
$signatureSpace = $signatureFile !== null ? 52 : 18;
|
||
|
||
// Zusatzvereinbarungen (Freitext aus der Buchung), falls hinterlegt.
|
||
$agreements = trim((string) ($booking['agreements'] ?? ''));
|
||
if ($agreements !== '') {
|
||
$textWidth = $pdf->pageWidth() - 100;
|
||
$agreementLines = 0;
|
||
$agreementText = [];
|
||
foreach (preg_split('/\R/', $agreements) ?: [] as $line) {
|
||
if (trim($line) === '') {
|
||
continue;
|
||
}
|
||
$wrapped = $pdf->wrap(trim($line), 9, $textWidth);
|
||
$agreementLines += count($wrapped);
|
||
foreach ($wrapped as $wrappedLine) {
|
||
$agreementText[] = $wrappedLine;
|
||
}
|
||
}
|
||
// Nur umbrechen, wenn Vereinbarungen + Unterschrift sonst nicht mehr passen.
|
||
$needed = 26 + $agreementLines * 12.5 + $signatureSpace + 12;
|
||
if ($y + $needed > 762) {
|
||
document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']);
|
||
$pdf->newPage();
|
||
$y = 90;
|
||
}
|
||
$y = document_pdf_heading($pdf, $y + 8, 'Zusatzvereinbarungen');
|
||
foreach ($agreementText as $line) {
|
||
$pdf->text(50, $y, 9, $line);
|
||
$y += 12.5;
|
||
}
|
||
}
|
||
|
||
// Unterschriftenfelder: links Ort/Datum (vorbelegt), rechts die hinterlegte
|
||
// Unterschrift des Vermieters. Nur bei Platzmangel auf eine neue Seite.
|
||
$signatureTop = $y + $signatureSpace;
|
||
if ($signatureTop > 762) {
|
||
document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']);
|
||
$pdf->newPage();
|
||
$signatureTop = 190;
|
||
}
|
||
|
||
$place = trim((string) ($legal['city'] ?? ''));
|
||
$pdf->text(50, $signatureTop - 7, 9.5, trim($place . ', ' . fmt_date(today_iso()), ', '));
|
||
$pdf->line(50, $signatureTop, 300, $signatureTop, 0.7);
|
||
$pdf->text(50, $signatureTop + 13, 7.5, 'Ort, Datum');
|
||
|
||
if ($signatureFile !== null) {
|
||
$pdf->image($signatureFile, 326, $signatureTop - 46, 130, 43.3);
|
||
}
|
||
$pdf->line(320, $signatureTop, 545, $signatureTop, 0.7);
|
||
$pdf->text(320, $signatureTop + 13, 7.5, 'Unterschrift Vermieter – ' . $owner);
|
||
document_pdf_footer($pdf, 'Auftragsbestätigung · Buchung #' . (int) $booking['id']);
|
||
|
||
return $pdf->output();
|
||
}
|
||
|
||
/* --------------------------------------------------- Zahlungserinnerung */
|
||
|
||
/** Vorlauf in Tagen, bis zu dem eine Überweisung eingegangen sein muss. */
|
||
function document_reminder_days(): int
|
||
{
|
||
return max(0, min(60, (int) config('app.reminder_due_days', 5)));
|
||
}
|
||
|
||
/**
|
||
* Vorlauf der automatischen Zahlungserinnerung bei Restzahlung per Überweisung
|
||
* (Versand an den Kunden, nicht das Zahlungsziel im Dokument).
|
||
*/
|
||
function transfer_reminder_days(): int
|
||
{
|
||
return max(1, min(60, (int) config('app.transfer_reminder_days', 10)));
|
||
}
|
||
|
||
/** Zahlt der Kunde die Restzahlung per Überweisung statt bar bei der Übergabe? */
|
||
function booking_balance_transfer(array $booking): bool
|
||
{
|
||
return (string) ($booking['balance_method'] ?? 'cash') === 'transfer';
|
||
}
|
||
|
||
/**
|
||
* Bankkonto einer Buchung: das gewählte Konto, sonst das erste gepflegte Konto.
|
||
* Liefert null, wenn gar kein Konto hinterlegt ist.
|
||
*/
|
||
function booking_money_account(array $booking): ?array
|
||
{
|
||
$account = deposit_account((int) ($booking['deposit_account_id'] ?? 0));
|
||
if ($account !== null) {
|
||
return $account;
|
||
}
|
||
$accounts = deposit_accounts();
|
||
return $accounts[0] ?? null;
|
||
}
|
||
|
||
/** Zahlungsziel der Restzahlung: n Tage vor Mietbeginn, mindestens heute. */
|
||
function booking_balance_due_date(array $booking): string
|
||
{
|
||
$start = (string) ($booking['start_date'] ?? '');
|
||
$due = valid_date($start) ? add_days($start, -document_reminder_days()) : today_iso();
|
||
return $due < today_iso() ? today_iso() : $due;
|
||
}
|
||
|
||
/**
|
||
* Zahlungsziel der Erinnerung: n Tage vor Mietbeginn, mindestens heute (ist die
|
||
* Frist schon verstrichen, mahnt das Dokument sofort an).
|
||
*/
|
||
function document_reminder_due_date(array $booking): string
|
||
{
|
||
return booking_balance_due_date($booking);
|
||
}
|
||
|
||
/**
|
||
* Bankkonto für die Erinnerung: das in der Buchung gewählte Konto (privat oder
|
||
* geschäftlich), sonst das erste gepflegte Konto.
|
||
*/
|
||
function document_reminder_account(array $booking): array
|
||
{
|
||
$account = booking_money_account($booking);
|
||
if ($account === null) {
|
||
throw new RuntimeException('Es ist kein Bankkonto hinterlegt. Bitte zuerst unter Einstellungen → Konten ein Konto anlegen.');
|
||
}
|
||
return $account;
|
||
}
|
||
|
||
/**
|
||
* Offener Betrag für die Erinnerung: bei vereinbarter Anzahlung der Restbetrag,
|
||
* sonst der Gesamtbetrag. Liefert Cents und die passende Bezeichnung.
|
||
*
|
||
* @return array{open: int, grand: int, paid: int, deposit: int, label: string}
|
||
*/
|
||
function document_reminder_amounts(array $booking): array
|
||
{
|
||
// Die Kaution wird bei der Übergabe in bar hinterlegt und ist damit keine
|
||
// Forderung – sie steht nur als Hinweis im Dokument.
|
||
$deposit = booking_deposit_amount($booking);
|
||
$grand = (int) $booking['total_cents'];
|
||
$paid = max(0, (int) ($booking['deposit_cents'] ?? 0));
|
||
$hasDeposit = (int) ($booking['deposit_required'] ?? 0) === 1 && $paid > 0;
|
||
$open = $hasDeposit ? max(0, $grand - $paid) : $grand;
|
||
return [
|
||
'open' => $open,
|
||
'grand' => $grand,
|
||
'paid' => $hasDeposit ? $paid : 0,
|
||
'deposit' => $deposit,
|
||
'label' => $hasDeposit ? 'Restbetrag' : 'Gesamtbetrag',
|
||
];
|
||
}
|
||
|
||
/** Zahlungserinnerung: offener Betrag, Zahlungsziel und Bankverbindung der Buchung. */
|
||
function document_reminder_pdf(array $booking): string
|
||
{
|
||
$amounts = document_reminder_amounts($booking);
|
||
$account = document_reminder_account($booking);
|
||
$due = document_reminder_due_date($booking);
|
||
$days = document_reminder_days();
|
||
$subject = document_subject_plain($booking);
|
||
$term = fmt_date_weekday((string) $booking['start_date']) . ' bis ' . fmt_date_weekday((string) $booking['end_date']);
|
||
|
||
$pdf = new PdfDoc();
|
||
document_pdf_title($pdf, 'Zahlungserinnerung', 'Buchung #' . (int) $booking['id'] . ' · ' . fmt_date(today_iso()));
|
||
$y = document_pdf_parties($pdf, 92, $booking);
|
||
|
||
$intro = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n"
|
||
. 'für Ihre Buchung (' . $subject . ', ' . $term . ') ist noch ein ' . $amounts['label'] . ' von '
|
||
. fmt_money($amounts['open']) . ' offen. Bitte überweisen Sie diesen Betrag bis spätestens '
|
||
. fmt_date($due) . ' (' . $days . ' Tage vor Mietbeginn) auf das unten genannte Konto.';
|
||
$y = $pdf->paragraph(50, $y, $pdf->pageWidth() - 100, 9.5, $intro, false, 13);
|
||
|
||
$y = document_pdf_heading($pdf, $y + 6, 'Offener Betrag');
|
||
$rows = [
|
||
['Mietgegenstand', $subject],
|
||
['Mietzeitraum', $term],
|
||
['Gesamtbetrag', fmt_money($amounts['grand'])],
|
||
];
|
||
if ($amounts['paid'] > 0) {
|
||
$rows[] = ['Anzahlung (bereits gezahlt)', '− ' . fmt_money($amounts['paid'])];
|
||
}
|
||
$rows[] = [$amounts['label'], fmt_money($amounts['open']), true];
|
||
$rows[] = ['Zahlungseingang bis', fmt_date($due)];
|
||
$y = document_pdf_rows($pdf, $y, $rows);
|
||
|
||
$y = document_pdf_heading($pdf, $y + 6, 'Zahlung per Überweisung');
|
||
$y = document_pdf_rows($pdf, $y, [
|
||
['Kontoinhaber', (string) $account['holder']],
|
||
['Bank', (string) $account['bank']],
|
||
['IBAN', (string) $account['iban']],
|
||
['Verwendungszweck', '#' . (int) $booking['id'] . ' ' . (string) $booking['customer_name']],
|
||
], 168.0);
|
||
|
||
$closing = 'Bitte geben Sie bei der Überweisung den Verwendungszweck an, damit wir die Zahlung zuordnen können. '
|
||
. 'Ist die Zahlung bereits veranlasst, betrachten Sie diese Erinnerung als gegenstandslos.';
|
||
if ($amounts['deposit'] > 0) {
|
||
$closing .= ' Die Kaution von ' . fmt_money($amounts['deposit']) . ' ist bei der Übergabe in bar zu '
|
||
. 'hinterlegen und wird bei ordnungsgemäßer Rückgabe vollständig erstattet (kein Teil des oben '
|
||
. 'genannten Betrags).';
|
||
}
|
||
$closing .= ' Es gelten die Allgemeinen Geschäftsbedingungen des Vermieters.';
|
||
$y = $pdf->paragraph(50, $y + 6, $pdf->pageWidth() - 100, 9, $closing, false, 12.5);
|
||
|
||
document_pdf_footer($pdf, 'Zahlungserinnerung · Buchung #' . (int) $booking['id']);
|
||
|
||
return $pdf->output();
|
||
}
|
||
|
||
/* -------------------------------------------------------- Unterschrift */
|
||
|
||
/**
|
||
* Speichert die Unterschrift (JPEG-Daten-URL) und erzeugt das Mietvertrags-PDF
|
||
* neu, damit die Unterschrift im Dokument steht.
|
||
*
|
||
* $via: 'tablet' (Kunde unterschreibt auf dem Drink-it-cold-Tablet bei der
|
||
* Lieferung) oder 'link' (Unterschriftslink auf dem eigenen Gerät des Kunden).
|
||
*/
|
||
function document_save_signature(
|
||
array $booking,
|
||
array $doc,
|
||
string $dataUrl,
|
||
?int $userId,
|
||
string $via = 'tablet',
|
||
string $role = DOCUMENT_SIGN_CUSTOMER
|
||
): array {
|
||
if ($doc['kind'] !== DOCUMENT_KIND_CONTRACT) {
|
||
throw new RuntimeException('Nur der Mietvertrag wird unterschrieben.');
|
||
}
|
||
if (!document_sign_role_valid($role)) {
|
||
$role = DOCUMENT_SIGN_CUSTOMER;
|
||
}
|
||
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);
|
||
// Die Kundenunterschrift behält den bisherigen Dateinamen (Kompatibilität),
|
||
// die beiden anderen Rollen bekommen ein eigenes Suffix.
|
||
$file = $role === DOCUMENT_SIGN_CUSTOMER
|
||
? 'unterschrift-' . (int) $doc['id'] . '.jpg'
|
||
: 'unterschrift-' . (int) $doc['id'] . '-' . $role . '.jpg';
|
||
if (@file_put_contents($dir . '/' . $file, $binary) === false) {
|
||
throw new RuntimeException('Die Unterschrift konnte nicht gespeichert werden.');
|
||
}
|
||
|
||
$via = in_array($via, ['tablet', 'link'], true) ? $via : 'tablet';
|
||
if (document_signatures_schema_ready()) {
|
||
db()->prepare(
|
||
'INSERT INTO document_signatures (document_id, role, signature_file, signed_at, signed_via, signed_by)
|
||
VALUES (?, ?, ?, ?, ?, ?)
|
||
ON DUPLICATE KEY UPDATE signature_file = VALUES(signature_file), signed_at = VALUES(signed_at),
|
||
signed_via = VALUES(signed_via), signed_by = VALUES(signed_by)'
|
||
)->execute([(int) $doc['id'], $role, $file, utc_now(), $via, $userId]);
|
||
}
|
||
if ($role === DOCUMENT_SIGN_CUSTOMER) {
|
||
// Kundenunterschrift zusätzlich in booking_documents (Anzeige, Mailversand,
|
||
// Löschprotokoll); der Unterschriftslink ist damit verbraucht.
|
||
db()->prepare(
|
||
'UPDATE booking_documents SET signature_file = ?, signed_at = ?, signed_via = ?, sign_token = NULL WHERE id = ?'
|
||
)->execute([$file, utc_now(), $via, (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);
|
||
}
|
||
|
||
/* ------------------------------------------- Digitale Unterschrift per Link */
|
||
|
||
/** Absolute URL für Links in E-Mails (config app.public_url, sonst Host). */
|
||
function document_absolute_url(string $path): string
|
||
{
|
||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||
if ($base === '' && !empty($_SERVER['HTTP_HOST'])) {
|
||
$base = (is_https() ? 'https://' : 'http://') . (string) $_SERVER['HTTP_HOST'];
|
||
}
|
||
return $base . url($path);
|
||
}
|
||
|
||
/** Unterschriftslink des Kunden (leer, solange keiner angefordert wurde). */
|
||
function document_sign_link(array $doc): string
|
||
{
|
||
$token = trim((string) ($doc['sign_token'] ?? ''));
|
||
return $token === '' ? '' : document_absolute_url('/unterschrift/' . $token);
|
||
}
|
||
|
||
function document_find_by_sign_token(string $token): ?array
|
||
{
|
||
$token = trim($token);
|
||
if (!preg_match('/^[a-f0-9]{64}$/', $token) || !documents_schema_ready()) {
|
||
return null;
|
||
}
|
||
$stmt = db()->prepare('SELECT * FROM booking_documents WHERE sign_token = ? LIMIT 1');
|
||
$stmt->execute([$token]);
|
||
$row = $stmt->fetch();
|
||
return $row ?: null;
|
||
}
|
||
|
||
/**
|
||
* Erzeugt (oder erneuert) den persönlichen Unterschriftslink des Kunden.
|
||
* Der Link bleibt gültig, bis der Kunde unterschreibt oder ein neuer erzeugt wird.
|
||
*/
|
||
function document_request_signature(array $doc, bool $renew = false): array
|
||
{
|
||
if ($doc['kind'] !== DOCUMENT_KIND_CONTRACT) {
|
||
throw new RuntimeException('Nur der Mietvertrag wird unterschrieben.');
|
||
}
|
||
if (!documents_schema_ready()) {
|
||
throw new RuntimeException('Die Tabelle für Unterlagen fehlt noch. Bitte zuerst /migrate mit dem Cron-Token aufrufen.');
|
||
}
|
||
$token = trim((string) ($doc['sign_token'] ?? ''));
|
||
if ($token === '' || $renew) {
|
||
$token = bin2hex(random_bytes(32));
|
||
db()->prepare('UPDATE booking_documents SET sign_token = ?, sign_requested_at = ? WHERE id = ?')
|
||
->execute([$token, utc_now(), (int) $doc['id']]);
|
||
}
|
||
return document_find((int) $doc['id']) ?? $doc;
|
||
}
|
||
|
||
/** Verschickt den Unterschriftslink an den Kunden. */
|
||
function document_mail_signature_request(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.');
|
||
}
|
||
$link = document_sign_link($doc);
|
||
if ($link === '') {
|
||
throw new RuntimeException('Es gibt noch keinen Unterschriftslink.');
|
||
}
|
||
$subject = 'Mietvertrag zur Unterschrift bei Drink it cold #' . (int) $booking['id'] . ' '
|
||
. booking_item_label($booking);
|
||
$body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n"
|
||
. 'bitte unterschreiben Sie den Mietvertrag zu Ihrer Buchung digital. Der Link ist persönlich für Sie '
|
||
. "bestimmt und bleibt gültig, bis Sie unterschrieben haben:\n\n"
|
||
. $link . "\n\n"
|
||
. 'Mietgegenstand: ' . booking_item_label($booking) . "\n"
|
||
. 'Zeitraum: ' . fmt_date_weekday_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||
. ' bis ' . fmt_date_weekday_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n"
|
||
. 'Den Vertrag können Sie sich im Link vorab als PDF ansehen. Nach der Unterschrift erhalten Sie den '
|
||
. "unterschriebenen Vertrag automatisch per E-Mail.\n\n"
|
||
. mail_signature_block() . "\n\n"
|
||
. mail_auto_hint();
|
||
|
||
if (!mail_send($to, $subject, $body)) {
|
||
return false;
|
||
}
|
||
db()->prepare('UPDATE booking_documents SET sign_requested_at = COALESCE(sign_requested_at, ?) WHERE id = ?')
|
||
->execute([utc_now(), (int) $doc['id']]);
|
||
return true;
|
||
}
|
||
|
||
/** Schickt dem Kunden den unterschriebenen Vertrag als PDF. */
|
||
function document_mail_signed_copy(array $booking, array $doc): bool
|
||
{
|
||
if (!mail_is_enabled()) {
|
||
return false;
|
||
}
|
||
$path = document_path($doc);
|
||
if (!is_file($path)) {
|
||
return false;
|
||
}
|
||
return mail_send_attachment(
|
||
trim((string) $booking['email']),
|
||
'Ihr unterschriebener Mietvertrag zur Buchung bei Drink it cold #' . (int) $booking['id'] . ' '
|
||
. booking_item_label($booking),
|
||
'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n"
|
||
. "vielen Dank – Ihre Unterschrift ist eingegangen. Den unterschriebenen Mietvertrag finden Sie im "
|
||
. "Anhang.\n\nMietgegenstand: " . booking_item_label($booking) . "\n"
|
||
. 'Zeitraum: ' . fmt_date_weekday_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||
. ' bis ' . fmt_date_weekday_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n"
|
||
. mail_signature_block() . "\n\n"
|
||
. mail_auto_hint(),
|
||
(string) $doc['file_name'],
|
||
'application/pdf',
|
||
(string) file_get_contents($path)
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Unterschrift aus dem Kundenlink: speichert die Signatur, entwertet den Link
|
||
* und schickt dem Kunden den unterschriebenen Vertrag.
|
||
*/
|
||
function document_sign_by_customer(array $booking, array $doc, string $dataUrl): array
|
||
{
|
||
$doc = document_save_signature($booking, $doc, $dataUrl, null, 'link');
|
||
$mailed = false;
|
||
if (mail_is_enabled() && filter_var((string) $booking['email'], FILTER_VALIDATE_EMAIL) !== false) {
|
||
$mailed = document_mail_signed_copy($booking, $doc);
|
||
}
|
||
return ['doc' => $doc, 'mailed' => $mailed];
|
||
}
|
||
|
||
/* ------------------------------------------------------------ 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.');
|
||
}
|
||
$label = document_kind_label((string) $doc['kind']);
|
||
$subject = $label . ' zur Buchung bei Drink it cold #' . (int) $booking['id'] . ' '
|
||
. booking_item_label($booking);
|
||
|
||
$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";
|
||
if ((string) $doc['kind'] === DOCUMENT_KIND_REMINDER) {
|
||
$amounts = document_reminder_amounts($booking);
|
||
$account = document_reminder_account($booking);
|
||
$body .= $amounts['label'] . ': ' . fmt_money($amounts['open']) . "\n"
|
||
. 'Zahlungseingang bis: ' . fmt_date_weekday(document_reminder_due_date($booking))
|
||
. ' (' . document_reminder_days() . ' Tage vor Mietbeginn)' . "\n"
|
||
. 'IBAN: ' . (string) $account['iban'] . ' (' . (string) $account['holder'] . ")\n";
|
||
if ($amounts['deposit'] > 0) {
|
||
$body .= 'Kaution: ' . fmt_money($amounts['deposit']) . " (bitte bei der Übergabe in bar mitbringen)\n";
|
||
}
|
||
$body .= "\n";
|
||
}
|
||
$body .= 'Mietgegenstand: ' . booking_item_label($booking) . "\n"
|
||
. 'Zeitraum: ' . fmt_date_weekday_with_time((string) $booking['start_date'], $booking['start_time'] ?? null)
|
||
. ' bis ' . fmt_date_weekday_with_time((string) $booking['end_date'], $booking['end_time'] ?? null) . "\n\n"
|
||
. mail_signature_block() . "\n\n"
|
||
. mail_auto_hint();
|
||
|
||
$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;
|
||
}
|
||
$signatureFiles = [];
|
||
if (document_signatures_schema_ready()) {
|
||
$stmt = db()->prepare('SELECT signature_file FROM document_signatures WHERE document_id = ?');
|
||
$stmt->execute([$id]);
|
||
$signatureFiles = array_map('strval', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
||
}
|
||
db()->prepare('DELETE FROM booking_documents WHERE id = ?')->execute([$id]);
|
||
$paths = [document_path($doc), document_signature_path($doc)];
|
||
foreach ($signatureFiles as $signatureFile) {
|
||
$paths[] = document_signature_file_path((int) $doc['booking_id'], $signatureFile);
|
||
}
|
||
foreach (array_unique(array_filter($paths)) as $path) {
|
||
if (is_file($path)) {
|
||
@unlink($path);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Aufbewahrungsfrist einer Unterlagen-Art in Tagen ab Mietende.
|
||
*
|
||
* Regel des Kunden (04.12.2026):
|
||
* - Rechnung NEIN → alle Unterlagen 30 Tage,
|
||
* - Rechnung JA → alle Unterlagen 30 Tage, nur der Mietvertrag bleibt
|
||
* 8 Jahre (2922 Tage) als Buchungsbeleg aufbewahrt.
|
||
*
|
||
* Die Fristen stehen in app.document_retention_days (with_invoice /
|
||
* without_invoice); die alte Form mit einer Frist je Art wird weiter gelesen.
|
||
* Rückgabe <= 0 bedeutet: nicht automatisch löschen.
|
||
*/
|
||
function document_retention_days(string $kind, ?array $booking = null): int
|
||
{
|
||
$invoice = $booking !== null && (int) ($booking['invoice'] ?? 0) === 1;
|
||
$defaults = [
|
||
'with_invoice' => [DOCUMENT_KIND_CONTRACT => 2922, 'default' => 30],
|
||
'without_invoice' => ['default' => 30],
|
||
];
|
||
$config = config('app.document_retention_days', $defaults);
|
||
if (!is_array($config)) {
|
||
// Altform: eine Zahl gilt für alle Arten.
|
||
return (int) $config;
|
||
}
|
||
if (isset($config['with_invoice']) || isset($config['without_invoice'])) {
|
||
$set = $invoice ? (array) ($config['with_invoice'] ?? []) : (array) ($config['without_invoice'] ?? []);
|
||
return (int) ($set[$kind] ?? $set['default'] ?? 30);
|
||
}
|
||
// Altform: art-spezifische Tage.
|
||
return (int) ($config[$kind] ?? $config['default'] ?? 30);
|
||
}
|
||
|
||
/** Frist als kurzer Text für die Oberfläche, z. B. "8 Jahre" oder "30 Tage". */
|
||
function document_retention_text(string $kind, ?array $booking = null): string
|
||
{
|
||
$days = document_retention_days($kind, $booking);
|
||
if ($days <= 0) {
|
||
return 'keine automatische Löschung';
|
||
}
|
||
if ($days >= 330) {
|
||
$years = (int) round($days / 365);
|
||
if (abs($days - $years * 365) <= 31) {
|
||
return $years === 1 ? '1 Jahr' : $years . ' Jahre';
|
||
}
|
||
}
|
||
return $days . ' Tage';
|
||
}
|
||
|
||
/**
|
||
* Löscht Unterlagen nach Ablauf der art-spezifischen Frist sowie verwaiste
|
||
* Dateien. Rechnungen und Mietverträge bleiben dadurch deutlich länger
|
||
* erhalten als Auftragsbestätigungen und Zahlungserinnerungen.
|
||
*
|
||
* @return array{rows: int, files: int}
|
||
*/
|
||
function documents_cleanup(): array
|
||
{
|
||
$result = ['rows' => 0, 'files' => 0];
|
||
|
||
if (!documents_schema_ready()) {
|
||
return $result;
|
||
}
|
||
|
||
$stmt = db()->query(
|
||
'SELECT d.*, b.end_date, b.invoice FROM booking_documents d JOIN bookings b ON b.id = d.booking_id'
|
||
);
|
||
foreach ($stmt->fetchAll() as $doc) {
|
||
$days = document_retention_days((string) $doc['kind'], $doc);
|
||
if ($days <= 0) {
|
||
continue; // dauerhaft aufbewahren
|
||
}
|
||
if ((string) $doc['end_date'] >= add_days(today_iso(), -$days)) {
|
||
continue; // Frist noch nicht abgelaufen
|
||
}
|
||
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;
|
||
}
|