- Neue Seite /admin/mailings/<id> mit Status je Empfänger (views/admin_mailing_detail.php, mailing_recipient_log()). - Das Formular schickt Häppchen per fetch, bis alle Empfänger durch sind – eine Antwort pro Häppchen, damit kein Request in die Zeitgrenze des Hosters läuft; ohne JavaScript bleibt es beim klassischen POST.
720 lines
31 KiB
PHP
720 lines
31 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/** Verwaltung: Benutzer, Mitarbeiter, Anhänger, Erinnerungsversand. */
|
||
|
||
function admin_handle(string $path, array $user): void
|
||
{
|
||
auth_require_admin();
|
||
|
||
if ($path === '/admin' || $path === '/admin/') {
|
||
redirect('/admin/users');
|
||
}
|
||
if ($path === '/admin/users') {
|
||
admin_users_list();
|
||
return;
|
||
}
|
||
if ($path === '/admin/users/new') {
|
||
admin_user_form(null);
|
||
return;
|
||
}
|
||
if (preg_match('#^/admin/users/(\d+)$#', $path, $m) === 1) {
|
||
admin_user_form((int) $m[1]);
|
||
return;
|
||
}
|
||
if (preg_match('#^/admin/users/(\d+)/invite$#', $path, $m) === 1) {
|
||
admin_user_invite((int) $m[1], $user);
|
||
return;
|
||
}
|
||
if (preg_match('#^/admin/users/(\d+)/delete$#', $path, $m) === 1) {
|
||
admin_user_delete((int) $m[1], $user);
|
||
return;
|
||
}
|
||
if ($path === '/admin/employees') {
|
||
admin_employees();
|
||
return;
|
||
}
|
||
if ($path === '/admin/trailers') {
|
||
admin_trailers();
|
||
return;
|
||
}
|
||
if ($path === '/admin/reminders/send') {
|
||
admin_reminders_send();
|
||
return;
|
||
}
|
||
if ($path === '/admin/mailings') {
|
||
admin_mailings($user);
|
||
return;
|
||
}
|
||
if (preg_match('#^/admin/mailings/(\d+)$#', $path, $m) === 1) {
|
||
admin_mailing_detail((int) $m[1]);
|
||
return;
|
||
}
|
||
|
||
abort_page(404, 'Diese Verwaltungsseite gibt es nicht.');
|
||
}
|
||
|
||
function admin_users_list(): void
|
||
{
|
||
$sql = 'SELECT u.*, e.name AS employee_name
|
||
FROM users u LEFT JOIN employees e ON e.id = u.employee_id
|
||
ORDER BY u.last_name, u.first_name';
|
||
$users = db()->query($sql)->fetchAll();
|
||
|
||
// Offene Einladungen, damit der Admin sieht, wer noch keinen Zugang hat.
|
||
$stmt = db()->prepare('SELECT user_id, expires_at FROM user_invites WHERE used_at IS NULL AND expires_at >= ?');
|
||
$stmt->execute([utc_now()]);
|
||
$openInvites = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$openInvites[(int) $row['user_id']] = (string) $row['expires_at'];
|
||
}
|
||
|
||
render_page('admin_users', [
|
||
'users' => $users,
|
||
'pushCounts' => push_counts_by_user(),
|
||
'pushLastUpdate' => push_last_update_by_user(),
|
||
'pushConfigured' => push_is_configured(),
|
||
'openInvites' => $openInvites,
|
||
], 'Benutzer');
|
||
}
|
||
|
||
function admin_user_form(?int $id): void
|
||
{
|
||
$editing = $id !== null ? auth_user_by_id($id) : null;
|
||
if ($id !== null && !$editing) {
|
||
abort_page(404, 'Benutzer nicht gefunden.');
|
||
}
|
||
|
||
$employees = employees_all();
|
||
$errors = [];
|
||
$values = $editing ? [
|
||
'first_name' => (string) $editing['first_name'],
|
||
'last_name' => (string) $editing['last_name'],
|
||
'email' => (string) ($editing['email'] ?? ''),
|
||
'role' => (string) $editing['role'],
|
||
'status' => (string) $editing['status'],
|
||
'employee_id' => (int) ($editing['employee_id'] ?? 0),
|
||
'must_change_password' => (int) $editing['must_change_password'],
|
||
] : [
|
||
'first_name' => '',
|
||
'last_name' => '',
|
||
'email' => '',
|
||
'role' => 'user',
|
||
'status' => 'active',
|
||
'employee_id' => 0,
|
||
'must_change_password' => 1,
|
||
];
|
||
|
||
if (is_post()) {
|
||
require_post();
|
||
$values = [
|
||
'first_name' => post_string('first_name'),
|
||
'last_name' => post_string('last_name'),
|
||
'email' => post_string('email'),
|
||
'role' => post_string('role') === 'admin' ? 'admin' : 'user',
|
||
'status' => post_string('status') === 'disabled' ? 'disabled' : 'active',
|
||
'employee_id' => (int) post_string('employee_id'),
|
||
'must_change_password' => post_string('must_change_password') === '1' ? 1 : 0,
|
||
];
|
||
$password = (string) ($_POST['password'] ?? '');
|
||
// Einladung: Passwort setzt der Benutzer selbst über einen Link.
|
||
$sendInvite = $id === null && post_string('send_invite') === '1';
|
||
|
||
if ($values['first_name'] === '' || mb_strlen($values['first_name']) > 80) {
|
||
$errors['first_name'] = 'Bitte einen Vornamen angeben (max. 80 Zeichen).';
|
||
}
|
||
if ($values['last_name'] === '' || mb_strlen($values['last_name']) > 80) {
|
||
$errors['last_name'] = 'Bitte einen Nachnamen angeben (max. 80 Zeichen).';
|
||
}
|
||
if ($values['email'] !== '' && (!filter_var($values['email'], FILTER_VALIDATE_EMAIL) || mb_strlen($values['email']) > 190)) {
|
||
$errors['email'] = 'Bitte eine gültige E-Mail-Adresse angeben.';
|
||
} elseif ($values['email'] !== '') {
|
||
$stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
|
||
$stmt->execute([$values['email'], $id ?? 0]);
|
||
if ($stmt->fetchColumn()) {
|
||
$errors['email'] = 'Diese E-Mail-Adresse ist bereits einem anderen Benutzer zugeordnet.';
|
||
}
|
||
}
|
||
|
||
$stmt = db()->prepare('SELECT id FROM users WHERE first_name = ? AND last_name = ? AND id <> ? LIMIT 1');
|
||
$stmt->execute([$values['first_name'], $values['last_name'], $id ?? 0]);
|
||
if ($stmt->fetchColumn()) {
|
||
$errors['name'] = 'Ein Benutzer mit diesem Vor- und Nachnamen existiert bereits.';
|
||
}
|
||
|
||
if ($values['employee_id'] > 0) {
|
||
$stmt = db()->prepare('SELECT id, first_name, last_name FROM users WHERE employee_id = ? AND id <> ? LIMIT 1');
|
||
$stmt->execute([$values['employee_id'], $id ?? 0]);
|
||
if ($other = $stmt->fetch()) {
|
||
$errors['employee_id'] = 'Dieser Mitarbeiter ist bereits mit ' . $other['first_name'] . ' ' . $other['last_name'] . ' verknüpft.';
|
||
}
|
||
if (!employee_find($values['employee_id'])) {
|
||
$errors['employee_id'] = 'Mitarbeiter nicht gefunden.';
|
||
}
|
||
}
|
||
|
||
if ($sendInvite && $values['email'] === '') {
|
||
$errors['email'] = 'Für die Einladung wird eine E-Mail-Adresse benötigt – oder das Startpasswort selbst vergeben.';
|
||
}
|
||
if ($sendInvite && $values['status'] !== 'active') {
|
||
$errors['status'] = 'Einladungen sind nur für aktive Konten möglich.';
|
||
}
|
||
|
||
if ($id === null && !$sendInvite && mb_strlen($password) < 8) {
|
||
$errors['password'] = 'Das Startpasswort muss mindestens 8 Zeichen haben.';
|
||
}
|
||
if ($id !== null && $password !== '' && mb_strlen($password) < 8) {
|
||
$errors['password'] = 'Das neue Passwort muss mindestens 8 Zeichen haben.';
|
||
}
|
||
|
||
// Der letzte aktive Admin darf nicht degradiert oder deaktiviert werden.
|
||
if ($editing && ($editing['role'] === 'admin' && $editing['status'] === 'active')
|
||
&& ($values['role'] !== 'admin' || $values['status'] !== 'active')
|
||
) {
|
||
$stmt = db()->query("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id <> " . (int) $editing['id']);
|
||
if ((int) $stmt->fetchColumn() === 0) {
|
||
$errors['role'] = 'Der letzte aktive Administrator kann nicht herabgestuft oder deaktiviert werden.';
|
||
}
|
||
}
|
||
if ($editing && (int) $editing['id'] === auth_user()['id']
|
||
&& ($values['role'] !== 'admin' || $values['status'] !== 'active')
|
||
) {
|
||
$errors['role'] = 'Das eigene Konto kann nicht deaktiviert oder zum normalen Benutzer gemacht werden.';
|
||
}
|
||
|
||
if (!$errors) {
|
||
$email = $values['email'] === '' ? null : $values['email'];
|
||
$pdo = db();
|
||
$pdo->beginTransaction();
|
||
try {
|
||
if ($id === null) {
|
||
$stmt = $pdo->prepare(
|
||
'INSERT INTO users (first_name, last_name, email, password_hash, role, status, employee_id,
|
||
must_change_password, auth_epoch, created_at, updated_at, password_changed_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)'
|
||
);
|
||
$stmt->execute([
|
||
$values['first_name'], $values['last_name'], $email,
|
||
hash_password($sendInvite ? bin2hex(random_bytes(24)) : $password),
|
||
$values['role'], $values['status'], $values['employee_id'] ?: null,
|
||
$values['must_change_password'], utc_now(), utc_now(), utc_now(),
|
||
]);
|
||
$newId = (int) $pdo->lastInsertId();
|
||
$pdo->commit();
|
||
|
||
$message = 'Benutzer ' . $values['first_name'] . ' ' . $values['last_name'] . ' wurde angelegt.';
|
||
if ($sendInvite) {
|
||
// Link erzeugen (und mailen, wenn der Versand aktiv ist).
|
||
$inviteResult = invite_provision($newId, (int) auth_user()['id']);
|
||
invite_notice_set($newId, $inviteResult);
|
||
$message .= $inviteResult['sent']
|
||
? ' Die Einladung ist an ' . $email . ' unterwegs.'
|
||
: ' Die Einladung ist erzeugt – der Link steht im Formular.';
|
||
}
|
||
flash('success', $message);
|
||
redirect('/admin/users/' . $newId);
|
||
}
|
||
|
||
$newId = (int) $editing['id'];
|
||
$securityChange = $password !== '' || ($editing['status'] === 'active' && $values['status'] === 'disabled');
|
||
$stmt = $pdo->prepare(
|
||
'UPDATE users SET first_name = ?, last_name = ?, email = ?, role = ?, status = ?,
|
||
employee_id = ?, must_change_password = ?, updated_at = ? WHERE id = ?'
|
||
);
|
||
$stmt->execute([
|
||
$values['first_name'], $values['last_name'], $email, $values['role'], $values['status'],
|
||
$values['employee_id'] ?: null, $values['must_change_password'], utc_now(), $newId,
|
||
]);
|
||
if ($password !== '') {
|
||
$pdo->prepare(
|
||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = ?,
|
||
auth_epoch = auth_epoch + 1 WHERE id = ?'
|
||
)->execute([hash_password($password), utc_now(), $values['must_change_password'], $newId]);
|
||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$newId]);
|
||
} elseif ($securityChange) {
|
||
$pdo->prepare('UPDATE users SET auth_epoch = auth_epoch + 1 WHERE id = ?')->execute([$newId]);
|
||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$newId]);
|
||
}
|
||
$pdo->commit();
|
||
} catch (Throwable $error) {
|
||
$pdo->rollBack();
|
||
throw $error;
|
||
}
|
||
|
||
flash('success', 'Benutzer wurde gespeichert.');
|
||
if ($password !== '' && $newId === (int) auth_user()['id']) {
|
||
auth_logout();
|
||
redirect('/login');
|
||
}
|
||
redirect('/admin/users');
|
||
}
|
||
http_response_code(422);
|
||
}
|
||
|
||
render_page('admin_user_form', [
|
||
'editing' => $editing,
|
||
'values' => $values,
|
||
'errors' => $errors,
|
||
'employees' => $employees,
|
||
'pushCount' => $editing ? push_subscription_count((int) $editing['id']) : 0,
|
||
'pushAvailable' => push_is_configured(),
|
||
'mailEnabled' => mail_is_enabled(),
|
||
'sendInvite' => $id === null && (!is_post() || post_string('send_invite') === '1'),
|
||
'inviteNotice' => invite_notice_take($id),
|
||
'openInvite' => $editing ? invite_active_for_user((int) $editing['id']) : null,
|
||
], $editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen');
|
||
}
|
||
|
||
/**
|
||
* Erzeugt einen neuen Einladungslink und mailt ihn. Ein bisheriges Passwort
|
||
* wird dabei ungültig, angemeldete Geräte werden abgemeldet.
|
||
*/
|
||
function admin_user_invite(int $id, array $actor): void
|
||
{
|
||
require_post();
|
||
$target = auth_user_by_id($id);
|
||
if (!$target) {
|
||
abort_page(404, 'Benutzer nicht gefunden.');
|
||
}
|
||
if ($id === (int) $actor['id']) {
|
||
abort_page(422, 'Für das eigene Konto lässt sich keine Einladung versenden. Bitte das Passwort unter „Mein Konto" ändern.');
|
||
}
|
||
if ($target['status'] !== 'active') {
|
||
flash('error', 'Für ein deaktiviertes Konto kann keine Einladung versendet werden. Bitte das Konto zuerst aktivieren.');
|
||
redirect('/admin/users/' . $id);
|
||
}
|
||
|
||
$result = invite_provision($id, (int) $actor['id']);
|
||
invite_notice_set($id, $result);
|
||
$email = trim((string) ($target['email'] ?? ''));
|
||
flash('success', $result['sent']
|
||
? 'Einladung an ' . $email . ' gesendet. Das bisherige Passwort ist jetzt ungültig.'
|
||
: 'Einladung erzeugt. Das bisherige Passwort ist jetzt ungültig.');
|
||
redirect('/admin/users/' . $id);
|
||
}
|
||
|
||
function admin_user_delete(int $id, array $actor): void
|
||
{
|
||
require_post();
|
||
$target = auth_user_by_id($id);
|
||
if (!$target) {
|
||
abort_page(404, 'Benutzer nicht gefunden.');
|
||
}
|
||
if ($id === (int) $actor['id']) {
|
||
abort_page(422, 'Das eigene Konto kann nicht gelöscht werden.');
|
||
}
|
||
if ($target['role'] === 'admin' && $target['status'] === 'active') {
|
||
$count = (int) db()->query("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id <> $id")->fetchColumn();
|
||
if ($count === 0) {
|
||
abort_page(422, 'Der letzte aktive Administrator kann nicht gelöscht werden.');
|
||
}
|
||
}
|
||
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$id]);
|
||
flash('success', 'Benutzer ' . $target['first_name'] . ' ' . $target['last_name'] . ' wurde gelöscht.');
|
||
redirect('/admin/users');
|
||
}
|
||
|
||
function admin_employees(): void
|
||
{
|
||
$errors = [];
|
||
$editId = query_int('edit');
|
||
$editing = $editId > 0 ? employee_find($editId) : null;
|
||
$values = ['name' => '', 'sort_order' => 0, 'active' => 1];
|
||
|
||
if (is_post()) {
|
||
require_post();
|
||
$action = post_string('action');
|
||
$id = (int) post_string('id');
|
||
|
||
if ($action === 'delete') {
|
||
$employee = employee_find($id);
|
||
if (!$employee) {
|
||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||
}
|
||
$stmt = db()->prepare('SELECT COUNT(*) FROM bookings WHERE employee_id = ?');
|
||
$stmt->execute([$id]);
|
||
if ((int) $stmt->fetchColumn() > 0) {
|
||
flash('error', 'Mitarbeiter ' . $employee['name'] . ' kann nicht gelöscht werden, weil Buchungen darauf verweisen. Der Mitarbeiter kann stattdessen deaktiviert werden.');
|
||
redirect('/admin/employees');
|
||
}
|
||
if ((int) $employee['active'] === 1
|
||
&& (int) db()->query('SELECT COUNT(*) FROM employees WHERE active = 1')->fetchColumn() <= 1
|
||
) {
|
||
flash('error', 'Mindestens ein aktiver Mitarbeiter muss bleiben, damit Buchungen zugeordnet werden können.');
|
||
redirect('/admin/employees');
|
||
}
|
||
db()->prepare('DELETE FROM employees WHERE id = ?')->execute([$id]);
|
||
flash('success', 'Mitarbeiter ' . $employee['name'] . ' wurde gelöscht.');
|
||
redirect('/admin/employees');
|
||
}
|
||
|
||
$values = [
|
||
'name' => post_string('name'),
|
||
'sort_order' => (int) post_string('sort_order'),
|
||
'active' => post_string('active') === '1' ? 1 : 0,
|
||
];
|
||
if ($values['name'] === '' || mb_strlen($values['name']) > 100) {
|
||
$errors['name'] = 'Bitte einen Namen angeben (max. 100 Zeichen).';
|
||
}
|
||
$stmt = db()->prepare('SELECT id FROM employees WHERE name = ? AND id <> ? LIMIT 1');
|
||
$stmt->execute([$values['name'], $id]);
|
||
if ($stmt->fetchColumn()) {
|
||
$errors['name'] = 'Dieser Mitarbeiter existiert bereits.';
|
||
}
|
||
|
||
if (!$errors) {
|
||
if ($action === 'create') {
|
||
db()->prepare('INSERT INTO employees (name, active, sort_order, created_at) VALUES (?, ?, ?, ?)')
|
||
->execute([$values['name'], $values['active'], $values['sort_order'], utc_now()]);
|
||
flash('success', 'Mitarbeiter ' . $values['name'] . ' wurde angelegt.');
|
||
} elseif ($action === 'update' && $id > 0) {
|
||
$existing = employee_find($id);
|
||
if (!$existing) {
|
||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||
}
|
||
if ((int) $existing['active'] === 1 && $values['active'] === 0) {
|
||
$stmt = db()->prepare("SELECT COUNT(*) FROM bookings WHERE employee_id = ? AND status = 'active' AND end_date >= ?");
|
||
$stmt->execute([$id, today_iso()]);
|
||
if ((int) $stmt->fetchColumn() > 0) {
|
||
$errors['active'] = 'Der Mitarbeiter hat noch aktive Buchungen und kann nicht deaktiviert werden. Bitte zuerst umbuchen.';
|
||
} elseif ((int) db()->query('SELECT COUNT(*) FROM employees WHERE active = 1')->fetchColumn() <= 1) {
|
||
$errors['active'] = 'Mindestens ein aktiver Mitarbeiter muss bleiben, damit Buchungen zugeordnet werden können.';
|
||
}
|
||
}
|
||
if (!$errors) {
|
||
db()->prepare('UPDATE employees SET name = ?, active = ?, sort_order = ? WHERE id = ?')
|
||
->execute([$values['name'], $values['active'], $values['sort_order'], $id]);
|
||
flash('success', 'Mitarbeiter wurde gespeichert.');
|
||
}
|
||
}
|
||
if (!$errors) {
|
||
redirect('/admin/employees');
|
||
}
|
||
}
|
||
http_response_code(422);
|
||
$editId = $action === 'update' ? $id : 0;
|
||
if ($editId > 0) {
|
||
$editing = employee_find($editId);
|
||
if (!$editing) {
|
||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($editId > 0 && !$editing) {
|
||
abort_page(404, 'Mitarbeiter nicht gefunden.');
|
||
}
|
||
if ($editing && !is_post()) {
|
||
$values = [
|
||
'name' => (string) $editing['name'],
|
||
'sort_order' => (int) $editing['sort_order'],
|
||
'active' => (int) $editing['active'],
|
||
];
|
||
}
|
||
|
||
$rows = db()->query(
|
||
'SELECT e.*, u.first_name, u.last_name,
|
||
(SELECT COUNT(*) FROM bookings b WHERE b.employee_id = e.id AND b.status = "active" AND b.end_date >= CURDATE()) AS future_bookings,
|
||
(SELECT COUNT(*) FROM bookings b WHERE b.employee_id = e.id) AS booking_count
|
||
FROM employees e LEFT JOIN users u ON u.employee_id = e.id
|
||
ORDER BY e.sort_order, e.name'
|
||
)->fetchAll();
|
||
|
||
render_page('admin_employees', [
|
||
'rows' => $rows,
|
||
'editing' => $editing,
|
||
'editId' => $editId,
|
||
'values' => $values,
|
||
'errors' => $errors,
|
||
], 'Mitarbeiter');
|
||
}
|
||
|
||
function admin_trailers(): void
|
||
{
|
||
$errors = [];
|
||
$createErrors = [];
|
||
$nextSort = (int) db()->query('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM trailers')->fetchColumn();
|
||
$createValues = [
|
||
'label' => '',
|
||
'color_name' => '',
|
||
'color_hex' => '#196abc',
|
||
'sort_order' => $nextSort,
|
||
'active' => 1,
|
||
];
|
||
|
||
if (is_post()) {
|
||
require_post();
|
||
$action = post_string('action', 'update');
|
||
|
||
if ($action === 'create') {
|
||
$createValues = [
|
||
'label' => post_string('label'),
|
||
'color_name' => post_string('color_name'),
|
||
'color_hex' => strtolower(post_string('color_hex')),
|
||
'sort_order' => (int) post_string('sort_order'),
|
||
'active' => post_string('active') === '1' ? 1 : 0,
|
||
];
|
||
if ($createValues['label'] === '' || mb_strlen($createValues['label']) > 40) {
|
||
$createErrors['label'] = 'Bitte eine Bezeichnung angeben (max. 40 Zeichen).';
|
||
}
|
||
if ($createValues['color_name'] === '' || mb_strlen($createValues['color_name']) > 40) {
|
||
$createErrors['color_name'] = 'Bitte einen Farbnamen angeben.';
|
||
}
|
||
if (!preg_match('/^#[0-9a-f]{6}$/', $createValues['color_hex'])) {
|
||
$createErrors['color_hex'] = 'Bitte eine gültige Farbe (#rrggbb) wählen.';
|
||
}
|
||
if ($createValues['label'] !== '') {
|
||
$stmt = db()->prepare('SELECT id FROM trailers WHERE label = ? LIMIT 1');
|
||
$stmt->execute([$createValues['label']]);
|
||
if ($stmt->fetchColumn()) {
|
||
$createErrors['label'] = 'Diese Bezeichnung ist bereits vergeben.';
|
||
}
|
||
}
|
||
if (!$createErrors) {
|
||
db()->prepare('INSERT INTO trailers (label, color_name, color_hex, sort_order, active) VALUES (?, ?, ?, ?, ?)')
|
||
->execute([
|
||
$createValues['label'], $createValues['color_name'], $createValues['color_hex'],
|
||
$createValues['sort_order'], $createValues['active'],
|
||
]);
|
||
flash('success', 'Anhänger ' . $createValues['label'] . ' wurde angelegt.');
|
||
redirect('/admin/trailers');
|
||
}
|
||
http_response_code(422);
|
||
} elseif ($action === 'delete') {
|
||
$id = (int) post_string('id');
|
||
$trailer = trailer_find($id);
|
||
if (!$trailer) {
|
||
abort_page(404, 'Anhänger nicht gefunden.');
|
||
}
|
||
$stmt = db()->prepare('SELECT COUNT(*) FROM bookings WHERE trailer_id = ?');
|
||
$stmt->execute([$id]);
|
||
if ((int) $stmt->fetchColumn() > 0) {
|
||
flash('error', 'Anhänger ' . $trailer['label'] . ' kann nicht gelöscht werden, weil Buchungen darauf verweisen. Der Anhänger kann stattdessen deaktiviert werden.');
|
||
redirect('/admin/trailers');
|
||
}
|
||
if ((int) $trailer['active'] === 1
|
||
&& (int) db()->query('SELECT COUNT(*) FROM trailers WHERE active = 1')->fetchColumn() <= 1
|
||
) {
|
||
flash('error', 'Mindestens ein Anhänger muss aktiv bleiben, damit neue Buchungen möglich sind.');
|
||
redirect('/admin/trailers');
|
||
}
|
||
db()->prepare('DELETE FROM trailers WHERE id = ?')->execute([$id]);
|
||
flash('success', 'Anhänger ' . $trailer['label'] . ' wurde gelöscht.');
|
||
redirect('/admin/trailers');
|
||
} else {
|
||
$labels = post_array('label');
|
||
$colorNames = post_array('color_name');
|
||
$colors = post_array('color_hex');
|
||
$sorts = post_array('sort_order');
|
||
$actives = post_array('active');
|
||
|
||
$existing = trailers_all(false);
|
||
$seen = [];
|
||
$updates = [];
|
||
foreach ($existing as $trailer) {
|
||
$id = (int) $trailer['id'];
|
||
$label = trim((string) ($labels[$id] ?? $trailer['label']));
|
||
$colorName = trim((string) ($colorNames[$id] ?? $trailer['color_name']));
|
||
$color = strtolower(trim((string) ($colors[$id] ?? $trailer['color_hex'])));
|
||
$sort = (int) ($sorts[$id] ?? $trailer['sort_order']);
|
||
$active = ((string) ($actives[$id] ?? '0')) === '1' ? 1 : 0;
|
||
|
||
if ($label === '' || mb_strlen($label) > 40) {
|
||
$errors['trailer_' . $id] = 'Bitte eine Bezeichnung angeben (max. 40 Zeichen).';
|
||
} elseif (isset($seen[mb_strtolower($label)])) {
|
||
$errors['trailer_' . $id] = 'Die Bezeichnung muss eindeutig sein.';
|
||
}
|
||
$seen[mb_strtolower($label)] = true;
|
||
if ($colorName === '' || mb_strlen($colorName) > 40) {
|
||
$errors['trailer_' . $id] = $errors['trailer_' . $id] ?? 'Bitte einen Farbnamen angeben.';
|
||
}
|
||
if (!preg_match('/^#[0-9a-f]{6}$/', $color)) {
|
||
$errors['trailer_' . $id] = $errors['trailer_' . $id] ?? 'Bitte eine gültige Farbe (#rrggbb) wählen.';
|
||
}
|
||
if ((int) $trailer['active'] === 1 && $active === 0) {
|
||
$stmt = db()->prepare("SELECT COUNT(*) FROM bookings WHERE trailer_id = ? AND status = 'active' AND end_date >= ?");
|
||
$stmt->execute([$id, today_iso()]);
|
||
if ((int) $stmt->fetchColumn() > 0) {
|
||
$errors['trailer_' . $id] = 'Der Anhänger hat noch aktuelle oder zukünftige Buchungen und kann nicht deaktiviert werden.';
|
||
}
|
||
}
|
||
$updates[$id] = [$label, $colorName, $color, $sort, $active];
|
||
}
|
||
if (!array_filter($updates, static fn (array $row): bool => (int) $row[4] === 1)) {
|
||
$errors['general'] = 'Mindestens ein Anhänger muss aktiv bleiben, damit neue Buchungen möglich sind.';
|
||
}
|
||
|
||
if (!$errors) {
|
||
foreach ($updates as $id => [$label, $colorName, $color, $sort, $active]) {
|
||
db()->prepare('UPDATE trailers SET label = ?, color_name = ?, color_hex = ?, sort_order = ?, active = ? WHERE id = ?')
|
||
->execute([$label, $colorName, $color, $sort, $active, $id]);
|
||
}
|
||
flash('success', 'Anhänger wurden gespeichert.');
|
||
redirect('/admin/trailers');
|
||
}
|
||
http_response_code(422);
|
||
}
|
||
}
|
||
|
||
// Zeilen mit Anzahl Buchungen für die Lösch-/Deaktivierungsprüfung.
|
||
$rows = db()->query(
|
||
'SELECT t.*, (SELECT COUNT(*) FROM bookings b WHERE b.trailer_id = t.id) AS booking_count
|
||
FROM trailers t ORDER BY t.sort_order, t.id'
|
||
)->fetchAll();
|
||
|
||
render_page('admin_trailers', [
|
||
'rows' => $rows,
|
||
'errors' => $errors,
|
||
'createErrors' => $createErrors,
|
||
'createValues' => $createValues,
|
||
'nextSort' => $nextSort,
|
||
], 'Anhänger');
|
||
}
|
||
function admin_reminders_send(): void
|
||
{
|
||
require_post();
|
||
$push = push_dispatch_due();
|
||
$mail = reminder_send_due();
|
||
$parts = [];
|
||
if (push_is_configured()) {
|
||
$parts[] = sprintf(
|
||
'Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt.',
|
||
$push['sent'], $push['failed'], $push['removed']
|
||
);
|
||
} else {
|
||
$parts[] = 'Push ist nicht konfiguriert.';
|
||
}
|
||
if (!$mail['enabled']) {
|
||
$parts[] = 'E-Mail-Versand ist deaktiviert.';
|
||
} elseif ($mail['errors']) {
|
||
$parts[] = 'E-Mail-Fehler: ' . implode(' ', $mail['errors']);
|
||
} else {
|
||
$parts[] = sprintf('E-Mail: %d versendet, %d übersprungen.', $mail['sent'], $mail['skipped']);
|
||
}
|
||
flash($mail['errors'] ? 'error' : 'success', implode(' ', $parts));
|
||
redirect('/reminders');
|
||
}
|
||
|
||
/**
|
||
* Protokoll einer einzelnen Rundmail: Status je Empfänger.
|
||
*/
|
||
function admin_mailing_detail(int $id): void
|
||
{
|
||
$mailing = mailing_find($id);
|
||
if (!$mailing) {
|
||
abort_page(404, 'Diese Rundmail gibt es nicht.');
|
||
}
|
||
|
||
$log = mailing_recipient_log($id);
|
||
$counts = ['sent' => 0, 'pending' => 0, 'failed' => 0];
|
||
foreach ($log as $row) {
|
||
$status = (string) $row['status'];
|
||
if (isset($counts[$status])) {
|
||
$counts[$status]++;
|
||
}
|
||
}
|
||
|
||
render_page('admin_mailing_detail', [
|
||
'mailing' => $mailing,
|
||
'log' => $log,
|
||
'counts' => $counts,
|
||
], 'Rundmail-Protokoll');
|
||
}
|
||
|
||
/**
|
||
* 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
|
||
{
|
||
$template = mailing_template();
|
||
$values = ['subject' => $template['subject'], 'body' => $template['body'], 'from_template' => true];
|
||
$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'));
|
||
$values['from_template'] = false;
|
||
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()) {
|
||
if (wants_json()) {
|
||
json_response(['error' => ['code' => 'mail_disabled',
|
||
'message' => 'Der Mailversand ist in der Konfiguration ausgeschaltet.']], 409);
|
||
}
|
||
flash('error', 'Der Mailversand ist in der Konfiguration ausgeschaltet (app.mail_enabled).');
|
||
redirect('/admin/mailings');
|
||
}
|
||
// Im Browser (fetch) schickt das Skript so viele Häppchen, bis alle
|
||
// durch sind: eine Antwort pro Häppchen, damit kein Request in die
|
||
// Zeitgrenze des Hosters läuft. Ohne JavaScript bleibt es beim
|
||
// klassischen POST mit Weiterleitung.
|
||
$result = mailing_send_batch($id, (int) post_string('batch', (string) MAILING_BATCH_DEFAULT));
|
||
if (wants_json()) {
|
||
json_response([
|
||
'sent' => $result['sent'],
|
||
'failed' => $result['failed'],
|
||
'remaining' => $result['remaining'],
|
||
]);
|
||
}
|
||
$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');
|
||
}
|