feat(mailing): Kundenrundmail mit Empfängern aus Buchungen, Abmeldelink und Versandprotokoll
Empfänger kommen aus bookings.email (dedupliziert, ohne Abmeldungen), Text mit
{jahr}, Testmail an die eigene Adresse, Versand in Häppchen über mail_send().
Abmeldungen landen in mail_optouts und gelten für alle künftigen Rundmails.
Migration 009_mailing.sql, DSGVO-Verzeichnis und ROADMAP (Feature 18) ergänzt.
This commit is contained in:
parent
1adc3c8f33
commit
5cce6ca86f
11 changed files with 657 additions and 1 deletions
|
|
@ -73,3 +73,9 @@
|
|||
- [x] **Feature 17: „Frei bis …“ bei freien Anhängern auf der Übersicht**
|
||||
- **Umsetzung:** `next_booking_start()` liefert die nächste Buchung; `page_dashboard()` gibt `free_until` (Tag vor Mietbeginn) je Anhänger mit, `views/dashboard.php` zeigt „Frei bis <Datum> – neue Buchung möglich“.
|
||||
- **Prüfung:** Anhänger mit Buchung in 10 Tagen zeigt „Frei bis <Datum vor Mietbeginn>“, Anhänger ohne Buchung den bisherigen Text, Anhänger mit heutiger Buchung unverändert.
|
||||
|
||||
## Kundenwunsch vom 30.11.2026
|
||||
|
||||
- [x] **Feature 18: Kundenrundmail (Dankeschön zum Jahresende)**
|
||||
- **Umsetzung:** Migration `009_mailing.sql` (`mail_optouts`, `mailings`, `mailing_recipients`); `app/mailing.php` zieht die Empfänger aus `bookings.email` (dedupliziert, ohne ungültige Adressen und ohne Abmeldungen), legt Kampagnen an und versendet in Häppchen von 25 Mails über `mail_send()`. Admin-Seite `/admin/mailings` mit Empfängerzahl, Testmail an die eigene Adresse, Anlegen und „Weiter senden“; Footer mit Herkunftshinweis und signiertem Abmeldelink auf `/abmelden`, der die Adresse in `mail_optouts` einträgt.
|
||||
- **Prüfung:** Rundmail anlegen – Empfängerzahl entspricht den Kunden mit Buchung; Testmail enthält Abmeldelink; Abmeldung über den Link reduziert die Zahl der offenen Empfänger und die Gesamtempfänger; nach dem letzten Häppchen steht „fertig“.
|
||||
|
|
|
|||
|
|
@ -42,6 +42,10 @@ function admin_handle(string $path, array $user): void
|
|||
admin_reminders_send();
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/mailings') {
|
||||
admin_mailings($user);
|
||||
return;
|
||||
}
|
||||
|
||||
abort_page(404, 'Diese Verwaltungsseite gibt es nicht.');
|
||||
}
|
||||
|
|
@ -586,3 +590,84 @@ function admin_reminders_send(): void
|
|||
flash($mail['errors'] ? 'error' : 'success', implode(' ', $parts));
|
||||
redirect('/reminders');
|
||||
}
|
||||
|
||||
/**
|
||||
* Kundenrundmail: Empfänger aus den Buchungen, Text mit {jahr}, Testmail und
|
||||
* Versand in Häppchen. Abmeldungen landen in mail_optouts (app/mailing.php).
|
||||
*/
|
||||
function admin_mailings(array $user): void
|
||||
{
|
||||
$values = ['subject' => '', 'body' => ''];
|
||||
$errors = [];
|
||||
|
||||
if (is_post()) {
|
||||
require_post();
|
||||
$action = post_string('action');
|
||||
|
||||
if ($action === 'test' || $action === 'create') {
|
||||
$values['subject'] = trim(post_string('subject'));
|
||||
$values['body'] = trim(post_string('body'));
|
||||
if (mb_strlen($values['subject']) < 3 || mb_strlen($values['subject']) > 190) {
|
||||
$errors['subject'] = 'Bitte einen Betreff mit 3 bis 190 Zeichen angeben.';
|
||||
}
|
||||
if (mb_strlen($values['body']) < 10 || mb_strlen($values['body']) > 5000) {
|
||||
$errors['body'] = 'Bitte einen Text mit 10 bis 5000 Zeichen angeben.';
|
||||
}
|
||||
if (!$errors && !mail_is_enabled()) {
|
||||
$errors['body'] = 'Der Mailversand ist in der Konfiguration ausgeschaltet (app.mail_enabled).';
|
||||
}
|
||||
|
||||
if (!$errors && $action === 'test') {
|
||||
$to = (string) ($user['email'] ?? '');
|
||||
$ok = mailing_send_test($values['subject'], $values['body'], $to);
|
||||
flash($ok ? 'success' : 'error', $ok
|
||||
? 'Testmail an ' . $to . ' verschickt (mit Abmeldelink im Text).'
|
||||
: 'Testmail konnte nicht verschickt werden – bitte Absenderadresse prüfen.');
|
||||
redirect('/admin/mailings');
|
||||
}
|
||||
|
||||
if (!$errors && $action === 'create') {
|
||||
$created = mailing_create($values['subject'], $values['body'], (int) $user['id']);
|
||||
if ($created['count'] === 0) {
|
||||
flash('error', 'Es gibt derzeit keine Empfänger: keine Buchung mit gültiger E-Mail-Adresse.');
|
||||
} else {
|
||||
flash('success', 'Rundmail angelegt – ' . $created['count']
|
||||
. ' Empfänger. Der Versand läuft in Häppchen, bis alle durch sind.');
|
||||
}
|
||||
redirect('/admin/mailings');
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'send') {
|
||||
$id = (int) post_string('mailing_id');
|
||||
$mailing = $id > 0 ? mailing_find($id) : null;
|
||||
if (!$mailing) {
|
||||
abort_page(404, 'Diese Rundmail gibt es nicht.');
|
||||
}
|
||||
if (!mail_is_enabled()) {
|
||||
flash('error', 'Der Mailversand ist in der Konfiguration ausgeschaltet (app.mail_enabled).');
|
||||
redirect('/admin/mailings');
|
||||
}
|
||||
$result = mailing_send_batch($id, (int) post_string('batch', (string) MAILING_BATCH_DEFAULT));
|
||||
$message = sprintf('%d verschickt, %d fehlgeschlagen, %d offen.',
|
||||
$result['sent'], $result['failed'], $result['remaining']);
|
||||
flash($result['failed'] > 0 ? 'info' : 'success', $message);
|
||||
redirect('/admin/mailings');
|
||||
}
|
||||
}
|
||||
|
||||
$mailings = mailing_list();
|
||||
foreach ($mailings as $index => $mailing) {
|
||||
$mailings[$index]['pending'] = mailing_pending_count((int) $mailing['id']);
|
||||
}
|
||||
|
||||
render_page('admin_mailings', [
|
||||
'recipients' => mailing_recipients(),
|
||||
'optoutCount' => mailing_optout_count(),
|
||||
'mailings' => $mailings,
|
||||
'values' => $values,
|
||||
'errors' => $errors,
|
||||
'mailEnabled' => mail_is_enabled(),
|
||||
'batchSize' => MAILING_BATCH_DEFAULT,
|
||||
], 'Kundenrundmail');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ require DIC_APP . '/auth.php';
|
|||
require DIC_APP . '/data.php';
|
||||
require DIC_APP . '/push.php';
|
||||
require DIC_APP . '/mail.php';
|
||||
require DIC_APP . '/mailing.php';
|
||||
require DIC_APP . '/inquiry.php';
|
||||
require DIC_APP . '/invite.php';
|
||||
require DIC_APP . '/privacy.php';
|
||||
|
|
@ -65,7 +66,7 @@ if (PHP_SAPI !== 'cli') {
|
|||
$path = current_path();
|
||||
$legalPublic = legal_is_public_path($path);
|
||||
security_headers($legalPublic);
|
||||
$sessionFree = ['/health', '/cron/reminders', '/anfrage'];
|
||||
$sessionFree = ['/health', '/cron/reminders', '/anfrage', '/abmelden'];
|
||||
if (!$legalPublic && !in_array($path, $sessionFree, true)) {
|
||||
start_session();
|
||||
}
|
||||
|
|
|
|||
278
app/mailing.php
Normal file
278
app/mailing.php
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Kundenrundmail (z. B. Dankeschön zum Jahresende).
|
||||
*
|
||||
* Empfänger werden aus den Buchungen gezogen: jede Buchung speichert bereits
|
||||
* eine E-Mail-Adresse im Feld bookings.email. Es gibt deshalb keine eigene
|
||||
* Kundenliste – die Empfängerliste ist immer der aktuelle Stand der Buchungen,
|
||||
* abzüglich der Adressen, die sich abgemeldet haben (mail_optouts).
|
||||
*
|
||||
* Versand läuft in Häppchen (mailing_send_batch), damit Shared-Hosting-Limits
|
||||
* und Timeouts nicht zuschlagen. Jede Mail geht einzeln raus (kein BCC), damit
|
||||
* Zustellbarkeit und persönliche Anrede stimmen. Der Stand steht je Empfänger
|
||||
* in mailing_recipients.
|
||||
*/
|
||||
|
||||
const MAILING_BATCH_DEFAULT = 25;
|
||||
|
||||
/**
|
||||
* Empfängerliste: alle Kunden mit gültiger Adresse in einer Buchung,
|
||||
* ohne Abmeldungen. Sortiert nach Adresse, damit der Versand reproduzierbar ist.
|
||||
*
|
||||
* @return list<array{email: string, bookings: int, last_booking: ?string}>
|
||||
*/
|
||||
function mailing_recipients(): array
|
||||
{
|
||||
$sql = "SELECT LOWER(b.email) AS email,
|
||||
COUNT(*) AS bookings,
|
||||
MAX(b.start_date) AS last_booking
|
||||
FROM bookings b
|
||||
WHERE b.email <> ''
|
||||
AND NOT EXISTS (SELECT 1 FROM mail_optouts o WHERE o.email = LOWER(b.email))
|
||||
GROUP BY LOWER(b.email)
|
||||
ORDER BY email";
|
||||
$rows = [];
|
||||
foreach (db()->query($sql)->fetchAll() as $row) {
|
||||
$email = (string) $row['email'];
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = [
|
||||
'email' => $email,
|
||||
'bookings' => (int) $row['bookings'],
|
||||
'last_booking' => $row['last_booking'] !== null ? (string) $row['last_booking'] : null,
|
||||
];
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
function mailing_optout_emails(): array
|
||||
{
|
||||
return array_map('strval', db()->query('SELECT email FROM mail_optouts ORDER BY email')
|
||||
->fetchAll(PDO::FETCH_COLUMN));
|
||||
}
|
||||
|
||||
function mailing_optout_count(): int
|
||||
{
|
||||
return (int) db()->query('SELECT COUNT(*) FROM mail_optouts')->fetchColumn();
|
||||
}
|
||||
|
||||
function mailing_is_optout(string $email): bool
|
||||
{
|
||||
try {
|
||||
$stmt = db()->prepare('SELECT 1 FROM mail_optouts WHERE email = ? LIMIT 1');
|
||||
$stmt->execute([mb_strtolower(trim($email))]);
|
||||
return (bool) $stmt->fetchColumn();
|
||||
} catch (Throwable) {
|
||||
// Fehlende Migration darf die öffentliche Abmeldeseite nicht sprengen.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function mailing_optout_add(string $email, string $source = 'link'): bool
|
||||
{
|
||||
$email = mb_strtolower(trim($email));
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$stmt = db()->prepare('INSERT IGNORE INTO mail_optouts (email, source, created_at) VALUES (?, ?, ?)');
|
||||
return $stmt->execute([$email, mb_substr($source, 0, 40), utc_now()]);
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Signatur für Abmeldelinks: HMAC über die Adresse, damit Links nicht ratbar sind. */
|
||||
function mailing_unsub_token(string $email): string
|
||||
{
|
||||
$secret = (string) config('app.cron_token', '');
|
||||
if ($secret === '') {
|
||||
$secret = (string) config('app.install_token', 'drink-it-cold');
|
||||
}
|
||||
return hash_hmac('sha256', mb_strtolower(trim($email)), $secret);
|
||||
}
|
||||
|
||||
function mailing_unsub_url(string $email): string
|
||||
{
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
return $base . '/abmelden?e=' . rawurlencode(mb_strtolower(trim($email)))
|
||||
. '&t=' . mailing_unsub_token($email);
|
||||
}
|
||||
|
||||
function mailing_unsub_valid(string $email, string $token): bool
|
||||
{
|
||||
return $token !== '' && hash_equals(mailing_unsub_token($email), $token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt den Text zusammen: Admin-Text plus Pflicht-Fußzeile mit Abmeldelink.
|
||||
* {jahr} wird durch das laufende Jahr ersetzt.
|
||||
*/
|
||||
function mailing_body_for(string $body, string $email): string
|
||||
{
|
||||
$body = str_replace('{jahr}', date('Y'), trim($body));
|
||||
$footer = "—\n"
|
||||
. "Sie erhalten diese Nachricht, weil Sie bei Drink it cold einen Kühlanhänger gebucht haben.\n"
|
||||
. 'Keine solchen Nachrichten mehr? Hier abmelden: ' . mailing_unsub_url($email);
|
||||
return $body . "\n\n" . $footer . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt eine Kampagne an und friert die aktuelle Empfängerliste ein.
|
||||
*
|
||||
* @return array{id: int, count: int}
|
||||
*/
|
||||
function mailing_create(string $subject, string $body, ?int $userId): array
|
||||
{
|
||||
$subject = trim($subject);
|
||||
$body = trim($body);
|
||||
$recipients = mailing_recipients();
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
$stmt = $pdo->prepare('INSERT INTO mailings (subject, body, recipient_count, created_at, created_by) VALUES (?, ?, ?, ?, ?)');
|
||||
$stmt->execute([$subject, $body, count($recipients), utc_now(), $userId]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
|
||||
$insert = $pdo->prepare("INSERT IGNORE INTO mailing_recipients (mailing_id, email, status) VALUES (?, ?, 'pending')");
|
||||
foreach ($recipients as $recipient) {
|
||||
$insert->execute([$id, $recipient['email']]);
|
||||
}
|
||||
$pdo->commit();
|
||||
} catch (Throwable $e) {
|
||||
$pdo->rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return ['id' => $id, 'count' => count($recipients)];
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
function mailing_list(int $limit = 20): array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT m.*, u.first_name, u.last_name
|
||||
FROM mailings m LEFT JOIN users u ON u.id = m.created_by
|
||||
ORDER BY m.id DESC LIMIT ' . (int) $limit);
|
||||
$stmt->execute();
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
function mailing_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM mailings WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
function mailing_pending_count(int $id): int
|
||||
{
|
||||
$stmt = db()->prepare("SELECT COUNT(*) FROM mailing_recipients WHERE mailing_id = ? AND status = 'pending'");
|
||||
$stmt->execute([$id]);
|
||||
return (int) $stmt->fetchColumn();
|
||||
}
|
||||
|
||||
function mailing_refresh_counts(int $id): void
|
||||
{
|
||||
$stmt = db()->prepare("UPDATE mailings SET
|
||||
sent_count = (SELECT COUNT(*) FROM mailing_recipients WHERE mailing_id = ? AND status = 'sent'),
|
||||
failed_count = (SELECT COUNT(*) FROM mailing_recipients WHERE mailing_id = ? AND status = 'failed'),
|
||||
finished_at = CASE WHEN (SELECT COUNT(*) FROM mailing_recipients WHERE mailing_id = ? AND status = 'pending') = 0
|
||||
THEN COALESCE(finished_at, ?) ELSE NULL END
|
||||
WHERE id = ?");
|
||||
$stmt->execute([$id, $id, $id, utc_now(), $id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt die nächsten offenen Empfänger einer Kampagne.
|
||||
*
|
||||
* @return array{sent: int, failed: int, remaining: int}
|
||||
*/
|
||||
function mailing_send_batch(int $id, int $limit = MAILING_BATCH_DEFAULT): array
|
||||
{
|
||||
$mailing = mailing_find($id);
|
||||
if (!$mailing) {
|
||||
return ['sent' => 0, 'failed' => 0, 'remaining' => 0];
|
||||
}
|
||||
|
||||
$limit = max(1, min(100, $limit));
|
||||
$pdo = db();
|
||||
$stmt = $pdo->prepare("SELECT email FROM mailing_recipients
|
||||
WHERE mailing_id = ? AND status = 'pending' ORDER BY email LIMIT " . $limit);
|
||||
$stmt->execute([$id]);
|
||||
$emails = array_map('strval', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
||||
|
||||
$markSent = $pdo->prepare("UPDATE mailing_recipients SET status = 'sent', sent_at = ?, error = '' WHERE mailing_id = ? AND email = ?");
|
||||
$markFailed = $pdo->prepare("UPDATE mailing_recipients SET status = 'failed', error = ? WHERE mailing_id = ? AND email = ?");
|
||||
|
||||
$sent = 0;
|
||||
$failed = 0;
|
||||
foreach ($emails as $email) {
|
||||
// Abmeldungen, die nach dem Anlegen der Kampagne kamen, respektieren.
|
||||
if (mailing_is_optout($email)) {
|
||||
$markFailed->execute(['abgemeldet', $id, $email]);
|
||||
$failed++;
|
||||
continue;
|
||||
}
|
||||
$ok = mail_send($email, (string) $mailing['subject'], mailing_body_for((string) $mailing['body'], $email));
|
||||
if ($ok) {
|
||||
$markSent->execute([utc_now(), $id, $email]);
|
||||
$sent++;
|
||||
} else {
|
||||
$markFailed->execute(['Versand fehlgeschlagen', $id, $email]);
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
mailing_refresh_counts($id);
|
||||
return ['sent' => $sent, 'failed' => $failed, 'remaining' => mailing_pending_count($id)];
|
||||
}
|
||||
|
||||
/** Testmail an eine eigene Adresse – ohne Eintrag in einer Kampagne. */
|
||||
function mailing_send_test(string $subject, string $body, string $to): bool
|
||||
{
|
||||
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||
return false;
|
||||
}
|
||||
return mail_send($to, '[Test] ' . trim($subject), mailing_body_for($body, $to));
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentliche Abmeldeseite /abmelden?e=…&t=…
|
||||
* GET zeigt die Bestätigung, POST trägt die Adresse in die Sperrliste ein.
|
||||
*/
|
||||
function page_unsubscribe(string $method): void
|
||||
{
|
||||
$email = mb_strtolower(trim(query_string('e')));
|
||||
$token = query_string('t');
|
||||
$valid = filter_var($email, FILTER_VALIDATE_EMAIL) && mailing_unsub_valid($email, $token);
|
||||
|
||||
$done = false;
|
||||
$error = '';
|
||||
if ($method === 'POST') {
|
||||
$email = mb_strtolower(trim(post_string('e')));
|
||||
$token = post_string('t');
|
||||
$valid = filter_var($email, FILTER_VALIDATE_EMAIL) && mailing_unsub_valid($email, $token);
|
||||
if (!$valid) {
|
||||
$error = 'Dieser Abmeldelink ist ungültig oder unvollständig.';
|
||||
} else {
|
||||
mailing_optout_add($email, 'abmeldelink');
|
||||
$done = true;
|
||||
}
|
||||
}
|
||||
|
||||
render_standalone('mailing_abmelden', [
|
||||
'email' => $email,
|
||||
'token' => $token,
|
||||
'valid' => $valid,
|
||||
'done' => $done,
|
||||
'error' => $error,
|
||||
'already' => $valid && !$done && mailing_is_optout($email),
|
||||
], 'Rundmail abbestellen');
|
||||
}
|
||||
|
|
@ -66,6 +66,10 @@ function page_handle(string $method, string $path): void
|
|||
page_inquiry($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/abmelden') {
|
||||
page_unsubscribe($method);
|
||||
return;
|
||||
}
|
||||
|
||||
$user = auth_user();
|
||||
if ($user !== null && $user['must_change_password'] === 1
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ in `app/config.local.php` kann die Werte überschreiben. Bei inhaltlichen
|
|||
| Remember-Me | Nutzer | Selector, Hash eines Tokens, Ablaufdatum | „Angemeldet bleiben“ | § 25 Abs. 2 TDDDG, Art. 6 Abs. 1 lit. b/f DSGVO | 90 Tage |
|
||||
| Erinnerungen | Mitarbeiter | Buchungsbezug, Art, Fälligkeit, Erlediger, Zeitpunkt | Aufgabenverwaltung | Art. 6 Abs. 1 lit. b/f DSGVO | mit Buchung |
|
||||
| E-Mail-Digest | Mitarbeiter | E-Mail, Name, Buchungsdaten, Versandzeit | dienstliche Erinnerung | § 26 Abs. 1 BDSG, Art. 6 Abs. 1 lit. b/f DSGVO | Protokoll 1 Jahr |
|
||||
| Kundenrundmail | Kunden mit Buchung | E-Mail, Betreff/Text der Rundmail, Versandstatus, Abmeldungen (`mail_optouts`) | Bestandskundenpflege (Dankeschön, Hinweis auf rechtzeitige Reservierung) | Art. 6 Abs. 1 lit. f DSGVO, § 7 Abs. 3 UWG | Versandprotokoll und Sperrliste bis Widerruf, Protokolle jährlich prüfen und alte Kampagnen löschen |
|
||||
| Web Push | Mitarbeiter | Endpoint, p256dh, auth, User-Agent, Zeitstempel, Fehlerstatus | Erinnerungen aufs Gerät | Art. 6 Abs. 1 lit. a DSGVO | bis Widerruf/Kontolöschung |
|
||||
| Abwesenheiten | Mitarbeiter | Name, Zeitraum, optionaler Hinweis (z. B. Urlaub/Krankheit) | Einsatzplanung, Erreichbarkeit, Schutz vor Einplanung | § 26 Abs. 1 BDSG, Art. 6 Abs. 1 lit. b/f DSGVO; bei Gesundheitsangaben Art. 9 Abs. 2 lit. b DSGVO i. V. m. § 26 Abs. 3 BDSG | bis Ende des Abwesenheitszeitraums, danach manuell löschbar |
|
||||
| Server-Logfiles | Besucher/Nutzer | IP, Zeit, URL, Status, Datenmenge, Referrer, User-Agent | Betriebssicherheit, Fehleranalyse | Art. 6 Abs. 1 lit. f DSGVO | in der Regel max. 30 Tage |
|
||||
|
|
|
|||
35
sql/migrations/009_mailing.sql
Normal file
35
sql/migrations/009_mailing.sql
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
-- Kundenrundmail: Sperrliste (Abmeldungen) und Versandprotokoll.
|
||||
-- Empfänger sind nicht gespeichert – sie werden je Kampagne aus bookings.email
|
||||
-- gezogen (siehe app/mailing.php).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mail_optouts (
|
||||
email VARCHAR(190) NOT NULL,
|
||||
source VARCHAR(40) NOT NULL DEFAULT '',
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (email)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mailings (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
subject VARCHAR(190) NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
recipient_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
sent_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
failed_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
created_by BIGINT UNSIGNED NULL DEFAULT NULL,
|
||||
finished_at DATETIME NULL DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_mailings_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mailing_recipients (
|
||||
mailing_id BIGINT UNSIGNED NOT NULL,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
status ENUM('pending', 'sent', 'failed') NOT NULL DEFAULT 'pending',
|
||||
error VARCHAR(190) NOT NULL DEFAULT '',
|
||||
sent_at DATETIME NULL DEFAULT NULL,
|
||||
PRIMARY KEY (mailing_id, email),
|
||||
KEY idx_mailing_recipients_status (mailing_id, status),
|
||||
CONSTRAINT fk_mailing_recipients_mailing FOREIGN KEY (mailing_id) REFERENCES mailings (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
|
@ -242,3 +242,38 @@ CREATE TABLE IF NOT EXISTS absences (
|
|||
CONSTRAINT fk_absences_created_by FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_absences_updated_by FOREIGN KEY (updated_by) REFERENCES users (id) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Kundenrundmail: Sperrliste für Abmeldungen und Versandprotokoll.
|
||||
-- Empfänger werden je Kampagne aus bookings.email gezogen (app/mailing.php).
|
||||
CREATE TABLE IF NOT EXISTS mail_optouts (
|
||||
email VARCHAR(190) NOT NULL,
|
||||
source VARCHAR(40) NOT NULL DEFAULT '',
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (email)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mailings (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
subject VARCHAR(190) NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
recipient_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
sent_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
failed_count INT UNSIGNED NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
created_by BIGINT UNSIGNED NULL DEFAULT NULL,
|
||||
finished_at DATETIME NULL DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_mailings_created (created_at),
|
||||
CONSTRAINT fk_mailings_created_by FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mailing_recipients (
|
||||
mailing_id BIGINT UNSIGNED NOT NULL,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
status ENUM('pending', 'sent', 'failed') NOT NULL DEFAULT 'pending',
|
||||
error VARCHAR(190) NOT NULL DEFAULT '',
|
||||
sent_at DATETIME NULL DEFAULT NULL,
|
||||
PRIMARY KEY (mailing_id, email),
|
||||
KEY idx_mailing_recipients_status (mailing_id, status),
|
||||
CONSTRAINT fk_mailing_recipients_mailing FOREIGN KEY (mailing_id) REFERENCES mailings (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ $items = [
|
|||
'/admin/users' => ['label' => 'Benutzer', 'icon' => 'i-user'],
|
||||
'/admin/employees' => ['label' => 'Mitarbeiter', 'icon' => 'i-users'],
|
||||
'/admin/trailers' => ['label' => 'Anhänger', 'icon' => 'i-truck'],
|
||||
'/admin/mailings' => ['label' => 'Rundmail', 'icon' => 'i-mail'],
|
||||
];
|
||||
?>
|
||||
<nav class="admin-nav" aria-label="Verwaltung">
|
||||
|
|
|
|||
154
views/admin_mailings.php
Normal file
154
views/admin_mailings.php
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
<?php
|
||||
/** @var list<array{email: string, bookings: int, last_booking: ?string}> $recipients */
|
||||
/** @var int $optoutCount */
|
||||
/** @var list<array<string, mixed>> $mailings */
|
||||
/** @var array{subject: string, body: string} $values */
|
||||
/** @var array<string, string> $errors */
|
||||
/** @var bool $mailEnabled */
|
||||
/** @var int $batchSize */
|
||||
$errorFor = static fn (string $key): string => (string) ($errors[$key] ?? '');
|
||||
$lastBooking = $recipients ? (string) ($recipients[count($recipients) - 1]['last_booking'] ?? '') : '';
|
||||
?>
|
||||
<div class="page-head page-head--compact">
|
||||
<div>
|
||||
<p class="eyebrow">Verwaltung</p>
|
||||
<h1>Kundenrundmail</h1>
|
||||
<p class="page-head__lede">Dankeschön oder Saisonhinweis an alle Kunden, die gebucht haben.
|
||||
Die Adressen kommen aus den Buchungen – gepflegt wird nichts doppelt. Text mit
|
||||
<code>{jahr}</code> setzt automatisch das laufende Jahr ein.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require __DIR__ . '/_admin_nav.php'; ?>
|
||||
|
||||
<?php if (!$mailEnabled): ?>
|
||||
<div class="alert alert--warning" role="status">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
|
||||
<div><strong>Mailversand ist ausgeschaltet.</strong>
|
||||
<p>In der Konfiguration steht <code>app.mail_enabled</code> auf aus. Anlegen und Testen ist
|
||||
möglich, der Versand an Kunden nicht.</p>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<div>
|
||||
<h2>Empfänger</h2>
|
||||
<p><?= count($recipients) ?> Kunden mit gültiger Adresse in einer Buchung<?= $lastBooking !== '' ? ', letzte Buchung am ' . e(date('d.m.Y', strtotime($lastBooking))) : '' ?>.</p>
|
||||
</div>
|
||||
<div class="panel__actions">
|
||||
<span class="muted small"><?= $optoutCount ?> abgemeldet</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="muted small">Abgemeldete Adressen werden automatisch übersprungen. Jede Mail enthält einen
|
||||
Abmeldelink; Buchungsbestätigungen und Erinnerungen bleiben davon unberührt.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<div>
|
||||
<h2>Neue Rundmail</h2>
|
||||
<p>Erst als Testmail an die eigene Adresse schicken, dann anlegen. Der Versand läuft danach in
|
||||
Häppchen von <?= (int) $batchSize ?> Mails.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($errors): ?>
|
||||
<div class="alert alert--error" role="alert">
|
||||
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
|
||||
<div><strong>Bitte die markierten Felder prüfen.</strong>
|
||||
<?php foreach ($errors as $message): ?><p><?= e($message) ?></p><?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" action="<?= e(url('/admin/mailings')) ?>" class="form-grid form-grid--single">
|
||||
<?= csrf_field() ?>
|
||||
<label class="field<?= $errorFor('subject') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Betreff</span>
|
||||
<input type="text" name="subject" value="<?= e($values['subject']) ?>" maxlength="190" required
|
||||
placeholder="Zum Jahresende: vielen Dank für Ihr Vertrauen in {jahr}">
|
||||
<?php if ($errorFor('subject')): ?><em class="field-error"><?= e($errorFor('subject')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<label class="field<?= $errorFor('body') !== '' ? ' has-error' : '' ?>">
|
||||
<span>Text</span>
|
||||
<textarea name="body" rows="10" maxlength="5000" required
|
||||
placeholder="Hallo liebe Kundin, hallo lieber Kunde, wir sagen Danke für {jahr} …"><?= e($values['body']) ?></textarea>
|
||||
<?php if ($errorFor('body')): ?><em class="field-error"><?= e($errorFor('body')) ?></em><?php endif; ?>
|
||||
</label>
|
||||
|
||||
<p class="muted small">Abschließend setzt das System automatisch den Satz „Sie erhalten diese
|
||||
Nachricht, weil Sie bei Drink it cold einen Kühlanhänger gebucht haben.“ und den Abmeldelink
|
||||
darunter.</p>
|
||||
|
||||
<div class="btn-row">
|
||||
<button type="submit" name="action" value="test" class="btn">Testmail an mich</button>
|
||||
<button type="submit" name="action" value="create" class="btn primary">An <?= count($recipients) ?> Kunden anlegen</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<div>
|
||||
<h2>Bisherige Rundmails</h2>
|
||||
<p>Der Stand je Empfänger steht im Protokoll; „Weiter senden“ schickt die nächste Häppchen-Größe.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!$mailings): ?>
|
||||
<p class="muted">Noch keine Rundmail angelegt.</p>
|
||||
<?php else: ?>
|
||||
<div class="table-wrap">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Angelegt</th>
|
||||
<th scope="col">Betreff</th>
|
||||
<th scope="col">Empfänger</th>
|
||||
<th scope="col">Stand</th>
|
||||
<th scope="col">Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($mailings as $mailing): ?>
|
||||
<?php
|
||||
$pending = (int) $mailing['pending'];
|
||||
$sent = (int) $mailing['sent_count'];
|
||||
$failed = (int) $mailing['failed_count'];
|
||||
$total = (int) $mailing['recipient_count'];
|
||||
?>
|
||||
<tr>
|
||||
<td><?= e(date('d.m.Y H:i', strtotime((string) $mailing['created_at']))) ?></td>
|
||||
<td><?= e((string) $mailing['subject']) ?></td>
|
||||
<td><?= $total ?></td>
|
||||
<td>
|
||||
<?= $sent ?> versendet<?= $failed > 0 ? ', ' . $failed . ' fehlgeschlagen' : '' ?>
|
||||
<?= $pending > 0 ? ' · ' . $pending . ' offen' : ' · fertig' ?>
|
||||
</td>
|
||||
<td>
|
||||
<?php if ($pending > 0): ?>
|
||||
<form method="post" action="<?= e(url('/admin/mailings')) ?>">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="send">
|
||||
<input type="hidden" name="mailing_id" value="<?= (int) $mailing['id'] ?>">
|
||||
<input type="hidden" name="batch" value="<?= (int) $batchSize ?>">
|
||||
<button type="submit" class="btn small primary"<?= $mailEnabled ? '' : ' disabled' ?>>
|
||||
<?= $pending > (int) $batchSize
|
||||
? 'Nächste ' . (int) $batchSize . ' senden'
|
||||
: 'Rest (' . $pending . ') senden' ?>
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<span class="muted small">abgeschlossen</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
56
views/mailing_abmelden.php
Normal file
56
views/mailing_abmelden.php
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
/**
|
||||
* Abmeldeseite für die Kundenrundmail (/abmelden?e=…&t=…).
|
||||
* Bewusst ohne App-Navigation: Empfänger sind Kunden, keine Mitarbeiter.
|
||||
* Der Link führt erst auf eine Bestätigung, damit Vorschau- und
|
||||
* Sicherheitsscanner in Mailprogrammen niemanden versehentlich abmelden.
|
||||
*
|
||||
* @var string $email
|
||||
* @var string $token
|
||||
* @var bool $valid
|
||||
* @var bool $done
|
||||
* @var bool $already
|
||||
* @var string $error
|
||||
*/
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow, noarchive">
|
||||
<title>Rundmail abbestellen · Drink it cold</title>
|
||||
<link rel="stylesheet" href="<?= e(asset('app.css')) ?>">
|
||||
</head>
|
||||
<body class="legal-page">
|
||||
<main class="legal">
|
||||
<h1>Rundmail abbestellen</h1>
|
||||
|
||||
<?php if ($done): ?>
|
||||
<p><strong>Erledigt.</strong> Die Adresse <em><?= e($email) ?></em> ist aus der Empfängerliste
|
||||
für Rundmails entfernt. Um Buchungen, Rechnungen und Terminbestätigungen kümmern wir uns
|
||||
unverändert.</p>
|
||||
<?php elseif ($error !== ''): ?>
|
||||
<p><strong><?= e($error) ?></strong> Bitte den Link aus der E-Mail erneut öffnen.</p>
|
||||
<?php elseif (!$valid): ?>
|
||||
<p>Dieser Abmeldelink ist ungültig oder unvollständig. Bitte den Link aus der E-Mail
|
||||
vollständig kopieren.</p>
|
||||
<?php elseif ($already): ?>
|
||||
<p>Die Adresse <em><?= e($email) ?></em> erhält bereits keine Rundmails mehr.</p>
|
||||
<?php else: ?>
|
||||
<p>Soll die Adresse <em><?= e($email) ?></em> künftig keine Rundmails (zum Beispiel das
|
||||
Dankeschön zum Jahresende) mehr erhalten?</p>
|
||||
<form method="post" action="<?= e(url('/abmelden')) ?>" class="btn-row">
|
||||
<input type="hidden" name="e" value="<?= e($email) ?>">
|
||||
<input type="hidden" name="t" value="<?= e($token) ?>">
|
||||
<button type="submit" class="btn">Ja, Rundmails abbestellen</button>
|
||||
</form>
|
||||
<p class="muted small">Bestätigungen und Erinnerungen zu gebuchten Terminen sind davon nicht
|
||||
betroffen.</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<p class="muted small"><a href="<?= e($base . '/') ?>">Zurück zur Startseite</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Add table
Add a link
Reference in a new issue