drink-it-cold/app/mail.php
torsten 2de8e95c15 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.
2026-11-30 15:40:31 +01:00

202 lines
7.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/**
* E-Mail-Versand: optionaler täglicher Digest für fällige Erinnerungen und
* Einladungen für neue Benutzer.
*
* Die In-App-Erinnerungen sind immer vorhanden. Der Digest ist zusätzlich
* und wird über tools/send_reminders.php (Cron) oder /cron/reminders?token=…
* ausgelöst. Jede Erinnerung wird genau einmal verschickt; das Protokoll steht
* in reminder_mail_log.
*
* Eingeschaltet wird der Versand über app.mail_enabled. Ist er aus, bleibt die
* App vollständig nutzbar; Einladungslinks zeigt der Admin dann selbst an.
*/
function mail_is_enabled(): bool
{
return (bool) config('app.mail_enabled', false);
}
/**
* Verschickt eine reine Textnachricht. Absender kommt aus app.mail_from.
* Der Aufrufer prüft mail_is_enabled() und die Empfängeradresse.
*
* $extraHeaders erlaubt zusätzliche Kopfzeilen (z. B. Reply-To für das
* Anfrageformular); Zeilenumbrüche werden entfernt, damit niemand weitere
* Header einschleusen kann.
*
* @param list<string> $extraHeaders
*/
function mail_send(string $to, string $subject, string $body, array $extraHeaders = []): bool
{
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
return false;
}
$headers = [
'From: ' . (string) config('app.mail_from', 'Drink it cold <noreply@localhost>'),
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
];
foreach ($extraHeaders as $header) {
$clean = trim(preg_replace('/[\r\n]+/', ' ', $header) ?? '');
if ($clean !== '') {
$headers[] = $clean;
}
}
return @mail(
$to,
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
$body,
implode("\r\n", $headers)
);
}
/**
* Verschickt eine Textnachricht mit einem Dateianhang (multipart/mixed).
*
* Gedacht für Buchungsunterlagen (Mietvertrag, Auftragsbestätigung, Rechnung).
* Der Anhang wird Base64-kodiert; Dateiname und MIME-Typ kommen vom Aufrufer.
*/
function mail_send_attachment(
string $to,
string $subject,
string $body,
string $fileName,
string $mimeType,
string $data
): bool {
if (!filter_var($to, FILTER_VALIDATE_EMAIL) || $data === '') {
return false;
}
$safeName = trim((string) preg_replace('/[\r\n"]+/', '', $fileName));
$safeType = trim((string) preg_replace('/[\r\n]+/', '', $mimeType));
$boundary = 'dic-' . bin2hex(random_bytes(12));
$headers = [
'From: ' . (string) config('app.mail_from', 'Drink it cold <noreply@localhost>'),
'MIME-Version: 1.0',
'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
];
$parts = [
'--' . $boundary,
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
'',
$body,
'--' . $boundary,
'Content-Type: ' . $safeType . '; name="' . $safeName . '"',
'Content-Transfer-Encoding: base64',
'Content-Disposition: attachment; filename="' . $safeName . '"',
'',
chunk_split(base64_encode($data), 76, "\r\n"),
'--' . $boundary . '--',
];
return @mail(
$to,
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
implode("\r\n", $parts),
implode("\r\n", $headers)
);
}
function reminder_mail_recipients(): array
{
$sql = "SELECT u.employee_id, u.email, u.first_name, u.last_name, e.name AS employee_name
FROM users u JOIN employees e ON e.id = u.employee_id
WHERE u.status = 'active' AND u.employee_id IS NOT NULL AND u.email IS NOT NULL AND u.email <> ''
ORDER BY e.sort_order";
$out = [];
foreach (db()->query($sql)->fetchAll() as $row) {
$out[(int) $row['employee_id']] = $row;
}
return $out;
}
/**
* Verschickt alle offenen, heute (oder in den letzten 7 Tagen) fälligen
* Erinnerungen als einen Digest pro Mitarbeiter.
*
* @return array{enabled: bool, sent: int, skipped: int, errors: array, details: array}
*/
function reminder_send_due(int $lookbackDays = 7): array
{
$result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
if (!$result['enabled']) {
return $result;
}
$today = today_iso();
$from = add_days($today, -max(1, $lookbackDays));
$recipients = reminder_mail_recipients();
$rows = reminder_list($from, $today, 0, false, REMINDER_SEND_MIN_AGE_MINUTES);
if (!$rows) {
return $result;
}
$byEmployee = [];
foreach ($rows as $row) {
// Rücknahme-Erinnerungen gehören ggf. dem abweichend zugewiesenen Mitarbeiter.
$employeeId = booking_employee_for_kind($row['booking'], (string) $row['kind']);
if (!isset($recipients[$employeeId])) {
$result['skipped']++;
continue;
}
// Bereits verschickt?
$stmt = db()->prepare('SELECT 1 FROM reminder_mail_log WHERE booking_id = ? AND kind = ? AND due_date = ?');
$stmt->execute([(int) $row['booking']['id'], $row['kind'], $row['due_date']]);
if ($stmt->fetchColumn()) {
$result['skipped']++;
continue;
}
$byEmployee[$employeeId][] = $row;
}
$appUrl = rtrim((string) config('app.public_url', ''), '/');
foreach ($byEmployee as $employeeId => $items) {
$recipient = $recipients[$employeeId];
$lines = [
'Guten Tag ' . $recipient['employee_name'] . ',',
'',
'diese Erinnerungen stehen an:',
'',
];
foreach ($items as $item) {
$booking = $item['booking'];
$lines[] = '• ' . fmt_date($item['due_date']) . ' – ' . $item['label'];
$lines[] = ' ' . $item['message'];
$lines[] = ' ' . $booking['customer_name'] . ', ' . $booking['trailer_label'] . ' (' . $booking['trailer_color_name'] . ')';
$lines[] = ' Miete: ' . fmt_date($booking['start_date']) . ' bis ' . fmt_date($booking['end_date']);
if ($appUrl !== '') {
$lines[] = ' ' . $appUrl . '/bookings/' . (int) $booking['id'];
}
$lines[] = '';
}
$lines[] = 'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.';
$body = implode("\n", $lines);
$subject = 'Drink it cold – ' . count($items) . ' fällige Erinnerung' . (count($items) === 1 ? '' : 'en');
$ok = mail_send((string) $recipient['email'], $subject, $body);
if (!$ok) {
$result['errors'][] = 'Versand an ' . $recipient['email'] . ' fehlgeschlagen.';
continue;
}
$log = db()->prepare(
'INSERT IGNORE INTO reminder_mail_log (booking_id, kind, due_date, employee_id, sent_to, sent_at)
VALUES (?, ?, ?, ?, ?, ?)'
);
foreach ($items as $item) {
$log->execute([
(int) $item['booking']['id'], $item['kind'], $item['due_date'],
$employeeId, (string) $recipient['email'], utc_now(),
]);
$result['sent']++;
}
$result['details'][] = $recipient['email'] . ' (' . count($items) . ')';
}
return $result;
}