feat: add Backend mit allen aktuellen features + Demo Daten
This commit is contained in:
1 parent
a78e84515a
commit
e122aa8650
17 files changed
+704
-238
No files matched your search
@@ -80,12 +80,13 @@ sowie klar erkennbare Demo-Termine. Die API prüft Kapazitäten innerhalb einer
|
|||||||
Transaktion und sperrt den Termin dabei mit `SELECT … FOR UPDATE`; parallele
|
Transaktion und sperrt den Termin dabei mit `SELECT … FOR UPDATE`; parallele
|
||||||
Anmeldungen können dadurch die Kapazität nicht überschreiten.
|
Anmeldungen können dadurch die Kapazität nicht überschreiten.
|
||||||
|
|
||||||
Die Demo speichert eine gültige Anmeldung direkt als `confirmed`. Sie hat
|
Die Demo speichert eine Anfrage zunächst als `pending_confirmation`. Sie
|
||||||
bewusst noch **keinen** Mailversand, kein Double-Opt-in, keine Erinnerungen,
|
erstellt einen zeitlich begrenzten Bestätigungslink, bestätigt danach atomar
|
||||||
keinen ICS-Feed und keine Verwaltungsoberfläche. Die Anzeige benennt diesen
|
gegen die verfügbare Kapazität und erzeugt eine zweite Bestätigungsnachricht.
|
||||||
Umstand ausdrücklich. Ein Produktiveinsatz erfordert außerdem die in den
|
Bestätigungs- und Erinnerungsnachrichten liegen standardmäßig im lokalen
|
||||||
SOLL-Dokumenten genannten Entscheidungen zu Art. 13 DSGVO, Löschfristen,
|
Mailausgang der Testverwaltung. Mit `BOOKING_MAIL_TRANSPORT=mail` versucht der
|
||||||
Mailbetrieb, Rollen/Berechtigungen und Missbrauchsschutz.
|
Job den Versand über die PHP-Funktion `mail()`; SMTP-Konfiguration und echter
|
||||||
|
Mailbetrieb gehören erst in die Produktiventscheidung.
|
||||||
|
|
||||||
Der Browser erhält ein CSRF-Token per gleicher Sitzung; die API validiert alle
|
Der Browser erhält ein CSRF-Token per gleicher Sitzung; die API validiert alle
|
||||||
Pflichtdaten serverseitig und begrenzt Anmeldungen pro Sitzung. Dies ist eine
|
Pflichtdaten serverseitig und begrenzt Anmeldungen pro Sitzung. Dies ist eine
|
||||||
@@ -134,9 +135,39 @@ X-SUFW-Booking-CSRF: <csrfToken-aus-dem-GET>
|
|||||||
Für ein PS-`Probearbeiten` mit `introductionRequired: true` müssen
|
Für ein PS-`Probearbeiten` mit `introductionRequired: true` müssen
|
||||||
`introductionAttended` den Wert `true` und `introductionDate` ein gültiges
|
`introductionAttended` den Wert `true` und `introductionDate` ein gültiges
|
||||||
Datum im Format `YYYY-MM-DD` enthalten. Bei Erfolg antwortet die Demo mit
|
Datum im Format `YYYY-MM-DD` enthalten. Bei Erfolg antwortet die Demo mit
|
||||||
`201 Created`; bei einem inzwischen ausgebuchten oder doppelt gebuchten Termin
|
`202 Accepted`; bei einem inzwischen ausgebuchten oder doppelt gebuchten Termin
|
||||||
mit `409 Conflict`; fehlerhafte Pflichtangaben erhalten `422`.
|
mit `409 Conflict`; fehlerhafte Pflichtangaben erhalten `422`.
|
||||||
|
|
||||||
|
Der Link ruft `GET /booking/confirm.php?token=<Token>` auf. Erst dort wird die
|
||||||
|
Teilnahme in den Status `confirmed` überführt. Nicht bestätigte Anfragen laufen
|
||||||
|
nach 30 Minuten ab.
|
||||||
|
|
||||||
|
## Eigenständiges PHP-Backend
|
||||||
|
|
||||||
|
Die Testverwaltung läuft unabhängig von Contao unter
|
||||||
|
<http://localhost:8080/booking-admin/>. Sie bietet für PW und PS:
|
||||||
|
|
||||||
|
- Termin anlegen, bearbeiten sowie aktivieren/deaktivieren,
|
||||||
|
- Übersicht und Entfernen von Teilnahmen,
|
||||||
|
- lokaler Mailausgang mit kopierbarem Bestätigungslink,
|
||||||
|
- Anzeige bestätigter Teilnahmen nach frei wählbarem Zeitraum,
|
||||||
|
- abonnierbaren ICS-Feed je Projekt,
|
||||||
|
- manuellen Lauf der Ablauf- und Erinnerungsjobs.
|
||||||
|
|
||||||
|
Der Verwaltungsbereich hat absichtlich keine Benutzerverwaltung
|
||||||
|
und darf nicht unverändert außerhalb der Testumgebung bereitgestellt werden.
|
||||||
|
Er ist eine eigenständige PHP-Seite, keine Contao-Komponente.
|
||||||
|
|
||||||
|
Die zeitgesteuerten Aufgaben können zusätzlich ohne Browser ausgeführt werden:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose exec app php scripts/Run-BookingJobs.php
|
||||||
|
```
|
||||||
|
|
||||||
|
Für einen späteren Betrieb muss dieser Aufruf als geplanter Job erfolgen. Die
|
||||||
|
ICS-Adresse zeigt die Testverwaltung an; sie enthält nur Terminmetadaten und
|
||||||
|
keine Daten der Teilnehmenden.
|
||||||
|
|
||||||
## Zwei Einbindungswege
|
## Zwei Einbindungswege
|
||||||
|
|
||||||
Die Terminbuchungskomponente hat eine Vorschau auf einem Webseiten-Nachbau der Orginalseite:
|
Die Terminbuchungskomponente hat eine Vorschau auf einem Webseiten-Nachbau der Orginalseite:
|
||||||
|
|||||||
@@ -54,4 +54,12 @@ MariaDB-/MySQL-Client ausgeführt. Zugangsdaten gehören dabei in die
|
|||||||
Betriebskonfiguration und niemals in die SQL-Datei oder das Repository. Die
|
Betriebskonfiguration und niemals in die SQL-Datei oder das Repository. Die
|
||||||
erste Migration erstellt `sufw_booking_events` und
|
erste Migration erstellt `sufw_booking_events` und
|
||||||
`sufw_booking_registrations` sowie neun ungefährliche Demo-Termine für beide
|
`sufw_booking_registrations` sowie neun ungefährliche Demo-Termine für beide
|
||||||
Instanzen.
|
Instanzen. `002_booking_workflow.sql` ergänzt Bestätigungstoken, lokalen
|
||||||
|
Mailausgang und pro Projekt einen beim Import zufällig erzeugten,
|
||||||
|
widerrufbaren ICS-Feed-Token. `003_booking_demo_data.sql` legt zusätzlich
|
||||||
|
bestätigte Demo-Teilnahmen an und hält Beispieltermine jeweils einen Monat in
|
||||||
|
der Vergangenheit und Zukunft. Diese letzte Datei ist ausschließlich für die
|
||||||
|
lokale Entwicklungs- und Testdatenbank bestimmt und darf nicht auf dem
|
||||||
|
Produktivsystem ausgeführt werden. `004_booking_contact_phones.sql` ergänzt
|
||||||
|
die Telefonnummer der Ansprechperson und ersetzt die Kontakte der stabilen
|
||||||
|
Demo-Termine durch Carina Hollederer und Sarah van den Heuvel.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
-- SUFW Terminbuchung: Bestätigungsfluss, Test-Mailausgang und iCalendar-Feeds
|
||||||
|
-- Diese Migration ergänzt das Anfangsschema und kann gefahrlos erneut laufen.
|
||||||
|
|
||||||
|
ALTER TABLE `sufw_booking_registrations`
|
||||||
|
ADD COLUMN IF NOT EXISTS `confirmation_token_hash` char(64) DEFAULT NULL AFTER `privacy_accepted_at`,
|
||||||
|
ADD COLUMN IF NOT EXISTS `confirmation_expires_at` datetime DEFAULT NULL AFTER `confirmation_token_hash`,
|
||||||
|
ADD COLUMN IF NOT EXISTS `confirmed_at` datetime DEFAULT NULL AFTER `confirmation_expires_at`,
|
||||||
|
ADD COLUMN IF NOT EXISTS `removed_at` datetime DEFAULT NULL AFTER `confirmed_at`;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `sufw_booking_project_settings` (
|
||||||
|
`project` varchar(32) NOT NULL,
|
||||||
|
`feed_token` char(64) NOT NULL,
|
||||||
|
`updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
||||||
|
PRIMARY KEY (`project`),
|
||||||
|
UNIQUE KEY `sufw_booking_project_settings_feed_token` (`feed_token`),
|
||||||
|
CONSTRAINT `sufw_booking_project_settings_project_check` CHECK (`project` IN ('perspektivwerk', 'produktionsschule'))
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `sufw_booking_outbox` (
|
||||||
|
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||||
|
`registration_id` char(36) NOT NULL,
|
||||||
|
`kind` varchar(32) NOT NULL,
|
||||||
|
`recipient_email` varchar(254) NOT NULL,
|
||||||
|
`subject` varchar(255) NOT NULL,
|
||||||
|
`body` text NOT NULL,
|
||||||
|
`created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||||
|
`sent_at` datetime DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `sufw_booking_outbox_registration_kind` (`registration_id`, `kind`),
|
||||||
|
KEY `sufw_booking_outbox_pending` (`sent_at`, `created_at`),
|
||||||
|
CONSTRAINT `sufw_booking_outbox_kind_check` CHECK (`kind` IN ('confirmation_request', 'confirmation', 'reminder')),
|
||||||
|
CONSTRAINT `sufw_booking_outbox_registration_fk` FOREIGN KEY (`registration_id`) REFERENCES `sufw_booking_registrations` (`id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sufw_booking_project_settings` (`project`, `feed_token`)
|
||||||
|
VALUES
|
||||||
|
('perspektivwerk', SHA2(CONCAT(UUID(), RAND(), NOW(6)), 256)),
|
||||||
|
('produktionsschule', SHA2(CONCAT(UUID(), RAND(), NOW(6)), 256));
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sufw_booking_schema_migrations` (`version`) VALUES ('002_booking_workflow');
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
-- SUFW Terminbuchung: Lokale Demo-Termine und bestätigte Teilnahmen
|
||||||
|
--
|
||||||
|
-- Nur für lokale Entwicklungs- und Testdatenbanken. Diese Datei darf nicht
|
||||||
|
-- auf einem Produktivsystem ausgeführt werden: Sie legt bewusst Testpersonen
|
||||||
|
-- und Beispieltermine an. Die stabilen IDs verhindern Duplikate; beim erneuten
|
||||||
|
-- Ausführen werden die Termine relativ zum heutigen Datum aktualisiert.
|
||||||
|
|
||||||
|
INSERT INTO `sufw_booking_events`
|
||||||
|
(`id`, `project`, `title`, `starts_at`, `ends_at`, `capacity`, `format`, `introduction_required`, `contact_name`, `contact_email`, `is_active`)
|
||||||
|
VALUES
|
||||||
|
('d3c7f216-2704-4c81-b17a-000000000001', 'perspektivwerk', 'Erstgespräch PerspektivWerk', TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -1 MONTH), '09:00:00'), TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -1 MONTH), '10:00:00'), 3, 'vor_ort', 0, 'Anna Müller', 'anna.mueller@example.test', 1),
|
||||||
|
('d3c7f216-2704-4c81-b17a-000000000002', 'perspektivwerk', 'Psy Modul PerspektivWerk', TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '13:15:00'), TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '17:15:00'), 2, 'telefonisch', 0, 'Anna Müller', 'anna.mueller@example.test', 1),
|
||||||
|
('d3c7f216-2704-4c81-b17a-000000000003', 'produktionsschule', 'Voranmeldung Kennenlerntermin Produktionsschule', TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -1 MONTH), '10:30:00'), TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL -1 MONTH), '11:30:00'), 3, 'vor_ort', 0, 'Bernd Fischer', 'bernd.fischer@example.test', 1),
|
||||||
|
('d3c7f216-2704-4c81-b17a-000000000004', 'produktionsschule', 'Probearbeiten', TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '08:00:00'), TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '16:00:00'), 3, 'vor_ort', 1, 'Bernd Fischer', 'bernd.fischer@example.test', 1)
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
`title` = VALUES(`title`), `starts_at` = VALUES(`starts_at`), `ends_at` = VALUES(`ends_at`), `capacity` = VALUES(`capacity`), `format` = VALUES(`format`), `introduction_required` = VALUES(`introduction_required`), `contact_name` = VALUES(`contact_name`), `contact_email` = VALUES(`contact_email`), `is_active` = VALUES(`is_active`);
|
||||||
|
|
||||||
|
INSERT INTO `sufw_booking_registrations`
|
||||||
|
(`id`, `event_id`, `status`, `name`, `email`, `phone`, `privacy_accepted_at`, `confirmed_at`, `introduction_attended`, `introduction_date`)
|
||||||
|
VALUES
|
||||||
|
('e3c7f216-2704-4c81-b17a-000000000001', 'd3c7f216-2704-4c81-b17a-000000000001', 'confirmed', 'Demo Alina Beispiel', 'alina.beispiel@example.test', '+49 000 100001', DATE_SUB(NOW(), INTERVAL 35 DAY), DATE_SUB(NOW(), INTERVAL 35 DAY), 0, NULL),
|
||||||
|
('e3c7f216-2704-4c81-b17a-000000000002', 'd3c7f216-2704-4c81-b17a-000000000001', 'confirmed', 'Demo Cem Beispiel', 'cem.beispiel@example.test', '+49 000 100002', DATE_SUB(NOW(), INTERVAL 34 DAY), DATE_SUB(NOW(), INTERVAL 34 DAY), 0, NULL),
|
||||||
|
('e3c7f216-2704-4c81-b17a-000000000003', 'd3c7f216-2704-4c81-b17a-000000000002', 'confirmed', 'Demo Dana Beispiel', 'dana.beispiel@example.test', '+49 000 100003', NOW(), NOW(), 0, NULL),
|
||||||
|
('e3c7f216-2704-4c81-b17a-000000000004', 'd3c7f216-2704-4c81-b17a-000000000003', 'confirmed', 'Demo Emir Beispiel', 'emir.beispiel@example.test', '+49 000 100004', DATE_SUB(NOW(), INTERVAL 35 DAY), DATE_SUB(NOW(), INTERVAL 35 DAY), 0, NULL),
|
||||||
|
('e3c7f216-2704-4c81-b17a-000000000005', 'd3c7f216-2704-4c81-b17a-000000000004', 'confirmed', 'Demo Frida Beispiel', 'frida.beispiel@example.test', '+49 000 100005', NOW(), NOW(), 1, CURDATE())
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
`event_id` = VALUES(`event_id`), `status` = VALUES(`status`), `name` = VALUES(`name`), `email` = VALUES(`email`), `phone` = VALUES(`phone`), `privacy_accepted_at` = VALUES(`privacy_accepted_at`), `confirmed_at` = VALUES(`confirmed_at`), `introduction_attended` = VALUES(`introduction_attended`), `introduction_date` = VALUES(`introduction_date`), `removed_at` = NULL;
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sufw_booking_schema_migrations` (`version`) VALUES ('003_booking_demo_data');
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
-- SUFW Terminbuchung: Telefonnummern der Ansprechpersonen
|
||||||
|
--
|
||||||
|
-- Eigenständige, idempotente Migration. Sie erweitert das Terminmodell um
|
||||||
|
-- die Telefonnummer der fachlichen Ansprechperson.
|
||||||
|
|
||||||
|
ALTER TABLE `sufw_booking_events`
|
||||||
|
ADD COLUMN IF NOT EXISTS `contact_phone` varchar(64) NOT NULL DEFAULT '' AFTER `contact_email`;
|
||||||
|
|
||||||
|
-- Die fest versionierten Demo-Termine verwenden die abgestimmten Kontaktdaten.
|
||||||
|
-- Eigene, später angelegte Termine bleiben von diesen Updates unberührt.
|
||||||
|
UPDATE `sufw_booking_events`
|
||||||
|
SET `contact_name` = 'Carina Hollederer', `contact_email` = 'c.hollederer@sufw.de', `contact_phone` = '(0176) 17922244'
|
||||||
|
WHERE `id` IN (
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000001',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000002',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000003',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000004',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000005',
|
||||||
|
'd3c7f216-2704-4c81-b17a-000000000001',
|
||||||
|
'd3c7f216-2704-4c81-b17a-000000000002'
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE `sufw_booking_events`
|
||||||
|
SET `contact_name` = 'Sarah van den Heuvel', `contact_email` = 's.vandenHeuvel@sufw.de', `contact_phone` = '(0176) 60328929'
|
||||||
|
WHERE `id` IN (
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000006',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000007',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000008',
|
||||||
|
'6c7f216b-2704-4c81-b17a-000000000009',
|
||||||
|
'd3c7f216-2704-4c81-b17a-000000000003',
|
||||||
|
'd3c7f216-2704-4c81-b17a-000000000004'
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sufw_booking_schema_migrations` (`version`) VALUES ('004_booking_contact_phones');
|
||||||
@@ -9,6 +9,8 @@ services:
|
|||||||
APP_ENV: dev
|
APP_ENV: dev
|
||||||
CONTAO_ENVIRONMENT: dev
|
CONTAO_ENVIRONMENT: dev
|
||||||
DATABASE_URL: mysql://perspektivwerk:perspektivwerk@db:3306/perspektivwerk?serverVersion=mariadb-10.11.0
|
DATABASE_URL: mysql://perspektivwerk:perspektivwerk@db:3306/perspektivwerk?serverVersion=mariadb-10.11.0
|
||||||
|
BOOKING_BASE_URL: http://localhost:8080
|
||||||
|
BOOKING_MAIL_TRANSPORT: database
|
||||||
command:
|
command:
|
||||||
- sh
|
- sh
|
||||||
- -c
|
- -c
|
||||||
|
|||||||
@@ -44,6 +44,10 @@
|
|||||||
# directory request to Contao's front controller.
|
# directory request to Contao's front controller.
|
||||||
RewriteRule ^perspektivwerk/?$ perspektivwerk/index.html [L]
|
RewriteRule ^perspektivwerk/?$ perspektivwerk/index.html [L]
|
||||||
|
|
||||||
|
# The independent booking administration is a plain PHP application, not a
|
||||||
|
# Contao route. Serve its directory URL directly as well.
|
||||||
|
RewriteRule ^booking-admin/?$ booking-admin/index.php [L]
|
||||||
|
|
||||||
# If the requested filename exists, simply serve it.
|
# If the requested filename exists, simply serve it.
|
||||||
# We only want to let Apache serve files and not directories.
|
# We only want to let Apache serve files and not directories.
|
||||||
RewriteCond %{REQUEST_FILENAME} -f
|
RewriteCond %{REQUEST_FILENAME} -f
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__.'/../booking/backend.php';
|
||||||
|
|
||||||
|
session_name('sufw_booking_admin');
|
||||||
|
session_start();
|
||||||
|
$csrf = $_SESSION['csrf'] ??= bin2hex(random_bytes(32));
|
||||||
|
$database = bookingDatabase();
|
||||||
|
$project = (string) ($_GET['project'] ?? $_POST['project'] ?? 'perspektivwerk');
|
||||||
|
if (!bookingProjectIsValid($project)) $project = 'perspektivwerk';
|
||||||
|
$view = (string) ($_GET['view'] ?? 'events');
|
||||||
|
if (!in_array($view, ['events', 'registrations', 'export', 'export-data'], true)) $view = 'events';
|
||||||
|
|
||||||
|
function h(mixed $value): string { return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
|
||||||
|
function isQuarterHourDateTime(string $value): bool {
|
||||||
|
$timestamp = strtotime($value);
|
||||||
|
return $timestamp !== false && date('s', $timestamp) === '00' && ((int) date('i', $timestamp) % 15) === 0;
|
||||||
|
}
|
||||||
|
function adminBack(string $project, string $view, string $notice): never {
|
||||||
|
header('Location: ?project='.rawurlencode($project).'&view='.rawurlencode($view).'¬ice='.rawurlencode($notice));
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($view === 'export-data') {
|
||||||
|
$from = (string) ($_GET['from'] ?? '');
|
||||||
|
$to = (string) ($_GET['to'] ?? '');
|
||||||
|
$exportProject = (string) ($_GET['filterProject'] ?? 'all');
|
||||||
|
if (!in_array($exportProject, ['all', 'perspektivwerk', 'produktionsschule'], true)) $exportProject = 'all';
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $from) || !preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $to) || strtotime($from) === false || strtotime($to) === false || strtotime($from) > strtotime($to)) {
|
||||||
|
echo json_encode(['error' => 'Bitte wählen Sie einen gültigen Zeitraum.'], JSON_UNESCAPED_UNICODE);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
$sql = "SELECT e.title, DATE(e.starts_at) AS event_day, r.name FROM sufw_booking_registrations r JOIN sufw_booking_events e ON e.id = r.event_id WHERE r.status = 'confirmed' AND e.starts_at BETWEEN :fromDate AND :toDate";
|
||||||
|
$parameters = ['fromDate' => $from.' 00:00:00', 'toDate' => $to.' 23:59:59'];
|
||||||
|
if ($exportProject !== 'all') { $sql .= ' AND e.project = :exportProject'; $parameters['exportProject'] = $exportProject; }
|
||||||
|
$statement = $database->prepare($sql.' ORDER BY e.starts_at, r.name');
|
||||||
|
$statement->execute($parameters);
|
||||||
|
echo json_encode(['registrations' => $statement->fetchAll()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
|
if (!hash_equals($csrf, (string) ($_POST['csrf'] ?? ''))) { http_response_code(403); exit('Ungültige Sitzung.'); }
|
||||||
|
$action = (string) ($_POST['action'] ?? '');
|
||||||
|
if ($action === 'save_event') {
|
||||||
|
$id = (string) ($_POST['id'] ?? '') ?: bookingUuid();
|
||||||
|
$title = trim((string) ($_POST['title'] ?? ''));
|
||||||
|
$startsAt = str_replace('T', ' ', (string) ($_POST['starts_at'] ?? ''));
|
||||||
|
$endsAt = str_replace('T', ' ', (string) ($_POST['ends_at'] ?? ''));
|
||||||
|
$capacity = (int) ($_POST['capacity'] ?? 0);
|
||||||
|
$format = (string) ($_POST['format'] ?? 'vor_ort');
|
||||||
|
$contactName = trim((string) ($_POST['contact_name'] ?? ''));
|
||||||
|
$contactEmail = trim((string) ($_POST['contact_email'] ?? ''));
|
||||||
|
$contactPhone = trim((string) ($_POST['contact_phone'] ?? ''));
|
||||||
|
if ($title === '' || $capacity < 1 || $capacity > 100 || !in_array($format, ['vor_ort', 'telefonisch'], true) || $contactName === '' || $contactPhone === '' || !filter_var($contactEmail, FILTER_VALIDATE_EMAIL) || !isQuarterHourDateTime($startsAt) || !isQuarterHourDateTime($endsAt) || strtotime($endsAt) <= strtotime($startsAt)) adminBack($project, 'events', 'Bitte prüfen Sie die Termindaten. Uhrzeiten sind nur im 15-Minuten-Raster zulässig.');
|
||||||
|
$save = $database->prepare("INSERT INTO sufw_booking_events (id, project, title, starts_at, ends_at, capacity, format, introduction_required, contact_name, contact_email, contact_phone) VALUES (:id, :project, :title, :startsAt, :endsAt, :capacity, :format, :introductionRequired, :contactName, :contactEmail, :contactPhone) ON DUPLICATE KEY UPDATE title = VALUES(title), starts_at = VALUES(starts_at), ends_at = VALUES(ends_at), capacity = VALUES(capacity), format = VALUES(format), introduction_required = VALUES(introduction_required), contact_name = VALUES(contact_name), contact_email = VALUES(contact_email), contact_phone = VALUES(contact_phone)");
|
||||||
|
$save->execute(['id' => $id, 'project' => $project, 'title' => $title, 'startsAt' => $startsAt, 'endsAt' => $endsAt, 'capacity' => $capacity, 'format' => $format, 'introductionRequired' => isset($_POST['introduction_required']) ? 1 : 0, 'contactName' => $contactName, 'contactEmail' => $contactEmail, 'contactPhone' => $contactPhone]);
|
||||||
|
adminBack($project, 'events', 'Termin gespeichert.');
|
||||||
|
}
|
||||||
|
if ($action === 'toggle_event') {
|
||||||
|
$database->prepare('UPDATE sufw_booking_events SET is_active = 1 - is_active WHERE id = :id AND project = :project')->execute(['id' => $_POST['id'] ?? '', 'project' => $project]);
|
||||||
|
adminBack($project, 'events', 'Terminstatus geändert.');
|
||||||
|
}
|
||||||
|
if ($action === 'remove_registration') {
|
||||||
|
$database->prepare("UPDATE sufw_booking_registrations SET status = 'removed', removed_at = UTC_TIMESTAMP() WHERE id = :id AND status IN ('pending_confirmation', 'confirmed')")->execute(['id' => $_POST['id'] ?? '']);
|
||||||
|
adminBack($project, 'registrations', 'Teilnahme entfernt; die Kapazität ist wieder frei.');
|
||||||
|
}
|
||||||
|
if ($action === 'run_jobs') {
|
||||||
|
$result = bookingRunJobs($database);
|
||||||
|
adminBack($project, $view, "Jobs ausgeführt: {$result['expired']} abgelaufen, {$result['remindersConsidered']} Erinnerungen geprüft.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$titles = $database->prepare('SELECT DISTINCT title FROM sufw_booking_events WHERE project = :project ORDER BY title');
|
||||||
|
$titles->execute(['project' => $project]);
|
||||||
|
$titles = $titles->fetchAll(PDO::FETCH_COLUMN);
|
||||||
|
$contacts = $database->prepare('SELECT DISTINCT contact_name, contact_email, contact_phone FROM sufw_booking_events WHERE project = :project ORDER BY contact_name, contact_email');
|
||||||
|
$contacts->execute(['project' => $project]);
|
||||||
|
$contactByName = [];
|
||||||
|
$contactByEmail = [];
|
||||||
|
foreach ($contacts as $contact) { $contactByName[$contact['contact_name']] ??= ['email' => $contact['contact_email'], 'phone' => $contact['contact_phone']]; $contactByEmail[$contact['contact_email']] ??= ['name' => $contact['contact_name'], 'phone' => $contact['contact_phone']]; }
|
||||||
|
$settings = $database->prepare('SELECT feed_token FROM sufw_booking_project_settings WHERE project = :project');
|
||||||
|
$settings->execute(['project' => $project]);
|
||||||
|
$feedToken = (string) $settings->fetchColumn();
|
||||||
|
$notice = (string) ($_GET['notice'] ?? '');
|
||||||
|
|
||||||
|
$events = [];
|
||||||
|
$edit = null;
|
||||||
|
if ($view === 'events') {
|
||||||
|
$statement = $database->prepare("SELECT e.*, COUNT(CASE WHEN r.status = 'confirmed' THEN 1 END) AS confirmed_count FROM sufw_booking_events e LEFT JOIN sufw_booking_registrations r ON r.event_id = e.id WHERE e.project = :project GROUP BY e.id ORDER BY e.starts_at");
|
||||||
|
$statement->execute(['project' => $project]);
|
||||||
|
$events = $statement->fetchAll();
|
||||||
|
foreach ($events as $event) if ($event['id'] === ($_GET['edit'] ?? '')) $edit = $event;
|
||||||
|
}
|
||||||
|
$registrations = [];
|
||||||
|
if ($view === 'registrations') {
|
||||||
|
$statement = $database->prepare("SELECT r.*, e.title, e.starts_at FROM sufw_booking_registrations r JOIN sufw_booking_events e ON e.id = r.event_id WHERE e.project = :project ORDER BY r.created_at DESC LIMIT 200");
|
||||||
|
$statement->execute(['project' => $project]);
|
||||||
|
$registrations = $statement->fetchAll();
|
||||||
|
}
|
||||||
|
$outbox = [];
|
||||||
|
if ($view === 'events') {
|
||||||
|
$statement = $database->prepare("SELECT o.*, r.name FROM sufw_booking_outbox o JOIN sufw_booking_registrations r ON r.id = o.registration_id JOIN sufw_booking_events e ON e.id = r.event_id WHERE e.project = :project ORDER BY o.created_at DESC LIMIT 20");
|
||||||
|
$statement->execute(['project' => $project]);
|
||||||
|
$outbox = $statement->fetchAll();
|
||||||
|
}
|
||||||
|
$defaultFrom = date('Y-m-01');
|
||||||
|
$defaultTo = date('Y-m-t');
|
||||||
|
?>
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Terminbuchung · Testverwaltung</title>
|
||||||
|
<style>
|
||||||
|
:root{--green:#08752a;--bg:#f3f6f3;--line:#cad2cb;--ink:#202020}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.45 Arial,sans-serif}.shell{max-width:1180px;margin:auto;padding:1.5rem}header{display:flex;gap:1rem;justify-content:space-between;align-items:start;flex-wrap:wrap}h1,h2{color:var(--green)}h1{margin:0}.warning,.notice{padding:.75rem 1rem;border-left:4px solid #a36a00;background:#fff8e7}.notice{border-color:var(--green);background:#eaf6ed}.tabs{display:flex;flex-wrap:wrap;gap:.5rem;margin:1rem 0}.tabs a,.button,button{display:inline-block;padding:.65rem .85rem;border:1px solid var(--green);background:#fff;color:var(--green);font:inherit;text-decoration:none;cursor:pointer}.tabs a.active,button.primary{background:var(--green);color:#fff}.grid{display:grid;gap:1.25rem;grid-template-columns:1.25fr .75fr;margin-top:1.25rem}.card{background:#fff;border:1px solid var(--line);padding:1rem;overflow:auto}table{border-collapse:collapse;width:100%;min-width:680px}th,td{padding:.6rem;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}small{color:#555}.status{font-weight:bold}.confirmed{color:#08752a}.pending_confirmation{color:#a36a00}.removed,.expired{color:#8a1515}form.inline{display:inline}label{display:grid;gap:.25rem;font-weight:bold}input,select{font:inherit;padding:.55rem;border:1px solid #68736a;width:100%}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}.wide{grid-column:1/-1}pre{white-space:pre-wrap;max-width:42rem;font:13px/1.35 ui-monospace,monospace}.date-time-trigger{width:100%;min-height:2.75rem;text-align:left}.picker-dialog{width:min(25rem,calc(100% - 2rem));border:0;padding:0;box-shadow:0 .75rem 2rem #0006}.picker-dialog::backdrop{background:#0008}.picker-content{padding:1rem}.picker-head,.picker-actions{display:flex;justify-content:space-between;gap:.5rem;align-items:center}.picker-month{font-weight:bold;text-transform:capitalize}.picker-week,.picker-days{display:grid;grid-template-columns:repeat(7,1fr);gap:.25rem;text-align:center}.picker-week{margin:1rem 0 .25rem;font-size:.8rem;font-weight:bold}.picker-days button{min-height:2.4rem;padding:.25rem;border:1px solid transparent}.picker-days button.selected{background:var(--green);color:#fff}.picker-days button:disabled{visibility:hidden}.picker-time{display:grid;grid-template-columns:1fr 1fr;gap:.75rem;margin:1rem 0}.export-results{margin-top:1rem}.export-results li{margin:.5rem 0;white-space:nowrap;overflow-x:auto}@media(max-width:760px){.grid,.form-grid{grid-template-columns:1fr}.shell{padding:1rem}}
|
||||||
|
select[data-dropdown-indicator]{appearance:none;padding-right:2.5rem;background:#fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='%2308752a' d='m3 6 5 5 5-5z'/%3E%3C/svg%3E") no-repeat right .75rem center/1rem}</style></head><body><main class="shell">
|
||||||
|
<header><div><h1>Terminbuchung · Testverwaltung</h1></div><form method="post"><input type="hidden" name="csrf" value="<?=h($csrf)?>"><input type="hidden" name="project" value="<?=h($project)?>"><input type="hidden" name="action" value="run_jobs"><button>Jobs ausführen</button></form></header>
|
||||||
|
<?php if ($notice !== ''): ?><p class="notice"><?=h($notice)?></p><?php endif; ?>
|
||||||
|
<nav class="tabs"><a class="<?= $view === 'events' && $project === 'perspektivwerk' ? 'active' : '' ?>" href="?project=perspektivwerk&view=events">PerspektivWerk</a><a class="<?= $view === 'events' && $project === 'produktionsschule' ? 'active' : '' ?>" href="?project=produktionsschule&view=events">Produktionsschule</a><a class="<?= $view === 'registrations' ? 'active' : '' ?>" href="?project=<?=h($project)?>&view=registrations">Teilnahmen</a><a class="<?= $view === 'export' ? 'active' : '' ?>" href="?project=<?=h($project)?>&view=export">Export</a></nav>
|
||||||
|
|
||||||
|
<?php if ($view === 'events'): ?>
|
||||||
|
<section class="grid"><article class="card"><h2><?= $edit ? 'Termin bearbeiten' : 'Termin anlegen' ?></h2><form method="post"><input type="hidden" name="csrf" value="<?=h($csrf)?>"><input type="hidden" name="action" value="save_event"><input type="hidden" name="project" value="<?=h($project)?>"><input type="hidden" name="id" value="<?=h($edit['id'] ?? '')?>"><div class="form-grid">
|
||||||
|
<label class="wide">Terminart<select name="title" required data-dropdown-indicator><option value="">Terminart wählen …</option><?php foreach ($titles as $title): ?><option value="<?=h($title)?>" <?=($edit['title'] ?? '') === $title ? 'selected' : ''?>><?=h($title)?></option><?php endforeach; ?></select></label>
|
||||||
|
<label>Beginn<input type="hidden" name="starts_at" value="<?=h($edit['starts_at'] ?? '')?>"><button type="button" class="date-time-trigger" data-datetime-picker data-target="starts_at">Datum & Uhrzeit wählen</button></label><label>Ende<input type="hidden" name="ends_at" value="<?=h($edit['ends_at'] ?? '')?>"><button type="button" class="date-time-trigger" data-datetime-picker data-target="ends_at">Datum & Uhrzeit wählen</button></label>
|
||||||
|
<label>Kapazität (1–100)<input type="number" min="1" max="100" name="capacity" required value="<?=h($edit['capacity'] ?? 1)?>"></label><label>Format<select name="format"><option value="vor_ort" <?=($edit['format'] ?? '') === 'vor_ort' ? 'selected' : ''?>>Vor Ort</option><option value="telefonisch" <?=($edit['format'] ?? '') === 'telefonisch' ? 'selected' : ''?>>Telefonisch</option></select></label>
|
||||||
|
<label>Ansprechperson<select id="contact_name" name="contact_name" required data-dropdown-indicator><option value="">Ansprechperson wählen …</option><?php foreach ($contactByName as $name => $contact): ?><option value="<?=h($name)?>" <?=($edit['contact_name'] ?? '') === $name ? 'selected' : ''?>><?=h($name)?></option><?php endforeach; ?></select></label><label>Kontakt-E-Mail<select id="contact_email" name="contact_email" required data-dropdown-indicator><option value="">Kontakt-E-Mail wählen …</option><?php foreach ($contactByEmail as $email => $contact): ?><option value="<?=h($email)?>" <?=($edit['contact_email'] ?? '') === $email ? 'selected' : ''?>><?=h($email)?></option><?php endforeach; ?></select></label>
|
||||||
|
<label>Telefon Ansprechperson<input id="contact_phone" name="contact_phone" type="tel" required readonly value="<?=h($edit['contact_phone'] ?? '')?>"></label>
|
||||||
|
<label class="wide"><span><input type="checkbox" name="introduction_required" <?=!empty($edit['introduction_required']) ? 'checked' : ''?>> Einführungsveranstaltung erforderlich (PS-Probearbeiten)</span></label></div><p><button class="primary">Termin speichern</button><?php if ($edit): ?> <a class="button" href="?project=<?=h($project)?>&view=events">Abbrechen</a><?php endif; ?></p></form></article>
|
||||||
|
<aside class="card"><h2>Kalenderfeed</h2><p>Nur bestätigte Termine, ohne Teilnehmendendaten:</p><p><a href="<?=h(bookingBaseUrl().'/booking/ical.php?project='.$project.'&token='.$feedToken)?>">ICS-Feed öffnen</a></p></aside></section>
|
||||||
|
<section class="card"><h2>Termine</h2><table><thead><tr><th>Termin</th><th>Zeit</th><th>Kapazität</th><th>Status</th><th></th></tr></thead><tbody><?php foreach ($events as $event): ?><tr><td><strong><?=h($event['title'])?></strong><br><small><?=h($event['format'])?><?=!empty($event['introduction_required']) ? ' · Einführung erforderlich' : ''?></small></td><td><?=h($event['starts_at'])?><br>bis <?=h($event['ends_at'])?></td><td><?=h($event['confirmed_count'])?> / <?=h($event['capacity'])?> bestätigt</td><td><?= $event['is_active'] ? 'Aktiv' : 'Inaktiv' ?></td><td><a class="button" href="?project=<?=h($project)?>&view=events&edit=<?=h($event['id'])?>">Bearbeiten</a> <form class="inline" method="post"><input type="hidden" name="csrf" value="<?=h($csrf)?>"><input type="hidden" name="project" value="<?=h($project)?>"><input type="hidden" name="action" value="toggle_event"><input type="hidden" name="id" value="<?=h($event['id'])?>"><button><?= $event['is_active'] ? 'Deaktivieren' : 'Aktivieren' ?></button></form></td></tr><?php endforeach; ?></tbody></table></section>
|
||||||
|
<section class="card"><h2>Lokaler Mailausgang</h2><?php foreach ($outbox as $mail): ?><article><strong><?=h($mail['kind'])?></strong> · <?=h($mail['recipient_email'])?><br><small><?=h($mail['subject'])?></small><pre><?=h($mail['body'])?></pre></article><?php endforeach; ?></section>
|
||||||
|
<?php elseif ($view === 'registrations'): ?>
|
||||||
|
<section class="card"><h2>Teilnahmen · <?=h(bookingProjectTitle($project))?></h2><table><thead><tr><th>Person</th><th>Termin</th><th>Status</th><th></th></tr></thead><tbody><?php foreach ($registrations as $registration): ?><tr><td><?=h($registration['name'])?><br><small><?=h($registration['email'])?><br><?=h($registration['phone'])?></small></td><td><?=h($registration['title'])?><br><small><?=h($registration['starts_at'])?></small></td><td class="status <?=h($registration['status'])?>"><?=h($registration['status'])?></td><td><?php if (in_array($registration['status'], ['pending_confirmation','confirmed'], true)): ?><form method="post"><input type="hidden" name="csrf" value="<?=h($csrf)?>"><input type="hidden" name="project" value="<?=h($project)?>"><input type="hidden" name="action" value="remove_registration"><input type="hidden" name="id" value="<?=h($registration['id'])?>"><button>Entfernen</button></form><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></section>
|
||||||
|
<?php elseif ($view === 'export'): ?>
|
||||||
|
<section class="card"><h2>Bestätigte Teilnahmen anzeigen</h2><p>Der Zeitraum umfasst jeweils vollständige Kalendertage (00:00 bis 23:59 Uhr) und aktualisiert die Liste unmittelbar.</p><div class="form-grid"><label>Projekt<select id="export-project" data-dropdown-indicator><option value="all">PerspektivWerk und Produktionsschule</option><option value="perspektivwerk">Nur PerspektivWerk</option><option value="produktionsschule">Nur Produktionsschule</option></select></label>
|
||||||
|
<label></label>
|
||||||
|
<label>Von<input type="hidden" id="export-from" value="<?=h($defaultFrom)?>"><button type="button" class="date-time-trigger" data-date-picker data-target="export-from">Datum wählen</button></label>
|
||||||
|
<label>Bis<input type="hidden" id="export-to" value="<?=h($defaultTo)?>"><button type="button" class="date-time-trigger" data-date-picker data-target="export-to">Datum wählen</button></label>
|
||||||
|
</div><div id="export-results" class="export-results" role="status" aria-live="polite">Lade Teilnahmen …</div></section>
|
||||||
|
<?php endif; ?>
|
||||||
|
</main>
|
||||||
|
<dialog class="picker-dialog" id="date-time-dialog" aria-labelledby="date-time-title"><div class="picker-content"><div class="picker-head"><button type="button" data-picker-prev aria-label="Vorheriger Monat">‹</button><strong class="picker-month" id="date-time-title"></strong><button type="button" data-picker-next aria-label="Nächster Monat">›</button></div><div class="picker-week" aria-hidden="true"><span>Mo</span><span>Di</span><span>Mi</span><span>Do</span><span>Fr</span><span>Sa</span><span>So</span></div><div class="picker-days" data-picker-days></div><div class="picker-time" data-picker-time-controls><label>Stunde<select data-picker-hour></select></label><label>Viertelstunde<select data-picker-quarter></select></label></div><div class="picker-actions"><button type="button" data-picker-close>Schließen</button><button type="button" class="primary" data-picker-apply>Übernehmen</button></div></div></dialog>
|
||||||
|
<script>
|
||||||
|
const contactByName = <?=json_encode($contactByName, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT)?>;
|
||||||
|
const contactByEmail = <?=json_encode($contactByEmail, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT)?>;
|
||||||
|
const contactName = document.querySelector('#contact_name'), contactEmail = document.querySelector('#contact_email'), contactPhone = document.querySelector('#contact_phone');
|
||||||
|
contactName?.addEventListener('change', () => { const contact=contactByName[contactName.value]; if (contact) { contactEmail.value=contact.email; contactPhone.value=contact.phone; } });
|
||||||
|
contactEmail?.addEventListener('change', () => { const contact=contactByEmail[contactEmail.value]; if (contact) { contactName.value=contact.name; contactPhone.value=contact.phone; } });
|
||||||
|
const dialog = document.querySelector('#date-time-dialog'), days = dialog.querySelector('[data-picker-days]'), monthLabel = dialog.querySelector('.picker-month'), timeControls = dialog.querySelector('[data-picker-time-controls]'), hourSelect = dialog.querySelector('[data-picker-hour]'), quarterSelect = dialog.querySelector('[data-picker-quarter]');
|
||||||
|
const hours = Array.from({length:24}, (_,hour) => String(hour).padStart(2,'0'));
|
||||||
|
hourSelect.innerHTML = hours.map(hour => '<option value="' + hour + '">' + hour + ' Uhr</option>').join('');
|
||||||
|
quarterSelect.innerHTML = ['00','15','30','45'].map(minute => '<option value="' + minute + '">' + minute + ' Min.</option>').join('');
|
||||||
|
let pickerTarget, pickerDate, pickerMonth, pickerMode;
|
||||||
|
const asDate = value => { const parts = String(value || '').match(/^(\\d{4})-(\\d{2})-(\\d{2})(?:[ T](\\d{2}):(\\d{2}))?/); return parts ? new Date(Number(parts[1]), Number(parts[2])-1, Number(parts[3]), Number(parts[4] || 0), Number(parts[5] || 0)) : new Date(); };
|
||||||
|
const formatDateValue = date => String(date.getFullYear())+'-'+String(date.getMonth()+1).padStart(2,'0')+'-'+String(date.getDate()).padStart(2,'0');
|
||||||
|
const formatValue = date => formatDateValue(date)+' '+String(date.getHours()).padStart(2,'0')+':'+String(date.getMinutes()).padStart(2,'0')+':00';
|
||||||
|
const formatLabel = (value, includeTime) => value ? new Intl.DateTimeFormat('de-DE', includeTime ? {dateStyle:'medium',timeStyle:'short'} : {dateStyle:'medium'}).format(asDate(value)) : (includeTime ? 'Datum & Uhrzeit wählen' : 'Datum wählen');
|
||||||
|
const getTarget = name => document.querySelector('[name="'+name+'"],#'+name);
|
||||||
|
const syncPickerLabels = () => document.querySelectorAll('[data-datetime-picker],[data-date-picker]').forEach(button => { const input = getTarget(button.dataset.target); button.textContent = formatLabel(input?.value, button.hasAttribute('data-datetime-picker')); });
|
||||||
|
function renderPicker() {
|
||||||
|
monthLabel.textContent = new Intl.DateTimeFormat('de-DE',{month:'long',year:'numeric'}).format(pickerMonth);
|
||||||
|
const first = new Date(pickerMonth.getFullYear(),pickerMonth.getMonth(),1), offset = (first.getDay()+6)%7, last = new Date(pickerMonth.getFullYear(),pickerMonth.getMonth()+1,0).getDate();
|
||||||
|
days.innerHTML = Array.from({length:offset+last}, (_,index) => { if(index<offset) return '<button type="button" disabled></button>'; const day=index-offset+1, selected=pickerDate.getFullYear()===pickerMonth.getFullYear()&&pickerDate.getMonth()===pickerMonth.getMonth()&&pickerDate.getDate()===day; return '<button type="button" data-picker-day="'+day+'" class="'+(selected?'selected':'')+'" aria-pressed="'+selected+'">'+day+'</button>'; }).join('');
|
||||||
|
days.querySelectorAll('[data-picker-day]').forEach(button => button.addEventListener('click', () => { pickerDate = new Date(pickerMonth.getFullYear(),pickerMonth.getMonth(),Number(button.dataset.pickerDay),pickerDate.getHours(),pickerDate.getMinutes()); renderPicker(); }));
|
||||||
|
}
|
||||||
|
document.querySelectorAll('[data-datetime-picker],[data-date-picker]').forEach(button => button.addEventListener('click', () => { pickerTarget=getTarget(button.dataset.target); pickerMode=button.hasAttribute('data-date-picker') ? 'date' : 'datetime'; pickerDate=asDate(pickerTarget.value); pickerMonth=new Date(pickerDate.getFullYear(),pickerDate.getMonth(),1); timeControls.hidden=pickerMode === 'date'; hourSelect.value=String(pickerDate.getHours()).padStart(2,'0'); quarterSelect.value=String(Math.floor(pickerDate.getMinutes()/15)*15).padStart(2,'0'); renderPicker(); dialog.showModal(); }));
|
||||||
|
dialog.querySelector('[data-picker-prev]').addEventListener('click', () => { pickerMonth=new Date(pickerMonth.getFullYear(),pickerMonth.getMonth()-1,1); renderPicker(); });
|
||||||
|
dialog.querySelector('[data-picker-next]').addEventListener('click', () => { pickerMonth=new Date(pickerMonth.getFullYear(),pickerMonth.getMonth()+1,1); renderPicker(); });
|
||||||
|
dialog.querySelector('[data-picker-close]').addEventListener('click', () => dialog.close());
|
||||||
|
dialog.querySelector('[data-picker-apply]').addEventListener('click', () => { if (pickerMode === 'datetime') pickerDate.setHours(Number(hourSelect.value),Number(quarterSelect.value),0,0); pickerTarget.value=pickerMode === 'date' ? formatDateValue(pickerDate) : formatValue(pickerDate); syncPickerLabels(); pickerTarget.dispatchEvent(new Event('booking-datetime-change')); dialog.close(); });
|
||||||
|
syncPickerLabels();
|
||||||
|
const exportResults=document.querySelector('#export-results');
|
||||||
|
const escapeHtml = value => String(value).replace(/[&<>"']/g, character => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[character]));
|
||||||
|
async function updateExport() { if(!exportResults)return; const from=document.querySelector('#export-from').value,to=document.querySelector('#export-to').value,filterProject=document.querySelector('#export-project').value; exportResults.textContent='Lade Teilnahmen …'; const result=await fetch('?view=export-data&filterProject='+encodeURIComponent(filterProject)+'&from='+encodeURIComponent(from)+'&to='+encodeURIComponent(to)).then(response=>response.json()); if(result.error){exportResults.textContent=result.error;return;} exportResults.innerHTML=result.registrations.length?'<p>'+result.registrations.length+' bestätigte Teilnahme(n)</p><ul>'+result.registrations.map(item=>'<li><strong>'+escapeHtml(item.name)+'</strong> · '+escapeHtml(item.title)+' · '+escapeHtml(item.event_day)+'</li>').join('')+'</ul>':'<p>Für diesen Zeitraum liegen keine bestätigten Teilnahmen vor.</p>'; }
|
||||||
|
document.querySelectorAll('#export-from,#export-to').forEach(input=>input.addEventListener('booking-datetime-change',updateExport)); document.querySelector('#export-project')?.addEventListener('change', updateExport); updateExport();
|
||||||
|
</script></body></html>
|
||||||
@@ -2,13 +2,7 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
/**
|
require __DIR__.'/backend.php';
|
||||||
* Öffentliche Demo-API der Terminbuchung.
|
|
||||||
*
|
|
||||||
* Die Datei ist absichtlich nicht an Contao-Tabellen gekoppelt: Sie wird unter
|
|
||||||
* /booking/api.php direkt von Apache ausgeliefert und kann dadurch gleich aus
|
|
||||||
* der statischen Vorschau und aus einem Contao-HTML-Element verwendet werden.
|
|
||||||
*/
|
|
||||||
|
|
||||||
header('Content-Type: application/json; charset=utf-8');
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
header('Cache-Control: no-store');
|
header('Cache-Control: no-store');
|
||||||
@@ -21,246 +15,58 @@ function respond(int $status, array $payload): never
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
function bookingDatabase(): PDO
|
|
||||||
{
|
|
||||||
$databaseUrl = getenv('DATABASE_URL');
|
|
||||||
if (!is_string($databaseUrl) || $databaseUrl === '') {
|
|
||||||
throw new RuntimeException('DATABASE_URL is not configured.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$parts = parse_url($databaseUrl);
|
|
||||||
if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'mysql' || !isset($parts['host'], $parts['path'], $parts['user'])) {
|
|
||||||
throw new RuntimeException('DATABASE_URL is invalid.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$database = ltrim($parts['path'], '/');
|
|
||||||
if ($database === '') {
|
|
||||||
throw new RuntimeException('DATABASE_URL has no database name.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$port = isset($parts['port']) ? (int) $parts['port'] : 3306;
|
|
||||||
$dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $parts['host'], $port, $database);
|
|
||||||
|
|
||||||
return new PDO($dsn, rawurldecode($parts['user']), rawurldecode($parts['pass'] ?? ''), [
|
|
||||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
||||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
||||||
PDO::ATTR_EMULATE_PREPARES => false,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function bookingSession(): void
|
function bookingSession(): void
|
||||||
{
|
{
|
||||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
if (session_status() === PHP_SESSION_ACTIVE) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
session_name('sufw_booking');
|
session_name('sufw_booking');
|
||||||
session_set_cookie_params([
|
session_set_cookie_params(['httponly' => true, 'samesite' => 'Lax', 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')]);
|
||||||
'httponly' => true,
|
|
||||||
'samesite' => 'Lax',
|
|
||||||
'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
|
|
||||||
]);
|
|
||||||
session_start();
|
session_start();
|
||||||
}
|
}
|
||||||
|
|
||||||
function csrfToken(): string
|
function csrfToken(): string
|
||||||
{
|
{
|
||||||
bookingSession();
|
bookingSession();
|
||||||
if (!isset($_SESSION['csrf_token'])) {
|
return $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
|
||||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return $_SESSION['csrf_token'];
|
function readPayload(): array
|
||||||
}
|
|
||||||
|
|
||||||
function ensureBookingRateLimit(): void
|
|
||||||
{
|
{
|
||||||
bookingSession();
|
if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 32768) respond(413, ['error' => 'Die Anfrage ist zu groß.']);
|
||||||
$now = time();
|
try { $payload = json_decode((string) file_get_contents('php://input'), true, 32, JSON_THROW_ON_ERROR); }
|
||||||
$recent = array_values(array_filter($_SESSION['booking_requests'] ?? [], static fn ($timestamp): bool => is_int($timestamp) && $timestamp > $now - 900));
|
catch (JsonException) { respond(400, ['error' => 'Die Anfrage konnte nicht verarbeitet werden.']); }
|
||||||
if (count($recent) >= 10) {
|
if (!is_array($payload)) respond(400, ['error' => 'Die Anfrage konnte nicht verarbeitet werden.']);
|
||||||
respond(429, ['error' => 'Zu viele Anfragen. Bitte versuchen Sie es später erneut.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$recent[] = $now;
|
|
||||||
$_SESSION['booking_requests'] = $recent;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readJsonBody(): array
|
|
||||||
{
|
|
||||||
$contentLength = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
|
|
||||||
if ($contentLength > 32768) {
|
|
||||||
respond(413, ['error' => 'Die Anfrage ist zu groß.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$payload = json_decode((string) file_get_contents('php://input'), true, 32, JSON_THROW_ON_ERROR);
|
|
||||||
} catch (JsonException) {
|
|
||||||
respond(400, ['error' => 'Die Anfrage konnte nicht verarbeitet werden.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!is_array($payload)) {
|
|
||||||
respond(400, ['error' => 'Die Anfrage konnte nicht verarbeitet werden.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $payload;
|
return $payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringField(array $payload, string $name, int $maxLength): string
|
function ensureRateLimit(): void
|
||||||
{
|
{
|
||||||
$value = trim((string) ($payload[$name] ?? ''));
|
bookingSession();
|
||||||
if ($value === '' || mb_strlen($value) > $maxLength) {
|
$now = time();
|
||||||
throw new InvalidArgumentException($name);
|
$recent = array_values(array_filter($_SESSION['booking_requests'] ?? [], static fn ($value): bool => is_int($value) && $value > $now - 900));
|
||||||
}
|
if (count($recent) >= 10) respond(429, ['error' => 'Zu viele Anfragen. Bitte versuchen Sie es später erneut.']);
|
||||||
|
$recent[] = $now;
|
||||||
return $value;
|
$_SESSION['booking_requests'] = $recent;
|
||||||
}
|
|
||||||
|
|
||||||
function dateField(array $payload, string $name): ?string
|
|
||||||
{
|
|
||||||
$value = trim((string) ($payload[$name] ?? ''));
|
|
||||||
if ($value === '') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
|
||||||
return $date && $date->format('Y-m-d') === $value ? $value : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function registrationId(): string
|
|
||||||
{
|
|
||||||
$hex = bin2hex(random_bytes(16));
|
|
||||||
return sprintf('%s-%s-%s-%s-%s', substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4), substr($hex, 16, 4), substr($hex, 20));
|
|
||||||
}
|
|
||||||
|
|
||||||
function normaliseEvent(array $event): array
|
|
||||||
{
|
|
||||||
$event['id'] = (string) $event['id'];
|
|
||||||
$event['capacity'] = (int) $event['capacity'];
|
|
||||||
$event['confirmedCount'] = (int) $event['confirmedCount'];
|
|
||||||
$event['availableCapacity'] = max(0, $event['capacity'] - $event['confirmedCount']);
|
|
||||||
$event['status'] = $event['availableCapacity'] > 0 ? 'available' : 'full';
|
|
||||||
$event['introductionRequired'] = (bool) $event['introductionRequired'];
|
|
||||||
unset($event['confirmedCount']);
|
|
||||||
return $event;
|
|
||||||
}
|
|
||||||
|
|
||||||
function listEvents(PDO $database): never
|
|
||||||
{
|
|
||||||
$project = (string) ($_GET['project'] ?? '');
|
|
||||||
$from = (string) ($_GET['from'] ?? '');
|
|
||||||
$to = (string) ($_GET['to'] ?? '');
|
|
||||||
if (!in_array($project, ['perspektivwerk', 'produktionsschule'], true) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
|
|
||||||
respond(400, ['error' => 'Ungültige Kalenderanfrage.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$fromDate = DateTimeImmutable::createFromFormat('!Y-m-d', $from);
|
|
||||||
$toDate = DateTimeImmutable::createFromFormat('!Y-m-d', $to);
|
|
||||||
if (!$fromDate || !$toDate || $fromDate >= $toDate || $fromDate->diff($toDate)->days > 93) {
|
|
||||||
respond(400, ['error' => 'Ungültiger Kalenderzeitraum.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$statement = $database->prepare(<<<'SQL'
|
|
||||||
SELECT e.id, e.project, e.title, e.starts_at AS startsAt, e.ends_at AS endsAt,
|
|
||||||
e.capacity, e.format, e.introduction_required AS introductionRequired,
|
|
||||||
e.contact_name AS contactName,
|
|
||||||
COUNT(r.id) AS confirmedCount
|
|
||||||
FROM sufw_booking_events e
|
|
||||||
LEFT JOIN sufw_booking_registrations r ON r.event_id = e.id AND r.status = 'confirmed'
|
|
||||||
WHERE e.project = :project AND e.is_active = 1
|
|
||||||
AND e.starts_at < :toDate AND e.ends_at >= :fromDate
|
|
||||||
GROUP BY e.id
|
|
||||||
ORDER BY e.starts_at, e.title
|
|
||||||
SQL);
|
|
||||||
$statement->execute(['project' => $project, 'fromDate' => "$from 00:00:00", 'toDate' => "$to 00:00:00"]);
|
|
||||||
|
|
||||||
respond(200, ['csrfToken' => csrfToken(), 'events' => array_map('normaliseEvent', $statement->fetchAll())]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createRegistration(PDO $database): never
|
|
||||||
{
|
|
||||||
ensureBookingRateLimit();
|
|
||||||
$providedToken = (string) ($_SERVER['HTTP_X_SUFW_BOOKING_CSRF'] ?? '');
|
|
||||||
if (!hash_equals(csrfToken(), $providedToken)) {
|
|
||||||
respond(403, ['error' => 'Die Sitzung ist abgelaufen. Bitte laden Sie den Kalender neu.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$payload = readJsonBody();
|
|
||||||
$project = (string) ($payload['project'] ?? '');
|
|
||||||
$eventId = (string) ($payload['eventId'] ?? '');
|
|
||||||
$privacyAccepted = ($payload['privacyAccepted'] ?? false) === true;
|
|
||||||
try {
|
|
||||||
$name = stringField($payload, 'name', 160);
|
|
||||||
$email = mb_strtolower(stringField($payload, 'email', 254));
|
|
||||||
$phone = stringField($payload, 'phone', 64);
|
|
||||||
} catch (InvalidArgumentException) {
|
|
||||||
respond(422, ['error' => 'Bitte prüfen Sie Ihre Pflichtangaben.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!in_array($project, ['perspektivwerk', 'produktionsschule'], true) || !preg_match('/^[a-f0-9-]{36}$/', $eventId) || !filter_var($email, FILTER_VALIDATE_EMAIL) || !preg_match('/^[0-9+()\-\/\s]{6,64}$/', $phone) || !$privacyAccepted) {
|
|
||||||
respond(422, ['error' => 'Bitte prüfen Sie Ihre Pflichtangaben.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$introductionAttended = ($payload['introductionAttended'] ?? false) === true;
|
|
||||||
$introductionDate = dateField($payload, 'introductionDate');
|
|
||||||
try {
|
|
||||||
$database->beginTransaction();
|
|
||||||
$eventStatement = $database->prepare('SELECT id, introduction_required, capacity FROM sufw_booking_events WHERE id = :id AND project = :project AND is_active = 1 FOR UPDATE');
|
|
||||||
$eventStatement->execute(['id' => $eventId, 'project' => $project]);
|
|
||||||
$event = $eventStatement->fetch();
|
|
||||||
if (!$event) {
|
|
||||||
$database->rollBack();
|
|
||||||
respond(404, ['error' => 'Dieser Termin ist nicht mehr verfügbar.']);
|
|
||||||
}
|
|
||||||
if ((bool) $event['introduction_required'] && (!$introductionAttended || $introductionDate === null)) {
|
|
||||||
$database->rollBack();
|
|
||||||
respond(422, ['error' => 'Bitte bestätigen Sie die Einführungsveranstaltung und geben Sie das Datum an.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$countStatement = $database->prepare("SELECT COUNT(*) FROM sufw_booking_registrations WHERE event_id = :eventId AND status = 'confirmed'");
|
|
||||||
$countStatement->execute(['eventId' => $eventId]);
|
|
||||||
if ((int) $countStatement->fetchColumn() >= (int) $event['capacity']) {
|
|
||||||
$database->rollBack();
|
|
||||||
respond(409, ['error' => 'Dieser Termin ist inzwischen ausgebucht. Bitte wählen Sie einen anderen Termin.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$duplicateStatement = $database->prepare("SELECT id FROM sufw_booking_registrations WHERE event_id = :eventId AND status = 'confirmed' AND email = :email AND name = :name LIMIT 1");
|
|
||||||
$duplicateStatement->execute(['eventId' => $eventId, 'email' => $email, 'name' => $name]);
|
|
||||||
if ($duplicateStatement->fetch()) {
|
|
||||||
$database->rollBack();
|
|
||||||
respond(409, ['error' => 'Für diese Person liegt bereits eine bestätigte Anmeldung vor.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insert = $database->prepare(<<<'SQL'
|
|
||||||
INSERT INTO sufw_booking_registrations
|
|
||||||
(id, event_id, status, name, email, phone, privacy_accepted_at, introduction_attended, introduction_date)
|
|
||||||
VALUES
|
|
||||||
(:id, :eventId, 'confirmed', :name, :email, :phone, UTC_TIMESTAMP(), :introductionAttended, :introductionDate)
|
|
||||||
SQL);
|
|
||||||
$insert->execute([
|
|
||||||
'id' => registrationId(), 'eventId' => $eventId, 'name' => $name, 'email' => $email, 'phone' => $phone,
|
|
||||||
'introductionAttended' => $introductionAttended ? 1 : 0,
|
|
||||||
'introductionDate' => $introductionAttended ? $introductionDate : null,
|
|
||||||
]);
|
|
||||||
$database->commit();
|
|
||||||
} catch (Throwable $exception) {
|
|
||||||
if ($database->inTransaction()) {
|
|
||||||
$database->rollBack();
|
|
||||||
}
|
|
||||||
error_log('SUFW booking API: '.$exception->getMessage());
|
|
||||||
respond(500, ['error' => 'Die Anmeldung konnte nicht gespeichert werden. Bitte versuchen Sie es später erneut.']);
|
|
||||||
}
|
|
||||||
|
|
||||||
respond(201, ['message' => 'Ihre Anmeldung wurde verbindlich gespeichert.']);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$database = bookingDatabase();
|
$database = bookingDatabase();
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
||||||
listEvents($database);
|
$project = (string) ($_GET['project'] ?? '');
|
||||||
|
$from = (string) ($_GET['from'] ?? '');
|
||||||
|
$to = (string) ($_GET['to'] ?? '');
|
||||||
|
$fromDate = DateTimeImmutable::createFromFormat('!Y-m-d', $from);
|
||||||
|
$toDate = DateTimeImmutable::createFromFormat('!Y-m-d', $to);
|
||||||
|
if (!bookingProjectIsValid($project) || !$fromDate || !$toDate || $fromDate >= $toDate || $fromDate->diff($toDate)->days > 93) respond(400, ['error' => 'Ungültige Kalenderanfrage.']);
|
||||||
|
respond(200, ['csrfToken' => csrfToken(), 'events' => bookingListEvents($database, $project, $from, $to)]);
|
||||||
}
|
}
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
createRegistration($database);
|
ensureRateLimit();
|
||||||
|
if (!hash_equals(csrfToken(), (string) ($_SERVER['HTTP_X_SUFW_BOOKING_CSRF'] ?? ''))) respond(403, ['error' => 'Die Sitzung ist abgelaufen. Bitte laden Sie den Kalender neu.']);
|
||||||
|
try { $registration = bookingCreateRegistration($database, readPayload()); }
|
||||||
|
catch (InvalidArgumentException $exception) { respond(422, ['error' => $exception->getMessage()]); }
|
||||||
|
catch (OutOfBoundsException $exception) { respond(404, ['error' => $exception->getMessage()]); }
|
||||||
|
catch (LogicException|RuntimeException $exception) { respond(409, ['error' => $exception->getMessage()]); }
|
||||||
|
respond(202, ['message' => 'Ihre Anfrage wurde gespeichert. Bitte bestätigen Sie den Link aus der E-Mail innerhalb von 30 Minuten.', 'expiresAt' => $registration['expiresAt']]);
|
||||||
}
|
}
|
||||||
header('Allow: GET, POST');
|
header('Allow: GET, POST');
|
||||||
respond(405, ['error' => 'Diese Methode wird nicht unterstützt.']);
|
respond(405, ['error' => 'Diese Methode wird nicht unterstützt.']);
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
function bookingDatabase(): PDO
|
||||||
|
{
|
||||||
|
$url = getenv('DATABASE_URL');
|
||||||
|
$parts = is_string($url) ? parse_url($url) : false;
|
||||||
|
if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'mysql' || !isset($parts['host'], $parts['path'], $parts['user'])) {
|
||||||
|
throw new RuntimeException('DATABASE_URL is not configured correctly.');
|
||||||
|
}
|
||||||
|
$dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4', $parts['host'], (int) ($parts['port'] ?? 3306), ltrim($parts['path'], '/'));
|
||||||
|
return new PDO($dsn, rawurldecode($parts['user']), rawurldecode($parts['pass'] ?? ''), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingBaseUrl(): string
|
||||||
|
{
|
||||||
|
$configured = getenv('BOOKING_BASE_URL');
|
||||||
|
if (is_string($configured) && $configured !== '') {
|
||||||
|
return rtrim($configured, '/');
|
||||||
|
}
|
||||||
|
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
|
||||||
|
return $scheme.'://'.($_SERVER['HTTP_HOST'] ?? 'localhost');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingUuid(): string
|
||||||
|
{
|
||||||
|
$hex = bin2hex(random_bytes(16));
|
||||||
|
return sprintf('%s-%s-%s-%s-%s', substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4), substr($hex, 16, 4), substr($hex, 20));
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingProjectIsValid(string $project): bool
|
||||||
|
{
|
||||||
|
return in_array($project, ['perspektivwerk', 'produktionsschule'], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingProjectTitle(string $project): string
|
||||||
|
{
|
||||||
|
return $project === 'produktionsschule' ? 'Produktionsschule' : 'PerspektivWerk';
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingQueueMail(PDO $database, string $registrationId, string $kind, string $email, string $subject, string $body): void
|
||||||
|
{
|
||||||
|
$statement = $database->prepare('INSERT IGNORE INTO sufw_booking_outbox (registration_id, kind, recipient_email, subject, body) VALUES (:registrationId, :kind, :email, :subject, :body)');
|
||||||
|
$statement->execute(compact('registrationId', 'kind', 'email', 'subject', 'body'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingNormaliseEvent(array $event): array
|
||||||
|
{
|
||||||
|
$event['capacity'] = (int) $event['capacity'];
|
||||||
|
$event['confirmedCount'] = (int) $event['confirmedCount'];
|
||||||
|
$event['availableCapacity'] = max(0, $event['capacity'] - $event['confirmedCount']);
|
||||||
|
$event['status'] = $event['availableCapacity'] > 0 ? 'available' : 'full';
|
||||||
|
$event['introductionRequired'] = (bool) $event['introductionRequired'];
|
||||||
|
unset($event['confirmedCount']);
|
||||||
|
return $event;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingListEvents(PDO $database, string $project, string $from, string $to): array
|
||||||
|
{
|
||||||
|
$statement = $database->prepare(<<<'SQL'
|
||||||
|
SELECT e.id, e.project, e.title, e.starts_at AS startsAt, e.ends_at AS endsAt, e.capacity,
|
||||||
|
e.format, e.introduction_required AS introductionRequired, e.contact_name AS contactName,
|
||||||
|
COUNT(r.id) AS confirmedCount
|
||||||
|
FROM sufw_booking_events e
|
||||||
|
LEFT JOIN sufw_booking_registrations r ON r.event_id = e.id AND r.status = 'confirmed'
|
||||||
|
WHERE e.project = :project AND e.is_active = 1 AND e.starts_at < :toDate AND e.ends_at >= :fromDate
|
||||||
|
GROUP BY e.id ORDER BY e.starts_at, e.title
|
||||||
|
SQL);
|
||||||
|
$statement->execute(['project' => $project, 'fromDate' => "$from 00:00:00", 'toDate' => "$to 00:00:00"]);
|
||||||
|
return array_map('bookingNormaliseEvent', $statement->fetchAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingCreateRegistration(PDO $database, array $payload): array
|
||||||
|
{
|
||||||
|
$project = (string) ($payload['project'] ?? '');
|
||||||
|
$eventId = (string) ($payload['eventId'] ?? '');
|
||||||
|
$name = trim((string) ($payload['name'] ?? ''));
|
||||||
|
$email = mb_strtolower(trim((string) ($payload['email'] ?? '')));
|
||||||
|
$phone = trim((string) ($payload['phone'] ?? ''));
|
||||||
|
$privacyAccepted = ($payload['privacyAccepted'] ?? false) === true;
|
||||||
|
$introductionAttended = ($payload['introductionAttended'] ?? false) === true;
|
||||||
|
$introductionDate = trim((string) ($payload['introductionDate'] ?? ''));
|
||||||
|
if (!bookingProjectIsValid($project) || !preg_match('/^[a-f0-9-]{36}$/', $eventId) || $name === '' || mb_strlen($name) > 160 || !filter_var($email, FILTER_VALIDATE_EMAIL) || mb_strlen($email) > 254 || !preg_match('/^[0-9+()\-\/\s]{6,64}$/', $phone) || !$privacyAccepted) {
|
||||||
|
throw new InvalidArgumentException('Bitte prüfen Sie Ihre Pflichtangaben.');
|
||||||
|
}
|
||||||
|
if ($introductionDate !== '' && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $introductionDate) || !DateTimeImmutable::createFromFormat('!Y-m-d', $introductionDate))) {
|
||||||
|
throw new InvalidArgumentException('Bitte prüfen Sie das Datum der Einführungsveranstaltung.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$database->beginTransaction();
|
||||||
|
try {
|
||||||
|
$eventStatement = $database->prepare('SELECT * FROM sufw_booking_events WHERE id = :id AND project = :project AND is_active = 1 FOR UPDATE');
|
||||||
|
$eventStatement->execute(['id' => $eventId, 'project' => $project]);
|
||||||
|
$event = $eventStatement->fetch();
|
||||||
|
if (!$event) throw new OutOfBoundsException('Dieser Termin ist nicht mehr verfügbar.');
|
||||||
|
if ((bool) $event['introduction_required'] && (!$introductionAttended || $introductionDate === '')) {
|
||||||
|
throw new InvalidArgumentException('Bitte bestätigen Sie die Einführungsveranstaltung und geben Sie das Datum an.');
|
||||||
|
}
|
||||||
|
$confirmed = $database->prepare("SELECT COUNT(*) FROM sufw_booking_registrations WHERE event_id = :eventId AND status = 'confirmed'");
|
||||||
|
$confirmed->execute(['eventId' => $eventId]);
|
||||||
|
if ((int) $confirmed->fetchColumn() >= (int) $event['capacity']) throw new RuntimeException('Dieser Termin ist inzwischen ausgebucht.');
|
||||||
|
$duplicate = $database->prepare("SELECT id FROM sufw_booking_registrations WHERE event_id = :eventId AND email = :email AND name = :name AND status IN ('pending_confirmation', 'confirmed') LIMIT 1");
|
||||||
|
$duplicate->execute(['eventId' => $eventId, 'email' => $email, 'name' => $name]);
|
||||||
|
if ($duplicate->fetch()) throw new LogicException('Für diese Person liegt bereits eine Anmeldung für diesen Termin vor.');
|
||||||
|
|
||||||
|
$registrationId = bookingUuid();
|
||||||
|
$token = bin2hex(random_bytes(32));
|
||||||
|
$insert = $database->prepare(<<<'SQL'
|
||||||
|
INSERT INTO sufw_booking_registrations
|
||||||
|
(id, event_id, status, name, email, phone, privacy_accepted_at, confirmation_token_hash, confirmation_expires_at, introduction_attended, introduction_date)
|
||||||
|
VALUES
|
||||||
|
(:id, :eventId, 'pending_confirmation', :name, :email, :phone, UTC_TIMESTAMP(), :tokenHash, DATE_ADD(UTC_TIMESTAMP(), INTERVAL 30 MINUTE), :introductionAttended, :introductionDate)
|
||||||
|
SQL);
|
||||||
|
$insert->execute(['id' => $registrationId, 'eventId' => $eventId, 'name' => $name, 'email' => $email, 'phone' => $phone, 'tokenHash' => hash('sha256', $token), 'introductionAttended' => $introductionAttended ? 1 : 0, 'introductionDate' => $introductionAttended ? $introductionDate : null]);
|
||||||
|
$link = bookingBaseUrl().'/booking/confirm.php?token='.rawurlencode($token);
|
||||||
|
$subject = 'Bitte bestätigen Sie Ihre Terminanfrage';
|
||||||
|
$body = "Guten Tag $name,\n\nbitte bestätigen Sie Ihre Anfrage für \"{$event['title']}\" am {$event['starts_at']} innerhalb von 30 Minuten:\n$link\n\nKontakt für Rückfragen: {$event['contact_name']} ({$event['contact_email']}).";
|
||||||
|
bookingQueueMail($database, $registrationId, 'confirmation_request', $email, $subject, $body);
|
||||||
|
$database->commit();
|
||||||
|
return ['registrationId' => $registrationId, 'expiresAt' => gmdate('c', time() + 1800)];
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
if ($database->inTransaction()) $database->rollBack();
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingConfirmRegistration(PDO $database, string $token): array
|
||||||
|
{
|
||||||
|
if (!preg_match('/^[a-f0-9]{64}$/', $token)) throw new InvalidArgumentException('Der Bestätigungslink ist ungültig.');
|
||||||
|
$database->beginTransaction();
|
||||||
|
try {
|
||||||
|
$statement = $database->prepare(<<<'SQL'
|
||||||
|
SELECT r.*, e.title, e.project, e.starts_at, e.ends_at, e.capacity, e.contact_name, e.contact_email
|
||||||
|
FROM sufw_booking_registrations r JOIN sufw_booking_events e ON e.id = r.event_id
|
||||||
|
WHERE r.confirmation_token_hash = :tokenHash FOR UPDATE
|
||||||
|
SQL);
|
||||||
|
$statement->execute(['tokenHash' => hash('sha256', $token)]);
|
||||||
|
$registration = $statement->fetch();
|
||||||
|
if (!$registration || $registration['status'] !== 'pending_confirmation') throw new OutOfBoundsException('Dieser Bestätigungslink ist nicht mehr gültig.');
|
||||||
|
if (strtotime($registration['confirmation_expires_at'].' UTC') < time()) {
|
||||||
|
$database->prepare("UPDATE sufw_booking_registrations SET status = 'expired' WHERE id = :id")->execute(['id' => $registration['id']]);
|
||||||
|
$database->commit();
|
||||||
|
throw new OutOfBoundsException('Die Bestätigungsfrist ist abgelaufen. Bitte fragen Sie den Termin erneut an.');
|
||||||
|
}
|
||||||
|
$count = $database->prepare("SELECT COUNT(*) FROM sufw_booking_registrations WHERE event_id = :eventId AND status = 'confirmed'");
|
||||||
|
$count->execute(['eventId' => $registration['event_id']]);
|
||||||
|
if ((int) $count->fetchColumn() >= (int) $registration['capacity']) throw new RuntimeException('Der Termin wurde inzwischen vergeben. Bitte wählen Sie einen anderen Termin.');
|
||||||
|
$database->prepare("UPDATE sufw_booking_registrations SET status = 'confirmed', confirmed_at = UTC_TIMESTAMP(), confirmation_token_hash = NULL WHERE id = :id")->execute(['id' => $registration['id']]);
|
||||||
|
$history = $database->prepare(<<<'SQL'
|
||||||
|
SELECT e.title, e.starts_at FROM sufw_booking_registrations r JOIN sufw_booking_events e ON e.id = r.event_id
|
||||||
|
WHERE r.email = :email AND r.name = :name AND r.status = 'confirmed' ORDER BY e.starts_at
|
||||||
|
SQL);
|
||||||
|
$history->execute(['email' => $registration['email'], 'name' => $registration['name']]);
|
||||||
|
$appointments = implode("\n", array_map(static fn (array $row): string => "- {$row['title']} am {$row['starts_at']}", $history->fetchAll()));
|
||||||
|
$body = "Guten Tag {$registration['name']},\n\nIhr Termin ist bestätigt:\n{$registration['title']} am {$registration['starts_at']} bis {$registration['ends_at']}.\n\nIhre weiteren bestätigten Termine:\n$appointments\n\nBei Stornierungswunsch wenden Sie sich an {$registration['contact_name']} ({$registration['contact_email']}).";
|
||||||
|
bookingQueueMail($database, $registration['id'], 'confirmation', $registration['email'], 'Ihr Termin ist bestätigt', $body);
|
||||||
|
$database->commit();
|
||||||
|
return $registration;
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
if ($database->inTransaction()) $database->rollBack();
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingRunJobs(PDO $database): array
|
||||||
|
{
|
||||||
|
$expired = $database->exec("UPDATE sufw_booking_registrations SET status = 'expired' WHERE status = 'pending_confirmation' AND confirmation_expires_at < UTC_TIMESTAMP()");
|
||||||
|
$reminders = $database->query(<<<'SQL'
|
||||||
|
SELECT r.id, r.email, r.name, e.title, e.starts_at, e.contact_name, e.contact_email
|
||||||
|
FROM sufw_booking_registrations r JOIN sufw_booking_events e ON e.id = r.event_id
|
||||||
|
WHERE r.status = 'confirmed' AND DATE(e.starts_at) = DATE_ADD(UTC_DATE(), INTERVAL 2 DAY)
|
||||||
|
SQL)->fetchAll();
|
||||||
|
foreach ($reminders as $reminder) {
|
||||||
|
$body = "Guten Tag {$reminder['name']},\n\ndies ist die Erinnerung an Ihren Termin \"{$reminder['title']}\" am {$reminder['starts_at']}.\n\nKontakt: {$reminder['contact_name']} ({$reminder['contact_email']}).";
|
||||||
|
bookingQueueMail($database, $reminder['id'], 'reminder', $reminder['email'], 'Erinnerung an Ihren Termin', $body);
|
||||||
|
}
|
||||||
|
return ['expired' => $expired, 'remindersConsidered' => count($reminders)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingIcsEscape(string $value): string
|
||||||
|
{
|
||||||
|
return str_replace(["\\", ";", ",", "\n"], ["\\\\", "\\;", "\\,", "\\n"], $value);
|
||||||
|
}
|
||||||
@@ -50,7 +50,7 @@ export function validateBookingForm({ name = '', email = '', phone = '', privacy
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
|
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
|
||||||
export function bookingConfirmationMessage(appointmentTitle) { return `Ihre Anmeldung für ${appointmentTitle} wurde verbindlich gespeichert.`; }
|
export function bookingConfirmationMessage(appointmentTitle) { return `Ihre Anfrage für ${appointmentTitle} wurde gespeichert. Bitte bestätigen Sie den Link aus der E-Mail innerhalb von 30 Minuten.`; }
|
||||||
function escapeHtml(value) { return String(value).replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); }
|
function escapeHtml(value) { return String(value).replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); }
|
||||||
|
|
||||||
function createMonthDates(month) {
|
function createMonthDates(month) {
|
||||||
@@ -89,7 +89,7 @@ function openConfirmationDialog(container, event) {
|
|||||||
const dialog = document.createElement('dialog');
|
const dialog = document.createElement('dialog');
|
||||||
dialog.className = 'sufw-booking__dialog';
|
dialog.className = 'sufw-booking__dialog';
|
||||||
dialog.setAttribute('aria-labelledby', 'sufw-booking-confirmation-title');
|
dialog.setAttribute('aria-labelledby', 'sufw-booking-confirmation-title');
|
||||||
dialog.innerHTML = `<section class="sufw-booking__form"><header class="sufw-booking__form-header"><p class="sufw-booking__eyebrow">Termin bestätigt</p><h2 id="sufw-booking-confirmation-title">Vielen Dank für Ihre Anmeldung</h2><p>${escapeHtml(bookingConfirmationMessage(event.title))}</p></header><p class="sufw-booking__appointment"><strong>${escapeHtml(event.project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule')}</strong><br>${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(event.title)}</p><p>Dies ist die lokale Demoversion. Es wird noch keine Bestätigungs-, Erinnerungs- oder Kalender-E-Mail versendet.</p><div class="sufw-booking__form-actions"><button type="button" data-close-confirmation>Schließen</button></div></section>`;
|
dialog.innerHTML = `<section class="sufw-booking__form"><header class="sufw-booking__form-header"><p class="sufw-booking__eyebrow">E-Mail bestätigen</p><h2 id="sufw-booking-confirmation-title">Fast geschafft</h2><p>${escapeHtml(bookingConfirmationMessage(event.title))}</p></header><p class="sufw-booking__appointment"><strong>${escapeHtml(event.project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule')}</strong><br>${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(event.title)}</p><p>In der lokalen Demo liegt die Nachricht im Mailausgang des Verwaltungsbereichs bereit.</p><div class="sufw-booking__form-actions"><button type="button" data-close-confirmation>Schließen</button></div></section>`;
|
||||||
dialog.querySelector('[data-close-confirmation]').addEventListener('click', () => dialog.close());
|
dialog.querySelector('[data-close-confirmation]').addEventListener('click', () => dialog.close());
|
||||||
dialog.addEventListener('close', () => dialog.remove());
|
dialog.addEventListener('close', () => dialog.remove());
|
||||||
container.append(dialog);
|
container.append(dialog);
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__.'/backend.php';
|
||||||
|
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
header('Cache-Control: no-store');
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
|
||||||
|
function page(string $title, string $message, bool $success = false): never
|
||||||
|
{
|
||||||
|
$safeTitle = htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
$safeMessage = htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
$class = $success ? 'success' : 'error';
|
||||||
|
echo "<!doctype html><html lang=\"de\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>$safeTitle</title><style>body{font:18px/1.5 Arial,sans-serif;margin:0;background:#f3f6f3;color:#202020}.box{max-width:42rem;margin:12vh auto;padding:2rem;background:#fff;border-top:6px solid #08752a}.success{color:#08752a}.error{color:#8a1515}a{color:#08752a}</style><main class=\"box\"><h1 class=\"$class\">$safeTitle</h1><p>$safeMessage</p><p><a href=\"/perspektivwerk/\">Zurück zur Terminbuchung</a></p></main></html>";
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$registration = bookingConfirmRegistration(bookingDatabase(), (string) ($_GET['token'] ?? ''));
|
||||||
|
page('Termin bestätigt', "Vielen Dank. Ihr Termin \"{$registration['title']}\" ist verbindlich bestätigt.", true);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
page('Bestätigung nicht möglich', $exception->getMessage());
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__.'/backend.php';
|
||||||
|
|
||||||
|
$project = (string) ($_GET['project'] ?? '');
|
||||||
|
$token = (string) ($_GET['token'] ?? '');
|
||||||
|
if (!bookingProjectIsValid($project) || !preg_match('/^[a-f0-9]{64}$/', $token)) {
|
||||||
|
http_response_code(404);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$database = bookingDatabase();
|
||||||
|
$settings = $database->prepare('SELECT feed_token FROM sufw_booking_project_settings WHERE project = :project');
|
||||||
|
$settings->execute(['project' => $project]);
|
||||||
|
if (!hash_equals((string) $settings->fetchColumn(), $token)) {
|
||||||
|
http_response_code(404);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$events = $database->prepare(<<<'SQL'
|
||||||
|
SELECT e.id, e.title, e.starts_at, e.ends_at, e.format
|
||||||
|
FROM sufw_booking_events e
|
||||||
|
WHERE e.project = :project AND EXISTS (SELECT 1 FROM sufw_booking_registrations r WHERE r.event_id = e.id AND r.status = 'confirmed')
|
||||||
|
ORDER BY e.starts_at
|
||||||
|
SQL);
|
||||||
|
$events->execute(['project' => $project]);
|
||||||
|
$timezone = new DateTimeZone('Europe/Berlin');
|
||||||
|
$utc = new DateTimeZone('UTC');
|
||||||
|
$lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//SUFW//Terminbuchung//DE', 'CALSCALE:GREGORIAN', 'X-WR-CALNAME:'.bookingIcsEscape(bookingProjectTitle($project))];
|
||||||
|
foreach ($events as $event) {
|
||||||
|
$start = new DateTimeImmutable($event['starts_at'], $timezone);
|
||||||
|
$end = new DateTimeImmutable($event['ends_at'], $timezone);
|
||||||
|
$lines[] = 'BEGIN:VEVENT';
|
||||||
|
$lines[] = 'UID:'.bookingIcsEscape($event['id']).'@sufw-booking';
|
||||||
|
$lines[] = 'DTSTAMP:'.gmdate('Ymd\\THis\\Z');
|
||||||
|
$lines[] = 'DTSTART:'.$start->setTimezone($utc)->format('Ymd\\THis\\Z');
|
||||||
|
$lines[] = 'DTEND:'.$end->setTimezone($utc)->format('Ymd\\THis\\Z');
|
||||||
|
$lines[] = 'SUMMARY:'.bookingIcsEscape($event['title']);
|
||||||
|
$lines[] = 'DESCRIPTION:'.bookingIcsEscape($event['format'] === 'telefonisch' ? 'Telefonischer Termin' : 'Termin vor Ort');
|
||||||
|
$lines[] = 'END:VEVENT';
|
||||||
|
}
|
||||||
|
$lines[] = 'END:VCALENDAR';
|
||||||
|
header('Content-Type: text/calendar; charset=utf-8');
|
||||||
|
header('Content-Disposition: inline; filename="'.($project === 'produktionsschule' ? 'produktionsschule' : 'perspektivwerk').'-termine.ics"');
|
||||||
|
header('Cache-Control: no-store');
|
||||||
|
echo implode("\r\n", $lines)."\r\n";
|
||||||
@@ -50,7 +50,7 @@ export function validateBookingForm({ name = '', email = '', phone = '', privacy
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
|
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
|
||||||
export function bookingConfirmationMessage(appointmentTitle) { return `Ihre Anmeldung für ${appointmentTitle} wurde verbindlich gespeichert.`; }
|
export function bookingConfirmationMessage(appointmentTitle) { return `Ihre Anfrage für ${appointmentTitle} wurde gespeichert. Bitte bestätigen Sie den Link aus der E-Mail innerhalb von 30 Minuten.`; }
|
||||||
function escapeHtml(value) { return String(value).replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); }
|
function escapeHtml(value) { return String(value).replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); }
|
||||||
|
|
||||||
function createMonthDates(month) {
|
function createMonthDates(month) {
|
||||||
@@ -89,7 +89,7 @@ function openConfirmationDialog(container, event) {
|
|||||||
const dialog = document.createElement('dialog');
|
const dialog = document.createElement('dialog');
|
||||||
dialog.className = 'sufw-booking__dialog';
|
dialog.className = 'sufw-booking__dialog';
|
||||||
dialog.setAttribute('aria-labelledby', 'sufw-booking-confirmation-title');
|
dialog.setAttribute('aria-labelledby', 'sufw-booking-confirmation-title');
|
||||||
dialog.innerHTML = `<section class="sufw-booking__form"><header class="sufw-booking__form-header"><p class="sufw-booking__eyebrow">Termin bestätigt</p><h2 id="sufw-booking-confirmation-title">Vielen Dank für Ihre Anmeldung</h2><p>${escapeHtml(bookingConfirmationMessage(event.title))}</p></header><p class="sufw-booking__appointment"><strong>${escapeHtml(event.project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule')}</strong><br>${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(event.title)}</p><p>Dies ist die lokale Demoversion. Es wird noch keine Bestätigungs-, Erinnerungs- oder Kalender-E-Mail versendet.</p><div class="sufw-booking__form-actions"><button type="button" data-close-confirmation>Schließen</button></div></section>`;
|
dialog.innerHTML = `<section class="sufw-booking__form"><header class="sufw-booking__form-header"><p class="sufw-booking__eyebrow">E-Mail bestätigen</p><h2 id="sufw-booking-confirmation-title">Fast geschafft</h2><p>${escapeHtml(bookingConfirmationMessage(event.title))}</p></header><p class="sufw-booking__appointment"><strong>${escapeHtml(event.project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule')}</strong><br>${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(event.title)}</p><p>In der lokalen Demo liegt die Nachricht im Mailausgang des Verwaltungsbereichs bereit.</p><div class="sufw-booking__form-actions"><button type="button" data-close-confirmation>Schließen</button></div></section>`;
|
||||||
dialog.querySelector('[data-close-confirmation]').addEventListener('click', () => dialog.close());
|
dialog.querySelector('[data-close-confirmation]').addEventListener('click', () => dialog.close());
|
||||||
dialog.addEventListener('close', () => dialog.remove());
|
dialog.addEventListener('close', () => dialog.remove());
|
||||||
container.append(dialog);
|
container.append(dialog);
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__.'/../public/booking/backend.php';
|
||||||
|
|
||||||
|
$database = bookingDatabase();
|
||||||
|
$result = bookingRunJobs($database);
|
||||||
|
$transport = getenv('BOOKING_MAIL_TRANSPORT') ?: 'database';
|
||||||
|
if ($transport === 'mail') {
|
||||||
|
$outbox = $database->query('SELECT id, recipient_email, subject, body FROM sufw_booking_outbox WHERE sent_at IS NULL ORDER BY id');
|
||||||
|
foreach ($outbox as $mail) {
|
||||||
|
if (mail($mail['recipient_email'], $mail['subject'], $mail['body'])) {
|
||||||
|
$database->prepare('UPDATE sufw_booking_outbox SET sent_at = UTC_TIMESTAMP() WHERE id = :id')->execute(['id' => $mail['id']]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
@@ -22,3 +22,63 @@ test('hält die statische Vorschaukopie der Buchungsassets identisch', async ()
|
|||||||
assert.equal(previewScript, componentScript);
|
assert.equal(previewScript, componentScript);
|
||||||
assert.equal(previewStyle, componentStyle);
|
assert.equal(previewStyle, componentStyle);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('modelliert Bestätigung, Mailausgang und ICS-Feeds als zweite Migration', async () => {
|
||||||
|
const migration = await readFile(new URL('../database/migrations/002_booking_workflow.sql', import.meta.url), 'utf8');
|
||||||
|
|
||||||
|
assert.match(migration, /confirmation_token_hash/);
|
||||||
|
assert.match(migration, /confirmation_expires_at/);
|
||||||
|
assert.match(migration, /CREATE TABLE IF NOT EXISTS `sufw_booking_outbox`/);
|
||||||
|
assert.match(migration, /CREATE TABLE IF NOT EXISTS `sufw_booking_project_settings`/);
|
||||||
|
assert.match(migration, /UNIQUE KEY `sufw_booking_outbox_registration_kind`/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('liefert lokale Demo-Termine und bestätigte Teilnahmen vor und nach dem heutigen Datum', async () => {
|
||||||
|
const migration = await readFile(new URL('../database/migrations/003_booking_demo_data.sql', import.meta.url), 'utf8');
|
||||||
|
|
||||||
|
assert.match(migration, /Nur für lokale Entwicklungs- und Testdatenbanken/);
|
||||||
|
assert.match(migration, /DATE_ADD\(CURDATE\(\), INTERVAL -1 MONTH\)/);
|
||||||
|
assert.match(migration, /DATE_ADD\(CURDATE\(\), INTERVAL 1 MONTH\)/);
|
||||||
|
assert.match(migration, /'confirmed'/);
|
||||||
|
assert.match(migration, /sufw_booking_registrations/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('erweitert Demo-Kontakte um die vorgesehenen Ansprechpartnerdaten', async () => {
|
||||||
|
const migration = await readFile(new URL('../database/migrations/004_booking_contact_phones.sql', import.meta.url), 'utf8');
|
||||||
|
|
||||||
|
assert.match(migration, /ADD COLUMN IF NOT EXISTS `contact_phone`/);
|
||||||
|
assert.match(migration, /Carina Hollederer/);
|
||||||
|
assert.match(migration, /Sarah van den Heuvel/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('liefert die unabhängige Verwaltung unter booking-admin mit getrennten Bereichen', async () => {
|
||||||
|
const [routes, admin] = await Promise.all([
|
||||||
|
readFile(new URL('../public/.htaccess', import.meta.url), 'utf8'),
|
||||||
|
readFile(new URL('../public/booking-admin/index.php', import.meta.url), 'utf8'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.match(routes, /\^booking-admin\/\?\$ booking-admin\/index\.php/);
|
||||||
|
assert.match(admin, /view === 'registrations'/);
|
||||||
|
assert.match(admin, /view === 'export'/);
|
||||||
|
assert.doesNotMatch(admin, /getenv\(/);
|
||||||
|
assert.match(admin, />Teilnahmen</);
|
||||||
|
assert.match(admin, />Export</);
|
||||||
|
assert.match(admin, /data-datetime-picker/);
|
||||||
|
assert.match(admin, /data-date-picker/);
|
||||||
|
assert.doesNotMatch(admin, /datetime-local/);
|
||||||
|
assert.match(admin, /data-picker-hour/);
|
||||||
|
assert.match(admin, /data-picker-quarter/);
|
||||||
|
assert.match(admin, /Array\.from\(\{length:24\}/);
|
||||||
|
assert.match(admin, /\['00','15','30','45'\]/);
|
||||||
|
assert.match(admin, /data-picker-close/);
|
||||||
|
assert.match(admin, /<select name="title"/);
|
||||||
|
assert.match(admin, /data-dropdown-indicator/);
|
||||||
|
assert.match(admin, /SELECT DISTINCT contact_name, contact_email, contact_phone/);
|
||||||
|
assert.match(admin, /contactByName\[contactName\.value\]/);
|
||||||
|
assert.match(admin, /contactByEmail\[contactEmail\.value\]/);
|
||||||
|
assert.match(admin, /booking-datetime-change/);
|
||||||
|
assert.match(admin, /id="export-project"/);
|
||||||
|
assert.match(admin, /DATE\(e\.starts_at\) AS event_day/);
|
||||||
|
assert.match(admin, /export-project/);
|
||||||
|
assert.doesNotMatch(admin, /text\/csv|fputcsv/i);
|
||||||
|
});
|
||||||
@@ -55,8 +55,8 @@ test('gibt den Absenden-Button erst nach DSGVO-Einwilligung frei', () => {
|
|||||||
assert.equal(canSubmitBookingForm(true), true);
|
assert.equal(canSubmitBookingForm(true), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('zeigt nach dem Absenden eine verbindliche Bestätigung ohne Mockup-Hinweis', () => {
|
test('zeigt nach dem Absenden den nächsten Bestätigungsschritt ohne Mockup-Hinweis', () => {
|
||||||
const message = bookingConfirmationMessage('Erstgespräch');
|
const message = bookingConfirmationMessage('Erstgespräch');
|
||||||
assert.match(message, /verbindlich gespeichert/);
|
assert.match(message, /E-Mail/);
|
||||||
assert.doesNotMatch(message, /Vorschau|Mockup/i);
|
assert.doesNotMatch(message, /Vorschau|Mockup/i);
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user