feat(booking): Kaution je Buchung, drei Vertragsunterschriften, Mails und Aufbewahrung nach Kundenwunsch
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.
This commit is contained in:
parent
606237dbda
commit
00b7b7f0e9
33 changed files with 1355 additions and 218 deletions
|
|
@ -62,6 +62,14 @@ function admin_handle(string $path, array $user): void
|
|||
admin_backups($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/export') {
|
||||
admin_year_export();
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/export/([A-Za-z0-9_.-]+)$#', $path, $m) === 1) {
|
||||
admin_year_export_file($m[1]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/backups/(backup_[A-Za-z0-9_.-]+\.tar\.gz)/download$#', $path, $m) === 1) {
|
||||
admin_backup_download($m[1]);
|
||||
return;
|
||||
|
|
@ -803,9 +811,51 @@ function admin_backups(array $user): void
|
|||
'directory' => backup_root(),
|
||||
'maxMb' => (int) config('app.backup_max_mb', 200),
|
||||
'available' => class_exists('PharData'),
|
||||
'exports' => year_exports(),
|
||||
'exportYear' => (int) date('Y'),
|
||||
], 'Sicherungen');
|
||||
}
|
||||
|
||||
/** Baut den Jahresexport der Mietverträge und liefert ihn als Download aus. */
|
||||
function admin_year_export(): never
|
||||
{
|
||||
$year = (int) query_string('year');
|
||||
if ($year < 2000 || $year > (int) date('Y')) {
|
||||
$year = (int) date('Y');
|
||||
}
|
||||
try {
|
||||
$export = year_export_build($year);
|
||||
admin_year_export_stream($export['path'], $export['name']);
|
||||
} catch (Throwable $error) {
|
||||
flash('error', 'Jahresexport fehlgeschlagen: ' . $error->getMessage());
|
||||
redirect('/admin/backups');
|
||||
}
|
||||
}
|
||||
|
||||
/** Liefert ein bereits gebautes Jahresarchiv aus. */
|
||||
function admin_year_export_file(string $name): never
|
||||
{
|
||||
if (!preg_match('/^mietvertraege-\d{4}\.(zip|tar\.gz)$/', $name)) {
|
||||
abort_page(404, 'Dieses Archiv gibt es nicht.');
|
||||
}
|
||||
$path = year_export_dir() . '/' . $name;
|
||||
if (!is_file($path)) {
|
||||
abort_page(404, 'Dieses Archiv gibt es nicht.');
|
||||
}
|
||||
admin_year_export_stream($path, $name);
|
||||
}
|
||||
|
||||
function admin_year_export_stream(string $path, string $name): never
|
||||
{
|
||||
$mime = str_ends_with($name, '.zip') ? 'application/zip' : 'application/gzip';
|
||||
header('Content-Type: ' . $mime);
|
||||
header('Content-Length: ' . (string) filesize($path));
|
||||
header('Content-Disposition: attachment; filename="' . $name . '"');
|
||||
header('Cache-Control: private, no-store');
|
||||
readfile($path);
|
||||
exit;
|
||||
}
|
||||
|
||||
function admin_backup_restore(array $user): never
|
||||
{
|
||||
$name = post_string('name');
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ require DIC_APP . '/inquiry.php';
|
|||
require DIC_APP . '/invite.php';
|
||||
require DIC_APP . '/privacy.php';
|
||||
require DIC_APP . '/backup.php';
|
||||
require DIC_APP . '/export.php';
|
||||
require DIC_APP . '/pages.php';
|
||||
require DIC_APP . '/admin.php';
|
||||
|
||||
|
|
|
|||
|
|
@ -44,17 +44,19 @@ return [
|
|||
'retired_url' => '',
|
||||
// Aufbewahrung der Buchungsunterlagen in Tagen ab Mietende; danach
|
||||
// räumt documents_cleanup() auf. 0 = nicht automatisch löschen.
|
||||
// Best effort, bis die Fristen rechtlich abgesichert sind:
|
||||
// Mietvertrag ~4 Jahre (Verjährung 3 Jahre ab Jahresende + Puffer),
|
||||
// Rechnung 8 Jahre (Buchungsbeleg, GoBD-Schutz noch offen).
|
||||
// Regel laut Kunde: ohne Rechnung alles 30 Tage; mit Rechnung bleiben
|
||||
// nur die Mietverträge 8 Jahre (2922 Tage) als Buchungsbeleg.
|
||||
'document_retention_days' => [
|
||||
'contract' => 1461,
|
||||
'confirmation' => 90,
|
||||
'reminder' => 365,
|
||||
'invoice' => 2922,
|
||||
'default' => 30,
|
||||
'with_invoice' => [
|
||||
'contract' => 2922,
|
||||
'default' => 30,
|
||||
],
|
||||
'without_invoice' => [
|
||||
'default' => 30,
|
||||
],
|
||||
],
|
||||
// Kaution, die im Vertrag aufgeführt wird (in Cent).
|
||||
// Standard-Kaution in Cent, mit der eine neue Buchung vorbelegt wird.
|
||||
// Pro Buchung änderbar (bookings.deposit_amount_cents, 0 = keine Kaution).
|
||||
'document_deposit_cents' => 10000,
|
||||
// Maximale Größe einer hochgeladenen Rechnung (PDF aus Lexware).
|
||||
'document_max_mb' => 10,
|
||||
|
|
@ -74,6 +76,11 @@ return [
|
|||
// Restzahlung per Überweisung: so viele Tage vor Mietbeginn geht die
|
||||
// Zahlungserinnerung automatisch per E-Mail an den Kunden (Standard 10).
|
||||
'transfer_reminder_days' => 10,
|
||||
// Bewertungsmail nach der Rückgabe: so viele Tage nach Mietende geht die
|
||||
// automatische Mail mit dem Google-Bewertungslink an den Kunden.
|
||||
'review_mail_days' => 7,
|
||||
// Link zur Google-Bewertung (erscheint in der Bewertungsmail).
|
||||
'review_url' => 'https://g.co/kgs/eBcVxRZ',
|
||||
],
|
||||
// Optional: Angaben für Impressum und Datenschutz überschreiben. Die
|
||||
// Standardwerte stehen in app/legal.php. Hinweis: tools/deploy.sh erzeugt
|
||||
|
|
|
|||
59
app/data.php
59
app/data.php
|
|
@ -180,6 +180,16 @@ function booking_input(array $source): array
|
|||
$invoiceNo = trim((string) ($source['invoice_no'] ?? ''));
|
||||
$invoice = $invoiceNo !== '' || ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0;
|
||||
|
||||
// Kaution: eigener Betrag je Buchung, 0 = keine Kaution. Fehlt das Feld
|
||||
// ganz (Aufrufer ohne Kenntnis der Kaution), gilt weiter der Standard.
|
||||
if (array_key_exists('deposit_amount_cents', $source)) {
|
||||
$depositAmount = max(0, (int) $source['deposit_amount_cents']);
|
||||
} elseif (array_key_exists('deposit_amount', $source)) {
|
||||
$depositAmount = parse_money((string) $source['deposit_amount']);
|
||||
} else {
|
||||
$depositAmount = booking_deposit_default_cents();
|
||||
}
|
||||
|
||||
return [
|
||||
'trailer_id' => (int) ($source['trailer_id'] ?? 0),
|
||||
'employee_id' => (int) ($source['employee_id'] ?? 0),
|
||||
|
|
@ -191,6 +201,7 @@ function booking_input(array $source): array
|
|||
'deposit_cents' => $depositRequired ? parse_money((string) ($source['deposit'] ?? '0')) : 0,
|
||||
'deposit_required' => $depositRequired,
|
||||
'deposit_account_id' => (int) ($source['deposit_account_id'] ?? 0),
|
||||
'deposit_amount_cents' => $depositAmount,
|
||||
'balance_method' => (string) ($source['balance_method'] ?? 'cash') === 'transfer' ? 'transfer' : 'cash',
|
||||
'rent_cents' => $rent,
|
||||
'delivery_cents' => $delivery,
|
||||
|
|
@ -224,6 +235,7 @@ function booking_to_input(array $booking): array
|
|||
'deposit_cents' => (int) $booking['deposit_cents'],
|
||||
'deposit_required' => (int) ($booking['deposit_required'] ?? 0),
|
||||
'deposit_account_id' => (int) ($booking['deposit_account_id'] ?? 0),
|
||||
'deposit_amount_cents' => booking_deposit_amount($booking),
|
||||
'balance_method' => (string) ($booking['balance_method'] ?? 'cash') === 'transfer' ? 'transfer' : 'cash',
|
||||
'rent_cents' => (int) ($booking['rent_cents'] ?? $booking['total_cents']),
|
||||
'delivery_cents' => (int) ($booking['delivery_cents'] ?? 0),
|
||||
|
|
@ -333,9 +345,11 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
|
|||
}
|
||||
|
||||
$maxAmount = 10000000; // 100.000,00 €
|
||||
if ($data['rent_cents'] < 0 || $data['delivery_cents'] < 0 || $data['deposit_cents'] < 0) {
|
||||
if ($data['rent_cents'] < 0 || $data['delivery_cents'] < 0 || $data['deposit_cents'] < 0
|
||||
|| (int) ($data['deposit_amount_cents'] ?? 0) < 0) {
|
||||
$errors['rent'] = 'Beträge dürfen nicht negativ sein.';
|
||||
} elseif ($data['rent_cents'] > $maxAmount || $data['delivery_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
|
||||
} elseif ($data['rent_cents'] > $maxAmount || $data['delivery_cents'] > $maxAmount
|
||||
|| $data['deposit_cents'] > $maxAmount || (int) ($data['deposit_amount_cents'] ?? 0) > $maxAmount) {
|
||||
$errors['rent'] = 'Der Betrag ist unrealistisch hoch.';
|
||||
} elseif ($data['deposit_cents'] > $data['total_cents']) {
|
||||
$errors['deposit'] = 'Die Anzahlung darf den Gesamtbetrag nicht übersteigen.';
|
||||
|
|
@ -545,7 +559,7 @@ function booking_create(array $data, int $userId): int
|
|||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO bookings
|
||||
(trailer_id, employee_id, return_employee_id, start_date, end_date, start_time, end_time, deposit_cents,
|
||||
deposit_required, deposit_account_id, balance_method,
|
||||
deposit_required, deposit_account_id, deposit_amount_cents, balance_method,
|
||||
rent_cents, delivery_cents, total_cents, invoice, invoice_no, kind,
|
||||
customer_name, street, city, delivery_street, delivery_city, mobile, email, note, agreements,
|
||||
status, created_at, updated_at, created_by, updated_by)
|
||||
|
|
@ -557,6 +571,7 @@ function booking_create(array $data, int $userId): int
|
|||
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
|
||||
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0),
|
||||
((int) ($data['deposit_account_id'] ?? 0)) > 0 ? (int) $data['deposit_account_id'] : null,
|
||||
(int) ($data['deposit_amount_cents'] ?? 0),
|
||||
(string) ($data['balance_method'] ?? 'cash'),
|
||||
$data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
|
||||
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
|
||||
|
|
@ -593,7 +608,7 @@ function booking_update(int $id, array $data, int $userId): void
|
|||
$stmt = $pdo->prepare(
|
||||
'UPDATE bookings SET trailer_id = ?, employee_id = ?, return_employee_id = ?, start_date = ?, end_date = ?,
|
||||
start_time = ?, end_time = ?, deposit_cents = ?, deposit_required = ?, deposit_account_id = ?,
|
||||
balance_method = ?,
|
||||
deposit_amount_cents = ?, balance_method = ?,
|
||||
rent_cents = ?, delivery_cents = ?, total_cents = ?, invoice = ?, invoice_no = ?, kind = ?,
|
||||
customer_name = ?, street = ?, city = ?, delivery_street = ?, delivery_city = ?,
|
||||
mobile = ?, email = ?, note = ?, agreements = ?, updated_at = ?,
|
||||
|
|
@ -605,6 +620,7 @@ function booking_update(int $id, array $data, int $userId): void
|
|||
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
|
||||
$data['deposit_cents'], (int) ($data['deposit_required'] ?? 0),
|
||||
((int) ($data['deposit_account_id'] ?? 0)) > 0 ? (int) $data['deposit_account_id'] : null,
|
||||
(int) ($data['deposit_amount_cents'] ?? 0),
|
||||
(string) ($data['balance_method'] ?? 'cash'),
|
||||
$data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
|
||||
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
|
||||
|
|
@ -744,6 +760,17 @@ function booking_kind_label(string $kind): string
|
|||
return $kind === 'delivery' ? 'Lieferung' : 'Abholer';
|
||||
}
|
||||
|
||||
/**
|
||||
* Mietgegenstand in Kurzform für Mail-Betreff und -Text: „Kühlanhänger“ oder
|
||||
* „Truhe“ – bewusst ohne Anhänger-Nummer, damit der Kunde die Nummer nicht
|
||||
* mit seiner Buchung verwechselt (Kundenwunsch 04.12.2026).
|
||||
*/
|
||||
function booking_item_label(array $booking): string
|
||||
{
|
||||
$label = mb_strtolower((string) ($booking['trailer_label'] ?? ''));
|
||||
return str_contains($label, 'truhe') ? 'Truhe' : 'Kühlanhänger';
|
||||
}
|
||||
|
||||
/** Name des Mitarbeiters für die Abholung/Rücknahme (fällt auf die Übergabe zurück). */
|
||||
function booking_return_employee_name(array $booking): string
|
||||
{
|
||||
|
|
@ -885,15 +912,37 @@ function availability_level(int $free, int $total): string
|
|||
return $free <= 2 ? 'few' : 'free';
|
||||
}
|
||||
|
||||
/** Standard-Kaution in Cent (app.document_deposit_cents, Standard 100 €). */
|
||||
function booking_deposit_default_cents(): int
|
||||
{
|
||||
return max(0, (int) config('app.document_deposit_cents', 10000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaution einer Buchung in Cent. 0 heißt „keine Kaution“ (z. B. Stammkunde) –
|
||||
* dann darf sie in den Unterlagen nirgends als Forderung auftauchen.
|
||||
* Fehlt die Spalte noch (Migration 020 ausstehend), gilt der Standard.
|
||||
*/
|
||||
function booking_deposit_amount(array $booking): int
|
||||
{
|
||||
if (array_key_exists('deposit_amount_cents', $booking) && $booking['deposit_amount_cents'] !== null) {
|
||||
return max(0, (int) $booking['deposit_amount_cents']);
|
||||
}
|
||||
return booking_deposit_default_cents();
|
||||
}
|
||||
|
||||
function booking_copy_text(array $booking): string
|
||||
{
|
||||
$depositAmount = booking_deposit_amount($booking);
|
||||
return implode("\n", [
|
||||
'Anzahlung: ' . fmt_money((int) $booking['deposit_cents'])
|
||||
. ((int) ($booking['deposit_required'] ?? 0) === 1 && (int) $booking['deposit_cents'] > 0
|
||||
? ' (fällig bis ' . fmt_date(deposit_due_date()) . ')'
|
||||
: ''),
|
||||
'Gesamtbetrag: ' . fmt_money((int) $booking['total_cents']),
|
||||
'Noch zu zahlen: ' . fmt_money(due_cents((int) $booking['total_cents'], (int) $booking['deposit_cents'])),
|
||||
'Kaution: ' . ($depositAmount > 0
|
||||
? fmt_money($depositAmount) . ' (in bar bei der Übergabe)'
|
||||
: 'entfällt'), 'Noch zu zahlen: ' . fmt_money(due_cents((int) $booking['total_cents'], (int) $booking['deposit_cents'])),
|
||||
'Restzahlung: ' . (booking_balance_transfer($booking)
|
||||
? 'Überweisung (bis ' . fmt_date(booking_balance_due_date($booking)) . ')'
|
||||
: 'bar bei der Übergabe'),
|
||||
|
|
|
|||
|
|
@ -23,6 +23,90 @@ 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
|
||||
{
|
||||
|
|
@ -233,7 +317,7 @@ function document_create(array $booking, string $kind, string $variant, ?int $us
|
|||
$dir = document_booking_dir((int) $booking['id'], true);
|
||||
$token = bin2hex(random_bytes(8));
|
||||
$stored = $token . '.pdf';
|
||||
$bytes = document_render($booking, $kind, $variant, null, null);
|
||||
$bytes = document_render($booking, $kind, $variant);
|
||||
if (@file_put_contents($dir . '/' . $stored, $bytes) === false) {
|
||||
throw new RuntimeException('Unterlage konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
|
@ -270,14 +354,7 @@ function document_regenerate(array $booking, array $doc): array
|
|||
if ($kind === DOCUMENT_KIND_REMINDER) {
|
||||
$variant = ''; // Erinnerungen haben keine Mietvertrags-Variante.
|
||||
}
|
||||
$bytes = document_render(
|
||||
$booking,
|
||||
$kind,
|
||||
$variant,
|
||||
document_signature_path($doc),
|
||||
$doc['signed_at'] !== null ? (string) $doc['signed_at'] : null,
|
||||
trim((string) ($doc['signed_via'] ?? '')) !== '' ? (string) $doc['signed_via'] : null
|
||||
);
|
||||
$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) {
|
||||
|
|
@ -293,14 +370,16 @@ function document_render(
|
|||
array $booking,
|
||||
string $kind,
|
||||
string $variant,
|
||||
?string $signatureFile,
|
||||
?string $signedAt,
|
||||
?string $signedVia = null
|
||||
?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, $signatureFile, $signedAt, $signedVia),
|
||||
default => document_contract_pdf(
|
||||
$booking,
|
||||
$variant,
|
||||
$doc !== null ? document_signatures($doc) : []
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -742,54 +821,76 @@ function document_pdf_note(PdfDoc $pdf, float $top, string $title, string $text)
|
|||
* $signedVia: tablet (vor Ort übergeben), link (Unterschriftslink des Kunden)
|
||||
* oder null, wenn noch nicht unterschrieben wurde.
|
||||
*/
|
||||
function document_pdf_signatures(
|
||||
PdfDoc $pdf,
|
||||
float $top,
|
||||
array $booking,
|
||||
?string $signatureFile,
|
||||
?string $signedAt,
|
||||
?string $signedVia = null
|
||||
): void {
|
||||
/** 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'];
|
||||
$lineLeft = 50.0;
|
||||
$lineRight = 310.0;
|
||||
$lineWidth = 235.0;
|
||||
$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',
|
||||
],
|
||||
];
|
||||
|
||||
if ($signatureFile !== null) {
|
||||
$pdf->image($signatureFile, $lineLeft, $top - 52, 150, 50);
|
||||
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;
|
||||
}
|
||||
$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) {
|
||||
$label = match ($signedVia) {
|
||||
'tablet' => 'vor Ort auf dem Tablet',
|
||||
'link' => 'per Unterschriftslink',
|
||||
default => 'digitale Signatur',
|
||||
};
|
||||
$pdf->text($lineLeft, $top - 6, 8.5, 'Unterschrieben am ' . fmt_datetime($signedAt) . ' (' . $label . ')');
|
||||
}
|
||||
$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: _____________________ €');
|
||||
return $top;
|
||||
}
|
||||
|
||||
/** Mietvertrag als PDF (Variante Lieferung, Selbstabholer oder Truhe). */
|
||||
function document_contract_pdf(
|
||||
array $booking,
|
||||
string $variant,
|
||||
?string $signatureFile,
|
||||
?string $signedAt,
|
||||
?string $signedVia = null
|
||||
array $signatures = []
|
||||
): 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));
|
||||
$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);
|
||||
|
|
@ -837,7 +938,7 @@ function document_contract_pdf(
|
|||
$priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)];
|
||||
}
|
||||
if ($deposit > 0) {
|
||||
$priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)'];
|
||||
$priceRows[] = ['Kaution', fmt_money($deposit) . ' (in bar bei Übergabe, Rückgabe: volle Erstattung)'];
|
||||
}
|
||||
if ($paid > 0) {
|
||||
$priceRows[] = ['Anzahlung', '− ' . fmt_money($paid)];
|
||||
|
|
@ -854,13 +955,34 @@ function document_contract_pdf(
|
|||
. '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) {
|
||||
// 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 = 150;
|
||||
$signatureTop = 90.0;
|
||||
}
|
||||
document_pdf_signatures($pdf, $signatureTop, $booking, $signatureFile, $signedAt, $signedVia);
|
||||
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).
|
||||
|
|
@ -907,12 +1029,15 @@ 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));
|
||||
$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;
|
||||
// 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()));
|
||||
|
|
@ -922,8 +1047,8 @@ function document_confirmation_pdf(array $booking, string $variant): string
|
|||
$rows = [
|
||||
['Mietgegenstand', document_subject_plain($booking)],
|
||||
['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)],
|
||||
['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)],
|
||||
];
|
||||
|
|
@ -937,9 +1062,6 @@ function document_confirmation_pdf(array $booking, string $variant): string
|
|||
if ($delivery > 0) {
|
||||
$priceRows[] = ['Lieferung / Abholung', fmt_money($delivery)];
|
||||
}
|
||||
if ($deposit > 0) {
|
||||
$priceRows[] = ['Kaution', fmt_money($deposit) . ' (Rückgabe: volle Erstattung)'];
|
||||
}
|
||||
// Anzahlung: vereinbart (Häkchen in der Buchung) und Betrag > 0.
|
||||
$depositRequired = (int) ($booking['deposit_required'] ?? 0) === 1;
|
||||
$transfer = booking_balance_transfer($booking);
|
||||
|
|
@ -957,9 +1079,14 @@ function document_confirmation_pdf(array $booking, string $variant): string
|
|||
$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($balanceDue) . ' (' . document_reminder_days()
|
||||
$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) {
|
||||
|
|
@ -983,8 +1110,7 @@ function document_confirmation_pdf(array $booking, string $variant): string
|
|||
['Kontoinhaber', $account['holder']],
|
||||
['Bank', $account['bank']],
|
||||
['IBAN', $account['iban']],
|
||||
['Verwendungszweck', document_subject_plain($booking) . ' ' . fmt_date((string) $booking['start_date'])
|
||||
. ' · ' . (string) $booking['customer_name']],
|
||||
['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 '
|
||||
|
|
@ -995,25 +1121,26 @@ function document_confirmation_pdf(array $booking, string $variant): string
|
|||
}
|
||||
|
||||
// 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. '
|
||||
. 'Die Kaution von ' . fmt_money($deposit) . ' wird bei ordnungsgemäßer Rückgabe vollständig erstattet. ';
|
||||
. 'Sie dazu noch eine Zahlungserinnerung. ' . $depositText;
|
||||
} elseif ($account !== null) {
|
||||
$payment = 'Der Restbetrag von ' . fmt_money($open) . ' ist bei der Übergabe in bar fällig. '
|
||||
. 'Die Kaution von ' . fmt_money($deposit) . ' wird bei ordnungsgemäßer Rückgabe vollständig erstattet. ';
|
||||
$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. '
|
||||
. 'Die Kaution von ' . fmt_money($deposit) . ' wird bei ordnungsgemäßer Rückgabe vollständig erstattet. '
|
||||
. ' 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). Die Kaution von ' . fmt_money($deposit)
|
||||
. ' wird bei ordnungsgemäßer Rückgabe vollständig erstattet. ';
|
||||
. '(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);
|
||||
|
|
@ -1151,8 +1278,10 @@ function document_reminder_account(array $booking): array
|
|||
*/
|
||||
function document_reminder_amounts(array $booking): array
|
||||
{
|
||||
$deposit = max(0, (int) config('app.document_deposit_cents', 10000));
|
||||
$grand = (int) $booking['total_cents'] + $deposit;
|
||||
// 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;
|
||||
|
|
@ -1173,7 +1302,7 @@ function document_reminder_pdf(array $booking): string
|
|||
$due = document_reminder_due_date($booking);
|
||||
$days = document_reminder_days();
|
||||
$subject = document_subject_plain($booking);
|
||||
$term = fmt_date((string) $booking['start_date']) . ' bis ' . fmt_date((string) $booking['end_date']);
|
||||
$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()));
|
||||
|
|
@ -1203,15 +1332,15 @@ function document_reminder_pdf(array $booking): string
|
|||
['Kontoinhaber', (string) $account['holder']],
|
||||
['Bank', (string) $account['bank']],
|
||||
['IBAN', (string) $account['iban']],
|
||||
['Verwendungszweck', $subject . ' ' . fmt_date((string) $booking['start_date'])
|
||||
. ' · ' . (string) $booking['customer_name']],
|
||||
['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']) . ' wird bei ordnungsgemäßer '
|
||||
. 'Rückgabe vollständig erstattet.';
|
||||
$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);
|
||||
|
|
@ -1235,11 +1364,15 @@ function document_save_signature(
|
|||
array $doc,
|
||||
string $dataUrl,
|
||||
?int $userId,
|
||||
string $via = 'tablet'
|
||||
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.');
|
||||
}
|
||||
|
|
@ -1252,15 +1385,31 @@ function document_save_signature(
|
|||
}
|
||||
|
||||
$dir = document_booking_dir((int) $doc['booking_id'], true);
|
||||
$file = 'unterschrift-' . (int) $doc['id'] . '.jpg';
|
||||
// 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';
|
||||
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']]);
|
||||
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 = ?')
|
||||
|
|
@ -1337,21 +1486,19 @@ function document_mail_signature_request(array $booking, array $doc): bool
|
|||
if ($link === '') {
|
||||
throw new RuntimeException('Es gibt noch keinen Unterschriftslink.');
|
||||
}
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$subject = 'Mietvertrag zur Unterschrift · ' . (string) $booking['trailer_label'] . ' · '
|
||||
. fmt_date_short((string) $booking['start_date']);
|
||||
$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: ' . (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"
|
||||
. '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"
|
||||
. 'Freundliche Grüße' . "\n" . $owner . "\n" . (string) $legal['business_name'] . "\n"
|
||||
. (string) $legal['phone'] . ' · ' . (string) $legal['email'];
|
||||
. mail_signature_block() . "\n\n"
|
||||
. mail_auto_hint();
|
||||
|
||||
if (!mail_send($to, $subject, $body)) {
|
||||
return false;
|
||||
|
|
@ -1373,15 +1520,15 @@ function document_mail_signed_copy(array $booking, array $doc): bool
|
|||
}
|
||||
return mail_send_attachment(
|
||||
trim((string) $booking['email']),
|
||||
'Ihr unterschriebener Mietvertrag · ' . (string) $booking['trailer_label'] . ' · '
|
||||
. fmt_date_short((string) $booking['start_date']),
|
||||
'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: " . (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\nFreundliche Grüße\n"
|
||||
. (string) legal_data()['business_name'],
|
||||
. "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)
|
||||
|
|
@ -1491,11 +1638,9 @@ function document_mail_to_customer(array $booking, array $doc): bool
|
|||
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']);
|
||||
$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
|
||||
|
|
@ -1504,16 +1649,19 @@ function document_mail_to_customer(array $booking, array $doc): bool
|
|||
$amounts = document_reminder_amounts($booking);
|
||||
$account = document_reminder_account($booking);
|
||||
$body .= $amounts['label'] . ': ' . fmt_money($amounts['open']) . "\n"
|
||||
. 'Zahlungseingang bis: ' . fmt_date(document_reminder_due_date($booking))
|
||||
. '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\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: ' . (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'];
|
||||
$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) {
|
||||
|
|
@ -1530,9 +1678,19 @@ function document_delete(int $id): void
|
|||
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]);
|
||||
foreach ([document_path($doc), document_signature_path($doc)] as $path) {
|
||||
if ($path !== null && is_file($path)) {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1541,38 +1699,39 @@ function document_delete(int $id): void
|
|||
/**
|
||||
* Aufbewahrungsfrist einer Unterlagen-Art in Tagen ab Mietende.
|
||||
*
|
||||
* Best effort, bis die Fristen rechtlich abgesichert sind:
|
||||
* - Mietvertrag: Verjährung von Ansprüchen (3 Jahre, beginnend am Jahresende)
|
||||
* plus Puffer, also rund 4 Jahre nach Mietende.
|
||||
* - Rechnung: 8 Jahre für Buchungsbelege; der GoBD-Schutz (Unveränderbarkeit,
|
||||
* Protokollierung) ist noch nicht umgesetzt, bitte steuerlich prüfen.
|
||||
* - Auftragsbestätigung/Zahlungserinnerung: nur für die Abwicklung nötig.
|
||||
* 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): int
|
||||
function document_retention_days(string $kind, ?array $booking = null): int
|
||||
{
|
||||
$invoice = $booking !== null && (int) ($booking['invoice'] ?? 0) === 1;
|
||||
$defaults = [
|
||||
DOCUMENT_KIND_CONTRACT => 1461,
|
||||
DOCUMENT_KIND_CONFIRMATION => 90,
|
||||
DOCUMENT_KIND_REMINDER => 365,
|
||||
DOCUMENT_KIND_INVOICE => 2922,
|
||||
'default' => 30,
|
||||
'with_invoice' => [DOCUMENT_KIND_CONTRACT => 2922, 'default' => 30],
|
||||
'without_invoice' => ['default' => 30],
|
||||
];
|
||||
$config = config('app.document_retention_days', $defaults);
|
||||
if (is_array($config)) {
|
||||
$days = $config[$kind] ?? $config['default'] ?? $defaults['default'];
|
||||
} else {
|
||||
if (!is_array($config)) {
|
||||
// Altform: eine Zahl gilt für alle Arten.
|
||||
$days = $config;
|
||||
return (int) $config;
|
||||
}
|
||||
return (int) $days;
|
||||
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. "4 Jahre" oder "90 Tage". */
|
||||
function document_retention_text(string $kind): string
|
||||
/** 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);
|
||||
$days = document_retention_days($kind, $booking);
|
||||
if ($days <= 0) {
|
||||
return 'keine automatische Löschung';
|
||||
}
|
||||
|
|
@ -1601,10 +1760,10 @@ function documents_cleanup(): array
|
|||
}
|
||||
|
||||
$stmt = db()->query(
|
||||
'SELECT d.*, b.end_date FROM booking_documents d JOIN bookings b ON b.id = d.booking_id'
|
||||
'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']);
|
||||
$days = document_retention_days((string) $doc['kind'], $doc);
|
||||
if ($days <= 0) {
|
||||
continue; // dauerhaft aufbewahren
|
||||
}
|
||||
|
|
|
|||
226
app/export.php
Normal file
226
app/export.php
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Jahresexport der Mietverträge.
|
||||
*
|
||||
* Der Kunde möchte am Ende des Jahres eine Datei mit allen Mietverträgen und
|
||||
* den zugehörigen Buchungsdaten lokal ablegen (Aufbewahrung: 8 Jahre, solange
|
||||
* eine Rechnung geschrieben wurde). Der Export bündelt
|
||||
*
|
||||
* mietvertraege/<Buchung> <Kunde>.pdf – alle Mietverträge des Jahres
|
||||
* buchungen.csv – eine Zeile je Buchung
|
||||
* README.txt – kurze Erläuterung
|
||||
*
|
||||
* in einem Archiv unter storage/exports/. Gebaut wird es auf Zuruf
|
||||
* (Verwaltung → Sicherungen) und automatisch beim ersten Cron-Lauf im Januar.
|
||||
*/
|
||||
|
||||
function year_export_dir(): string
|
||||
{
|
||||
$path = rtrim((string) config('app.storage_path', dirname(__DIR__) . '/storage'), '/') . '/exports';
|
||||
if (!is_dir($path)) {
|
||||
@mkdir($path, 0775, true);
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
/** Endung des Archivs: ZIP, wenn PHP es kann, sonst tar.gz über PharData. */
|
||||
function year_export_extension(): string
|
||||
{
|
||||
return class_exists('ZipArchive') ? '.zip' : '.tar.gz';
|
||||
}
|
||||
|
||||
function year_export_path(int $year): string
|
||||
{
|
||||
return year_export_dir() . '/mietvertraege-' . $year . year_export_extension();
|
||||
}
|
||||
|
||||
function year_export_exists(int $year): bool
|
||||
{
|
||||
return is_file(year_export_path($year));
|
||||
}
|
||||
|
||||
/** @return list<array{year: int, name: string, size: int, created_at: string}> */
|
||||
function year_exports(): array
|
||||
{
|
||||
$dir = year_export_dir();
|
||||
$items = [];
|
||||
foreach (glob($dir . '/mietvertraege-*') ?: [] as $file) {
|
||||
if (!is_file($file)) {
|
||||
continue;
|
||||
}
|
||||
if (!preg_match('/mietvertraege-(\d{4})/', basename($file), $m)) {
|
||||
continue;
|
||||
}
|
||||
$items[] = [
|
||||
'year' => (int) $m[1],
|
||||
'name' => basename($file),
|
||||
'size' => (int) filesize($file),
|
||||
'created_at' => date('Y-m-d H:i', (int) filemtime($file)),
|
||||
];
|
||||
}
|
||||
usort($items, static fn (array $a, array $b): int => $b['year'] <=> $a['year']);
|
||||
return $items;
|
||||
}
|
||||
|
||||
/** CSV-Zeile einer Buchung (Semikolon, weil Excel das im deutschen Raum erwartet). */
|
||||
function year_export_row(array $booking, string $contractFile): array
|
||||
{
|
||||
return [
|
||||
(int) $booking['id'],
|
||||
(string) $booking['customer_name'],
|
||||
(string) $booking['street'],
|
||||
(string) $booking['city'],
|
||||
(string) $booking['mobile'],
|
||||
(string) $booking['email'],
|
||||
(string) $booking['trailer_label'],
|
||||
booking_kind_label((string) $booking['kind']),
|
||||
fmt_date((string) $booking['start_date']),
|
||||
fmt_date((string) $booking['end_date']),
|
||||
number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
|
||||
number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
|
||||
number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
|
||||
number_format(booking_deposit_amount($booking) / 100, 2, ',', ''),
|
||||
number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
|
||||
booking_invoice_label((int) $booking['invoice']),
|
||||
(string) ($booking['invoice_no'] ?? ''),
|
||||
str_replace(["\r\n", "\r", "\n"], ' | ', (string) ($booking['agreements'] ?? '')),
|
||||
str_replace(["\r\n", "\r", "\n"], ' | ', (string) ($booking['note'] ?? '')),
|
||||
$contractFile,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Jahresarchiv neu (überschreibt ein vorhandenes).
|
||||
*
|
||||
* @return array{path: string, name: string, bookings: int, contracts: int}
|
||||
*/
|
||||
function year_export_build(int $year): array
|
||||
{
|
||||
if ($year < 2000 || $year > (int) date('Y') + 1) {
|
||||
throw new InvalidArgumentException('Ungültiges Jahr für den Export.');
|
||||
}
|
||||
$dir = year_export_dir();
|
||||
if (!is_dir($dir) || !is_writable($dir)) {
|
||||
throw new RuntimeException('Der Export-Ordner ist nicht beschreibbar: ' . $dir);
|
||||
}
|
||||
|
||||
$from = sprintf('%04d-01-01', $year);
|
||||
$to = sprintf('%04d-12-31', $year);
|
||||
$bookings = booking_list($from, $to, true);
|
||||
|
||||
$rows = [[
|
||||
'Buchung', 'Kunde', 'Straße', 'Ort', 'Handy', 'E-Mail', 'Mietgegenstand', 'Art',
|
||||
'Beginn', 'Ende', 'Miete', 'Lieferung', 'Gesamt', 'Kaution', 'Anzahlung',
|
||||
'Rechnung', 'Rechnungsnummer', 'Zusatzvereinbarungen', 'Bemerkung', 'Mietvertrag',
|
||||
]];
|
||||
$files = [];
|
||||
$used = [];
|
||||
foreach ($bookings as $booking) {
|
||||
$contractName = '';
|
||||
foreach (documents_for_booking((int) $booking['id']) as $doc) {
|
||||
if ((string) $doc['kind'] !== DOCUMENT_KIND_CONTRACT) {
|
||||
continue;
|
||||
}
|
||||
$path = document_path($doc);
|
||||
if (!is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
$name = 'mietvertraege/' . $doc['file_name'];
|
||||
// Doppelte Dateinamen (gleicher Kunde, gleicher Tag) eindeutig machen.
|
||||
$base = substr($name, 0, -4);
|
||||
$suffix = 2;
|
||||
while (isset($used[$name])) {
|
||||
$name = $base . ' (' . $suffix . ').pdf';
|
||||
$suffix++;
|
||||
}
|
||||
$used[$name] = true;
|
||||
$files[$name] = $path;
|
||||
if ($contractName === '') {
|
||||
$contractName = $name;
|
||||
}
|
||||
}
|
||||
$rows[] = year_export_row($booking, $contractName);
|
||||
}
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
if ($handle === false) {
|
||||
throw new RuntimeException('CSV konnte nicht erzeugt werden.');
|
||||
}
|
||||
fwrite($handle, "\xEF\xBB\xBF"); // BOM, damit Excel Umlaute richtig liest
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($handle, $row, ';', '"', '');
|
||||
}
|
||||
rewind($handle);
|
||||
$csv = (string) stream_get_contents($handle);
|
||||
fclose($handle);
|
||||
|
||||
$readme = "Jahresexport $year – Drink it cold\n"
|
||||
. "Erstellt am " . fmt_datetime(utc_now()) . "\n\n"
|
||||
. "Inhalt:\n"
|
||||
. "- mietvertraege/ alle Mietverträge des Jahres " . $year . ' (' . count($files) . " Dateien)\n"
|
||||
. "- buchungen.csv eine Zeile je Buchung (Semikolon-getrennt, UTF-8)\n\n"
|
||||
. "Aufbewahrung: Mietverträge mit Rechnung 8 Jahre, alle übrigen Unterlagen 30 Tage nach Mietende.\n";
|
||||
|
||||
$path = year_export_path($year);
|
||||
if (class_exists('ZipArchive')) {
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
||||
throw new RuntimeException('Das Archiv konnte nicht angelegt werden.');
|
||||
}
|
||||
foreach ($files as $name => $file) {
|
||||
$zip->addFile($file, $name);
|
||||
}
|
||||
$zip->addFromString('buchungen.csv', $csv);
|
||||
$zip->addFromString('README.txt', $readme);
|
||||
$zip->close();
|
||||
} else {
|
||||
// Fallback ohne ZIP-Erweiterung: tar.gz über PharData.
|
||||
if (!class_exists('PharData')) {
|
||||
throw new RuntimeException('Weder ZIP noch Phar stehen zur Verfügung – Export nicht möglich.');
|
||||
}
|
||||
if (is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
$phar = new PharData($path);
|
||||
foreach ($files as $name => $file) {
|
||||
$phar->addFile($file, $name);
|
||||
}
|
||||
$phar->addFromString('buchungen.csv', $csv);
|
||||
$phar->addFromString('README.txt', $readme);
|
||||
$phar->compress(Phar::GZ);
|
||||
@unlink($dir . '/mietvertraege-' . $year . '.tar');
|
||||
$path = year_export_path($year);
|
||||
}
|
||||
|
||||
return [
|
||||
'path' => $path,
|
||||
'name' => basename($path),
|
||||
'bookings' => count($bookings),
|
||||
'contracts' => count($files),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Beim ersten Cron-Lauf im Januar den Export des Vorjahres anlegen, falls er
|
||||
* noch fehlt. Fehler dürfen den Erinnerungslauf nicht stoppen.
|
||||
*
|
||||
* @return array{path: string, name: string, bookings: int, contracts: int}|null
|
||||
*/
|
||||
function year_export_maybe_run(): ?array
|
||||
{
|
||||
if ((int) date('n') !== 1) {
|
||||
return null;
|
||||
}
|
||||
$year = (int) date('Y') - 1;
|
||||
if (year_export_exists($year)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return year_export_build($year);
|
||||
} catch (Throwable $error) {
|
||||
error_log('Jahresexport ' . $year . ' fehlgeschlagen: ' . $error->getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -47,6 +47,8 @@ function legal_data(): array
|
|||
'log_max_mb' => 5,
|
||||
'invoice_retention_years' => 10,
|
||||
'limitation_years' => 3,
|
||||
// Website für den Mail-Fuß (Kundenwunsch 04.12.2026).
|
||||
'website' => 'https://drinkitcold.de',
|
||||
];
|
||||
|
||||
$configured = config('legal', []);
|
||||
|
|
|
|||
135
app/mail.php
135
app/mail.php
|
|
@ -19,6 +19,40 @@ function mail_is_enabled(): bool
|
|||
return (bool) config('app.mail_enabled', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signaturblock für Kundenmails – exakt so, wie der Kunde ihn vorgibt.
|
||||
*/
|
||||
function mail_signature_block(): string
|
||||
{
|
||||
$legal = legal_data();
|
||||
$owner = trim((string) ($legal['owner'] ?? '')) !== '' ? (string) $legal['owner'] : (string) $legal['business_name'];
|
||||
$lines = [
|
||||
'Freundliche Grüße',
|
||||
'',
|
||||
$owner,
|
||||
mb_strtoupper((string) $legal['business_name']) . ' – Wir machen Kälte mobil!',
|
||||
(string) $legal['street'],
|
||||
trim((string) $legal['postal_code'] . ' ' . $legal['city']),
|
||||
'',
|
||||
'Tel.: ' . (string) $legal['phone'],
|
||||
'E-Mail: ' . (string) $legal['email'],
|
||||
'Web: ' . (string) ($legal['website'] ?? 'https://drinkitcold.de'),
|
||||
];
|
||||
return implode("\n", $lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinweis unter automatisch erzeugten Kundenmails: Antworten landen nicht im
|
||||
* Postfach, deshalb der Verweis auf die echte Adresse und die Telefonnummer.
|
||||
*/
|
||||
function mail_auto_hint(): string
|
||||
{
|
||||
$legal = legal_data();
|
||||
return 'WICHTIG: Bitte nicht auf diese Mail antworten – sie wurde automatisch erzeugt und Antworten '
|
||||
. 'kommen bei uns nicht an. Bei Fragen bitte an ' . (string) $legal['email'] . ' schreiben oder rufen Sie '
|
||||
. 'uns an (' . (string) $legal['phone'] . ').';
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt eine reine Textnachricht. Absender kommt aus app.mail_from.
|
||||
* Der Aufrufer prüft mail_is_enabled() und die Empfängeradresse.
|
||||
|
|
@ -292,3 +326,104 @@ function payment_reminder_send_due(int $lookbackDays = 7): array
|
|||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Bewertungsmail */
|
||||
|
||||
/** Vorlauf der Bewertungsmail nach der Rückgabe in Tagen. */
|
||||
function review_mail_days(): int
|
||||
{
|
||||
return max(1, min(120, (int) config('app.review_mail_days', 7)));
|
||||
}
|
||||
|
||||
/** Link zur Google-Bewertung (config app.review_url). */
|
||||
function review_mail_url(): string
|
||||
{
|
||||
$url = trim((string) config('app.review_url', ''));
|
||||
return $url !== '' ? $url : 'https://g.co/kgs/eBcVxRZ';
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatische Bewertungsmail ein paar Tage nach der Rückgabe.
|
||||
*
|
||||
* Der Kunde hat diese Mail bisher manuell verschickt. Jede Buchung bekommt sie
|
||||
* genau einmal (Protokoll review_mail_log, Migration 022); ein Nachlauf von
|
||||
* $lookbackDays Tagen holt Termine nach, falls der Cron pausiert war.
|
||||
*
|
||||
* @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array}
|
||||
*/
|
||||
function review_mail_send_due(int $lookbackDays = 7): array
|
||||
{
|
||||
$result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
|
||||
if (!$result['enabled']) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
try {
|
||||
$table = db()->query("SHOW TABLES LIKE 'review_mail_log'");
|
||||
if ($table === false || $table->fetchColumn() === false) {
|
||||
$result['errors'][] = 'Migration 022_review_mail_log.sql fehlt – Bewertungsmails werden nicht verschickt.';
|
||||
return $result;
|
||||
}
|
||||
$due = add_days(today_iso(), -review_mail_days());
|
||||
$from = add_days($due, -max(1, $lookbackDays));
|
||||
$stmt = db()->prepare(
|
||||
"SELECT id FROM bookings
|
||||
WHERE status <> 'cancelled' AND end_date >= ? AND end_date <= ?
|
||||
ORDER BY end_date, id"
|
||||
);
|
||||
$stmt->execute([$from, $due]);
|
||||
$ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
||||
} catch (Throwable $error) {
|
||||
$result['errors'][] = 'Bewertungsmails nicht lesbar: ' . $error->getMessage();
|
||||
return $result;
|
||||
}
|
||||
|
||||
$legal = legal_data();
|
||||
$link = review_mail_url();
|
||||
foreach ($ids as $id) {
|
||||
$booking = booking_find($id);
|
||||
if (!$booking) {
|
||||
$result['skipped']++;
|
||||
continue;
|
||||
}
|
||||
$to = trim((string) ($booking['email'] ?? ''));
|
||||
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||
$result['skipped']++;
|
||||
continue;
|
||||
}
|
||||
$check = db()->prepare('SELECT 1 FROM review_mail_log WHERE booking_id = ?');
|
||||
$check->execute([$id]);
|
||||
if ($check->fetchColumn()) {
|
||||
$result['skipped']++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$subject = 'Ihre Meinung ist uns wichtig – Drink it cold';
|
||||
$body = 'Guten Tag ' . (string) $booking['customer_name'] . ",\n\n"
|
||||
. "vielen Dank, dass Sie bei Drink it cold einen Kühlanhänger / eine Truhe gemietet haben.\n"
|
||||
. "Wir hoffen, dass Sie mit unserem Service rundum zufrieden waren.\n\n"
|
||||
. "Es würde uns sehr freuen, wenn Sie sich einen kurzen Moment Zeit nehmen und Ihre Erfahrung mit uns "
|
||||
. "auf Google teilen würden. Ihre Bewertung hilft nicht nur uns, sondern auch zukünftigen Kunden bei "
|
||||
. "ihrer Entscheidung.\n\n"
|
||||
. "Hier bewerten: " . $link . "\n\n"
|
||||
. "Ebenso würden wir uns freuen, Sie auch in Zukunft bei Bedarf wieder als Kunden begrüßen zu dürfen.\n"
|
||||
. "Vielen Dank für Ihre Unterstützung!\n\n"
|
||||
. 'Ihr ' . (string) $legal['business_name'] . "-Team\n\n"
|
||||
. mail_auto_hint();
|
||||
|
||||
try {
|
||||
if (!mail_send($to, $subject, $body)) {
|
||||
$result['errors'][] = 'Bewertungsmail an ' . $to . ' konnte nicht versendet werden (Buchung #' . $id . ').';
|
||||
continue;
|
||||
}
|
||||
db()->prepare('INSERT IGNORE INTO review_mail_log (booking_id, sent_to, sent_at) VALUES (?, ?, ?)')
|
||||
->execute([$id, $to, utc_now()]);
|
||||
$result['sent']++;
|
||||
$result['details'][] = 'Buchung #' . $id . ' → ' . $to;
|
||||
} catch (Throwable $error) {
|
||||
$result['errors'][] = 'Buchung #' . $id . ': ' . $error->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -886,6 +886,7 @@ function form_values_from_input(array $data): array
|
|||
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
|
||||
'deposit_required' => (int) ($data['deposit_required'] ?? 0),
|
||||
'deposit_account_id' => (int) ($data['deposit_account_id'] ?? 0),
|
||||
'deposit_amount' => number_format((int) ($data['deposit_amount_cents'] ?? booking_deposit_default_cents()) / 100, 2, ',', ''),
|
||||
'balance_method' => (string) ($data['balance_method'] ?? 'cash') === 'transfer' ? 'transfer' : 'cash',
|
||||
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
|
||||
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
|
||||
|
|
@ -933,6 +934,35 @@ function page_booking_new(array $user, string $method): void
|
|||
$employeeId = (int) $employees[0]['id'];
|
||||
}
|
||||
|
||||
// Weitere Buchung für denselben Kunden/denselben Termin (mehrere Anhänger
|
||||
// oder Anhänger + Truhe): Werte aus der Quellbuchung vorbelegen.
|
||||
$customerName = '';
|
||||
$customerStreet = '';
|
||||
$customerCity = '';
|
||||
$customerMobile = '';
|
||||
$customerEmail = '';
|
||||
$kind = 'pickup';
|
||||
$deliveryStreet = '';
|
||||
$deliveryCity = '';
|
||||
$copyFrom = query_int('from');
|
||||
if ($copyFrom > 0) {
|
||||
$source = booking_find($copyFrom);
|
||||
if ($source !== null) {
|
||||
$customerName = (string) $source['customer_name'];
|
||||
$customerStreet = (string) $source['street'];
|
||||
$customerCity = (string) $source['city'];
|
||||
$customerMobile = (string) $source['mobile'];
|
||||
$customerEmail = (string) $source['email'];
|
||||
$kind = (string) $source['kind'];
|
||||
$deliveryStreet = (string) ($source['delivery_street'] ?? '');
|
||||
$deliveryCity = (string) ($source['delivery_city'] ?? '');
|
||||
if (query_string('start') === '') {
|
||||
$start = (string) $source['start_date'];
|
||||
$end = (string) $source['end_date'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$values = [
|
||||
'trailer_id' => $trailerId,
|
||||
'employee_id' => $employeeId,
|
||||
|
|
@ -944,20 +974,21 @@ function page_booking_new(array $user, string $method): void
|
|||
'deposit' => '',
|
||||
'deposit_required' => 0,
|
||||
'deposit_account_id' => (int) (deposit_accounts()[0]['id'] ?? 0),
|
||||
'deposit_amount' => number_format(booking_deposit_default_cents() / 100, 2, ',', ''),
|
||||
'balance_method' => 'cash',
|
||||
'rent' => '',
|
||||
'delivery' => '',
|
||||
'invoice' => 0,
|
||||
'invoice_no' => '',
|
||||
'kind' => 'pickup',
|
||||
'customer_name' => '',
|
||||
'street' => '',
|
||||
'city' => '',
|
||||
'delivery_street' => '',
|
||||
'delivery_city' => '',
|
||||
'kind' => in_array($kind, ['pickup', 'delivery'], true) ? $kind : 'pickup',
|
||||
'customer_name' => $customerName,
|
||||
'street' => $customerStreet,
|
||||
'city' => $customerCity,
|
||||
'delivery_street' => $deliveryStreet,
|
||||
'delivery_city' => $deliveryCity,
|
||||
'agreements' => '',
|
||||
'mobile' => '',
|
||||
'email' => '',
|
||||
'mobile' => $customerMobile,
|
||||
'email' => $customerEmail,
|
||||
'note' => '',
|
||||
];
|
||||
$errors = [];
|
||||
|
|
@ -1004,6 +1035,7 @@ function page_booking_edit(array $user, int $id, string $method): void
|
|||
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
|
||||
'deposit_required' => (int) ($booking['deposit_required'] ?? 0),
|
||||
'deposit_account_id' => (int) ($booking['deposit_account_id'] ?? 0) ?: (int) (deposit_accounts()[0]['id'] ?? 0),
|
||||
'deposit_amount' => number_format(booking_deposit_amount($booking) / 100, 2, ',', ''),
|
||||
'balance_method' => (string) ($booking['balance_method'] ?? 'cash') === 'transfer' ? 'transfer' : 'cash',
|
||||
'rent' => number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
|
||||
'delivery' => number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
|
||||
|
|
@ -1034,6 +1066,7 @@ function page_booking_edit(array $user, int $id, string $method): void
|
|||
$data['deposit_cents'] = (int) $booking['deposit_cents'];
|
||||
$data['deposit_required'] = (int) ($booking['deposit_required'] ?? 0);
|
||||
$data['deposit_account_id'] = (int) ($booking['deposit_account_id'] ?? 0);
|
||||
$data['deposit_amount_cents'] = booking_deposit_amount($booking);
|
||||
$data['balance_method'] = (string) ($booking['balance_method'] ?? 'cash') === 'transfer' ? 'transfer' : 'cash';
|
||||
$data['rent_cents'] = (int) $booking['rent_cents'];
|
||||
$data['delivery_cents'] = (int) $booking['delivery_cents'];
|
||||
|
|
@ -1087,8 +1120,8 @@ function booking_detail_context(array $booking, array $user): array
|
|||
'documentsMailEnabled' => mail_is_enabled(),
|
||||
'documentsRetention' => array_reduce(
|
||||
array_keys(document_kinds()),
|
||||
static function (array $carry, string $kind): array {
|
||||
$carry[$kind] = document_retention_text($kind);
|
||||
static function (array $carry, string $kind) use ($booking): array {
|
||||
$carry[$kind] = document_retention_text($kind, $booking);
|
||||
return $carry;
|
||||
},
|
||||
[]
|
||||
|
|
@ -1270,24 +1303,33 @@ function page_booking_document_action(array $user, string $method, int $bookingI
|
|||
if (!auth_can_edit_booking($user)) {
|
||||
abort_page(403, 'Dafür fehlt dir die Berechtigung.');
|
||||
}
|
||||
// Drei Unterschriften: Mitarbeiter bestätigt die Zahlung (handover),
|
||||
// Kunde die Übernahme (customer) bzw. die Rückgabe der Kaution (return).
|
||||
$role = post_string('role') !== '' ? post_string('role') : query_string('role');
|
||||
$role = document_sign_role_valid($role) ? $role : DOCUMENT_SIGN_CUSTOMER;
|
||||
if ($method === 'GET') {
|
||||
render_standalone('document_sign', [
|
||||
'booking' => $booking,
|
||||
'doc' => $doc,
|
||||
'role' => $role,
|
||||
'pageTitle' => 'Unterschrift Mietvertrag',
|
||||
], 'Unterschrift · ' . $booking['customer_name']);
|
||||
return;
|
||||
}
|
||||
require_post();
|
||||
try {
|
||||
document_save_signature($booking, $doc, post_string('signature'), (int) $user['id'], 'tablet');
|
||||
document_save_signature($booking, $doc, post_string('signature'), (int) $user['id'], 'tablet', $role);
|
||||
$mailUrl = '';
|
||||
if (mail_is_enabled() && filter_var((string) $booking['email'], FILTER_VALIDATE_EMAIL) !== false) {
|
||||
if ($role === DOCUMENT_SIGN_CUSTOMER
|
||||
&& mail_is_enabled()
|
||||
&& filter_var((string) $booking['email'], FILTER_VALIDATE_EMAIL) !== false
|
||||
) {
|
||||
$mailUrl = '/bookings/' . $bookingId . '/documents/' . $docId . '/mail';
|
||||
}
|
||||
render_standalone('document_sign_done', [
|
||||
'booking' => $booking,
|
||||
'doc' => document_find($docId) ?? $doc,
|
||||
'role' => $role,
|
||||
'mailed' => false,
|
||||
'backUrl' => '/bookings/' . $bookingId . '#unterlagen',
|
||||
'mailUrl' => $mailUrl,
|
||||
|
|
@ -1408,6 +1450,7 @@ function page_signature_public(string $method, string $token): void
|
|||
render_standalone('document_sign_done', [
|
||||
'booking' => $booking,
|
||||
'doc' => $result['doc'],
|
||||
'role' => DOCUMENT_SIGN_CUSTOMER,
|
||||
'mailed' => $result['mailed'],
|
||||
'backUrl' => '',
|
||||
'mailUrl' => '',
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ function privacy_cleanup(): array
|
|||
'reminder_mail_log' => 0,
|
||||
'reminder_push_log' => 0,
|
||||
'payment_reminder_log' => 0,
|
||||
'review_mail_log' => 0,
|
||||
'booking_documents' => 0,
|
||||
'log_rotated' => false,
|
||||
];
|
||||
|
|
@ -49,6 +50,11 @@ function privacy_cleanup(): array
|
|||
'DELETE FROM payment_reminder_log WHERE sent_at < ?',
|
||||
[utc_after(-365 * 86400)]
|
||||
);
|
||||
// Protokoll der Bewertungsmails (max. ein Jahr).
|
||||
$result['review_mail_log'] = privacy_delete(
|
||||
'DELETE FROM review_mail_log WHERE sent_at < ?',
|
||||
[utc_after(-365 * 86400)]
|
||||
);
|
||||
|
||||
// Buchungsunterlagen werden je nach Art gestaffelt nach dem Mietende
|
||||
// gelöscht (app.document_retention_days, document_retention_days()).
|
||||
|
|
|
|||
26
app/util.php
26
app/util.php
|
|
@ -349,6 +349,32 @@ function fmt_date_short_with_time(string $iso, ?string $time): string
|
|||
return $clock === '' ? fmt_date_short($iso) : fmt_date_short($iso) . ' ' . $clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Datum mit Wochentag, z. B. "Freitag 12.12.2027" – der Kunde möchte den Tag
|
||||
* überall dort sehen, wo ein Termin genannt wird.
|
||||
*/
|
||||
function fmt_date_weekday(string $iso): string
|
||||
{
|
||||
if (!valid_date($iso)) {
|
||||
return '–';
|
||||
}
|
||||
$days = ['', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
|
||||
return $days[(int) date_obj($iso)->format('N')] . ' ' . fmt_date($iso);
|
||||
}
|
||||
|
||||
/** Wie fmt_date_weekday(), optional mit Uhrzeit: "Freitag 12.12.2027 14:00". */
|
||||
function fmt_date_weekday_with_time(string $iso, ?string $time): string
|
||||
{
|
||||
$clock = fmt_time($time);
|
||||
return $clock === '' ? fmt_date_weekday($iso) : fmt_date_weekday($iso) . ' ' . $clock;
|
||||
}
|
||||
|
||||
/** Kurzform für Tabellen und Mails: "Fr 12.12.27". */
|
||||
function fmt_date_weekday_short(string $iso): string
|
||||
{
|
||||
return valid_date($iso) ? fmt_weekday_short($iso) . ' ' . fmt_date_short($iso) : '–';
|
||||
}
|
||||
|
||||
|
||||
function add_days(string $iso, int $days): string
|
||||
{
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue