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
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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue