reorder folders for easy 1:1 upload to boogie server

This commit is contained in:
Robert Wartenberg committed 2026-08-31 11:40:54 +02:00
1 parent de5895f558
commit 6c16e16354
20 files changed
+171 -52

No files matched your search

@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
require __DIR__.'/backend.php';
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
function respond(int $status, array $payload): never
{
http_response_code($status);
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
exit;
}
function bookingSession(): void
{
if (session_status() === PHP_SESSION_ACTIVE) return;
session_name('sufw_booking');
session_set_cookie_params(['httponly' => true, 'samesite' => 'Lax', 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')]);
session_start();
}
function csrfToken(): string
{
bookingSession();
return $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
}
function readPayload(): array
{
if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 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;
}
function ensureRateLimit(): void
{
bookingSession();
$now = time();
$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;
$_SESSION['booking_requests'] = $recent;
}
try {
$database = bookingDatabase();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$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') {
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');
respond(405, ['error' => 'Diese Methode wird nicht unterstützt.']);
} catch (Throwable $exception) {
error_log('SUFW booking API: '.$exception->getMessage());
respond(500, ['error' => 'Der Kalender ist vorübergehend nicht verfügbar.']);
}
@@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
function bookingDatabaseUrl(?string $environmentUrl = null, ?string $configurationFile = null): string
{
$url = $environmentUrl ?? getenv('DATABASE_URL');
if (!is_string($url) || trim($url) === '') {
$configurationFile ??= dirname(__DIR__, 2).'/booking-config.php';
if (is_file($configurationFile)) {
$configuration = require $configurationFile;
$url = is_array($configuration) ? ($configuration['database_url'] ?? '') : '';
}
}
if (!is_string($url) || trim($url) === '') {
throw new RuntimeException('DATABASE_URL is not configured and the booking configuration file does not contain a database URL.');
}
return trim($url);
}
function bookingDatabase(): PDO
{
$url = bookingDatabaseUrl();
$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);
}
@@ -0,0 +1,356 @@
.sufw-booking {
--sufw-booking-green: #08752a;
--sufw-booking-text: #202020;
--sufw-booking-muted: #5a5a5a;
--sufw-booking-line: #c7c7c7;
--sufw-booking-pale: #f3f6f3;
box-sizing: border-box;
max-width: 860px;
margin: 2rem auto;
padding: 1.25rem;
color: var(--sufw-booking-text);
background: #fff;
border: 1px solid var(--sufw-booking-line);
font: 1rem/1.5 Arial, "Helvetica Neue", sans-serif;
}
.sufw-booking * {
box-sizing: border-box;
}
.sufw-booking__header h2,
.sufw-booking__slots h3 {
margin: 0.15rem 0 0.5rem;
color: var(--sufw-booking-green);
font-size: 1.4rem;
}
.sufw-booking__header p {
margin: 0.3rem 0;
}
.sufw-booking__eyebrow {
color: var(--sufw-booking-green);
font-size: 0.875rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.sufw-booking__legend {
display: flex;
gap: 1rem;
flex-wrap: wrap;
margin: 1.25rem 0;
font-size: 0.9rem;
}
.sufw-booking__marker {
display: inline-block;
width: 0.8rem;
height: 0.8rem;
margin-right: 0.35rem;
border-radius: 50%;
}
.sufw-booking__marker--available {
background: var(--sufw-booking-green);
}
.sufw-booking__marker--booked {
background: #535353;
}
.sufw-booking__month-nav {
display: grid;
grid-template-columns: 3rem 1fr 3rem;
align-items: center;
margin-top: 1rem;
text-align: center;
}
.sufw-booking__month-nav h3 {
margin: 0;
font-size: 1.1rem;
text-transform: capitalize;
}
.sufw-booking__nav,
.sufw-booking__day,
.sufw-booking__slot {
font: inherit;
}
.sufw-booking__nav {
min-width: 2.75rem;
min-height: 2.75rem;
border: 1px solid var(--sufw-booking-green);
color: var(--sufw-booking-green);
background: #fff;
font-size: 1.7rem;
cursor: pointer;
}
.sufw-booking__nav:hover,
.sufw-booking__nav:focus-visible {
background: var(--sufw-booking-pale);
}
.sufw-booking__weekdays,
.sufw-booking__calendar {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 0.3rem;
}
.sufw-booking__weekdays {
margin-top: 1rem;
text-align: center;
font-weight: 700;
font-size: 0.8rem;
}
.sufw-booking__day {
display: grid;
place-items: center;
gap: 0.1rem;
min-height: 3.8rem;
padding: 0.25rem;
border: 1px solid transparent;
background: #fff;
color: var(--sufw-booking-text);
cursor: pointer;
}
.sufw-booking__day:hover {
border-color: var(--sufw-booking-green);
background: var(--sufw-booking-pale);
}
.sufw-booking__day--available {
background: #dff3e4;
border-color: var(--sufw-booking-green);
}
.sufw-booking__day--booked {
background: #ececec;
border-color: #777;
}
.sufw-booking__day.is-selected {
outline: 3px solid #1f4fbc;
outline-offset: 1px;
}
.sufw-booking__day small {
font-size: 0.7rem;
}
.sufw-booking__empty {
min-height: 3.8rem;
}
.sufw-booking__slots {
margin-top: 1.5rem;
padding-top: 1.25rem;
border-top: 1px solid var(--sufw-booking-line);
}
.sufw-booking__slots ul {
padding: 0;
margin: 0;
list-style: none;
}
.sufw-booking__slot {
display: grid;
grid-template-columns: 5rem 1fr auto;
gap: 0.7rem;
width: 100%;
margin: 0.45rem 0;
padding: 0.8rem;
text-align: left;
color: var(--sufw-booking-text);
background: #fff;
border: 1px solid var(--sufw-booking-green);
cursor: pointer;
}
.sufw-booking__slot:hover,
.sufw-booking__slot:focus-visible {
background: var(--sufw-booking-pale);
}
.sufw-booking__slot em {
color: var(--sufw-booking-green);
font-style: normal;
font-weight: 700;
}
.sufw-booking__slot span {
display: grid;
gap: 0.15rem;
}
.sufw-booking__slot small {
color: var(--sufw-booking-muted);
font-size: 0.875rem;
font-weight: 400;
}
.sufw-booking__slot:disabled {
border-color: #777;
background: #eee;
color: #555;
cursor: not-allowed;
}
.sufw-booking__slot:disabled em {
color: #555;
}
.sufw-booking__empty-state,
.sufw-booking__status {
margin: 0.7rem 0;
}
.sufw-booking__status {
font-weight: 700;
}
.sufw-booking__dialog {
width: min(42rem, calc(100% - 2rem));
max-height: calc(100vh - 2rem);
padding: 0;
border: 0;
color: var(--sufw-booking-text);
box-shadow: 0 0.75rem 2.5rem rgba(0, 0, 0, 0.35);
font: 1rem/1.5 Arial, "Helvetica Neue", sans-serif;
}
.sufw-booking__dialog::backdrop {
background: rgba(0, 0, 0, 0.62);
}
.sufw-booking__form {
display: grid;
gap: 1rem;
padding: 1.25rem;
}
.sufw-booking__form-header {
padding-bottom: 1rem;
border-bottom: 1px solid var(--sufw-booking-line);
}
.sufw-booking__form-header h2 {
margin: 0.15rem 0 0.5rem;
color: var(--sufw-booking-green);
font-size: 1.5rem;
}
.sufw-booking__appointment,
.sufw-booking__required,
.sufw-booking__prototype-note {
margin: 0.35rem 0;
}
.sufw-booking__required {
font-size: 0.875rem;
}
.sufw-booking__optional {
color: var(--sufw-booking-muted);
font-size: 0.875rem;
font-weight: 400;
}
.sufw-booking__form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.sufw-booking__form label {
display: grid;
gap: 0.35rem;
font-weight: 700;
}
.sufw-booking__form input,
.sufw-booking__form textarea {
width: 100%;
padding: 0.65rem;
border: 1px solid #767676;
color: var(--sufw-booking-text);
font: inherit;
}
.sufw-booking__form input:focus-visible,
.sufw-booking__form textarea:focus-visible,
.sufw-booking__form button:focus-visible {
outline: 3px solid #1f4fbc;
outline-offset: 2px;
}
.sufw-booking__consent {
grid-template-columns: auto 1fr;
align-items: start;
font-weight: 400 !important;
}
.sufw-booking__consent input {
width: 1.1rem !important;
height: 1.1rem;
margin-top: 0.25rem;
}
.sufw-booking__form-errors:empty {
display: none;
}
.sufw-booking__form-errors {
padding: 0.75rem;
border-left: 4px solid #a31111;
background: #fff1f1;
color: #6c0808;
}
.sufw-booking__conditional {
display: grid;
gap: 0.8rem;
margin: 0;
padding: 1rem;
border: 1px solid var(--sufw-booking-line);
}
.sufw-booking__conditional legend {
padding: 0 0.25rem;
font-weight: 700;
}
.sufw-booking__load-error {
margin: 1rem 0;
padding: 1rem;
border-left: 4px solid #a31111;
background: #fff1f1;
color: #6c0808;
}
.sufw-booking__form-errors ul {
margin: 0;
padding-left: 1.25rem;
}
.sufw-booking__prototype-note {
padding: 0.75rem;
background: var(--sufw-booking-pale);
font-size: 0.9rem;
}
.sufw-booking__form-status {
margin: 0;
color: var(--sufw-booking-green);
font-weight: 700;
}
.sufw-booking__form-actions {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
flex-wrap: wrap;
}
.sufw-booking__form-actions button {
padding: 0.7rem 1rem;
border: 1px solid var(--sufw-booking-green);
background-color: #08752a;
color: #fff;
font: inherit;
font-weight: 700;
cursor: pointer;
}
.sufw-booking__form-actions button:hover:not(:disabled) {
border-color: #05571f;
background-color: #05571f;
color: #fff;
}
.sufw-booking__form-actions button:disabled {
border-color: #777;
background-color: #d8d8d8;
color: #555;
cursor: not-allowed;
}
.sufw-booking__form-actions .sufw-booking__secondary {
background-color: #fff;
color: var(--sufw-booking-green);
}
@media (max-width: 520px) {
.sufw-booking {
margin: 1rem 0;
padding: 1rem;
}
.sufw-booking__weekdays {
font-size: 0.7rem;
}
.sufw-booking__day {
min-height: 3.4rem;
padding: 0.15rem;
}
.sufw-booking__slot {
grid-template-columns: 1fr;
gap: 0.15rem;
}
.sufw-booking__slot strong {
font-size: 1.1rem;
}
.sufw-booking__form-grid {
grid-template-columns: 1fr;
}
.sufw-booking__form-actions button {
width: 100%;
}
}
@@ -0,0 +1,192 @@
/* Browsernatives ES-Modul; wird ohne Build-Schritt ausgeliefert. */
const dateFormatter = new Intl.DateTimeFormat('de-DE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
const monthFormatter = new Intl.DateTimeFormat('de-DE', { month: 'long', year: 'numeric' });
const timeFormatter = new Intl.DateTimeFormat('de-DE', { hour: '2-digit', minute: '2-digit' });
const weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
const sessionProfileKey = 'sufw-booking-profile-v1';
function parseDateTime(value) { return new Date(value.replace(' ', 'T')); }
function parseDate(value) { return new Date(`${value}T12:00:00`); }
export function formatDateKey(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
function eventDateRange(event) { return [event.startsAt.slice(0, 10), event.endsAt.slice(0, 10)]; }
function occursOnDate(event, date) { const [startDate, endDate] = eventDateRange(event); return startDate <= date && endDate >= date; }
export function getSlotsForDate(project, date, events = []) { return events.filter((event) => event.project === project && occursOnDate(event, date)); }
export function requiresIntroductionDetails(event = {}) { return event.project === 'produktionsschule' && event.introductionRequired === true; }
export function formatEventDuration(event) {
const start = parseDateTime(event.startsAt);
const end = parseDateTime(event.endsAt);
const [startDate, endDate] = eventDateRange(event);
if (startDate !== endDate) {
const dayCount = Math.round((parseDate(endDate) - parseDate(startDate)) / 86400000) + 1;
return `${dayCount} Tage`;
}
const hours = Math.round((end - start) / 3600000 * 10) / 10;
return `${String(hours).replace('.', ',')} ${hours === 1 ? 'Stunde' : 'Stunden'}`;
}
function formatEventTime(event) { return `${timeFormatter.format(parseDateTime(event.startsAt))}–${timeFormatter.format(parseDateTime(event.endsAt))} Uhr`; }
function formatEventFormat(event) { return event.format === 'telefonisch' ? 'Telefonisch' : 'Vor Ort'; }
export function validateBookingField(fieldName, value) {
const text = typeof value === 'string' ? value.trim() : '';
if (fieldName === 'name') return text && text.length <= 160 ? '' : 'Bitte geben Sie Ihren Namen ein.';
if (fieldName === 'email') return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text) && text.length <= 254 ? '' : 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
if (fieldName === 'phone') return /^[0-9+()\-/\s]{6,64}$/.test(text) ? '' : 'Bitte geben Sie eine gültige Telefonnummer ein.';
if (fieldName === 'introductionAttended') return value ? '' : 'Bitte bestätigen Sie die Teilnahme an einer Einführungsveranstaltung.';
if (fieldName === 'introductionDate') return /^\d{4}-\d{2}-\d{2}$/.test(text) ? '' : 'Bitte geben Sie das Datum der Einführungsveranstaltung ein.';
if (fieldName === 'privacy') return value ? '' : 'Bitte bestätigen Sie die Datenschutzhinweise.';
return '';
}
export function validateBookingForm({ name = '', email = '', phone = '', privacyAccepted = false, introductionAttended = false, introductionDate = '', event = {} }) {
const values = { name, email, phone, privacy: privacyAccepted };
if (requiresIntroductionDetails(event)) Object.assign(values, { introductionAttended, introductionDate });
return Object.fromEntries(Object.entries(values).map(([fieldName, value]) => [fieldName, validateBookingField(fieldName, value)]).filter(([, error]) => error));
}
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' })[character]); }
function createMonthDates(month) {
const first = new Date(month.getFullYear(), month.getMonth(), 1);
const dates = new Array((first.getDay() + 6) % 7).fill(null);
const lastDay = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
for (let day = 1; day <= lastDay; day += 1) dates.push(new Date(month.getFullYear(), month.getMonth(), day));
return dates;
}
function loadSessionProfile() {
try { const profile = JSON.parse(sessionStorage.getItem(sessionProfileKey) ?? '{}'); return typeof profile === 'object' && profile ? profile : {}; } catch { return {}; }
}
function saveSessionProfile(profile) { try { sessionStorage.setItem(sessionProfileKey, JSON.stringify(profile)); } catch { /* Speicherung ist optional. */ } }
function showFieldError(form, fieldName, error) {
const field = form.elements.namedItem(fieldName);
if (!field) return;
const errorId = `sufw-booking-${fieldName}-error`;
let message = form.querySelector(`#${errorId}`);
if (!message) {
message = document.createElement('span');
message.id = errorId;
message.className = 'sufw-booking__field-error';
message.setAttribute('role', 'alert');
const host = fieldName === 'privacy' || fieldName === 'introductionAttended' ? field.closest('label') : field;
host.insertAdjacentElement('afterend', message);
field.setAttribute('aria-describedby', errorId);
}
message.textContent = error;
message.hidden = !error;
field.setAttribute('aria-invalid', error ? 'true' : 'false');
}
function openConfirmationDialog(container, event) {
const dialog = document.createElement('dialog');
dialog.className = 'sufw-booking__dialog';
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">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.addEventListener('close', () => dialog.remove());
container.append(dialog);
if (typeof dialog.showModal === 'function') dialog.showModal(); else { dialog.setAttribute('open', ''); dialog.querySelector('[data-close-confirmation]').focus(); }
}
function openBookingDialog(container, event, state) {
const profile = loadSessionProfile();
const requiresIntroduction = requiresIntroductionDetails(event);
const dialog = document.createElement('dialog');
dialog.className = 'sufw-booking__dialog';
dialog.setAttribute('aria-labelledby', 'sufw-booking-form-title');
dialog.innerHTML = `<form class="sufw-booking__form" novalidate><header class="sufw-booking__form-header"><p class="sufw-booking__eyebrow">Termin verbindlich anmelden</p><h2 id="sufw-booking-form-title">Ihre Angaben</h2><p class="sufw-booking__appointment"><strong>${escapeHtml(event.title)}</strong><br>${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(formatEventDuration(event))} · ${escapeHtml(formatEventFormat(event))}</p></header><p class="sufw-booking__required"><span aria-hidden="true">*</span> Pflichtfeld</p><p class="sufw-booking__form-errors" role="alert" hidden></p><div class="sufw-booking__form-grid"><label>Vor- und Nachname <span aria-hidden="true">*</span><input name="name" type="text" autocomplete="name" maxlength="160" required value="${escapeHtml(profile.name ?? '')}"></label><label>E-Mail-Adresse <span aria-hidden="true">*</span><input name="email" type="email" autocomplete="email" maxlength="254" required value="${escapeHtml(profile.email ?? '')}"></label><label>Telefonnummer <span aria-hidden="true">*</span><input name="phone" type="tel" autocomplete="tel" maxlength="64" required value="${escapeHtml(profile.phone ?? '')}"></label></div>${requiresIntroduction ? '<fieldset class="sufw-booking__conditional"><legend>Voraussetzung für Probearbeiten</legend><label class="sufw-booking__consent"><input name="introductionAttended" type="checkbox" value="accepted"><span>Ich habe an einer Einführungsveranstaltung teilgenommen. <span aria-hidden="true">*</span></span></label><label>Datum der Einführungsveranstaltung <span aria-hidden="true">*</span><input name="introductionDate" type="date"></label></fieldset>' : ''}<label class="sufw-booking__consent"><input name="privacy" type="checkbox" value="accepted" required><span>Ich habe die Datenschutzhinweise nach Art. 13 DSGVO gelesen und stimme der Verarbeitung meiner Angaben zur Terminplanung zu. <span aria-hidden="true">*</span></span></label><div class="sufw-booking__form-actions"><button type="button" class="sufw-booking__secondary" data-close-dialog>Abbrechen</button><button type="submit" data-submit-booking disabled>Verbindlich anmelden</button></div></form>`;
const form = dialog.querySelector('form');
const submitButton = dialog.querySelector('[data-submit-booking]');
const privacy = form.elements.namedItem('privacy');
const fieldNames = ['name', 'email', 'phone', 'privacy', ...(requiresIntroduction ? ['introductionAttended', 'introductionDate'] : [])];
const formError = form.querySelector('.sufw-booking__form-errors');
const validateField = (fieldName) => {
const field = form.elements.namedItem(fieldName);
const value = fieldName === 'privacy' || fieldName === 'introductionAttended' ? field.checked : field.value;
const error = validateBookingField(fieldName, value);
showFieldError(form, fieldName, error);
return error;
};
fieldNames.forEach((fieldName) => {
const field = form.elements.namedItem(fieldName);
field.addEventListener(field.type === 'checkbox' ? 'change' : 'input', () => validateField(fieldName));
if (field.type !== 'checkbox') field.addEventListener('blur', () => validateField(fieldName));
});
privacy.addEventListener('change', () => { submitButton.disabled = !canSubmitBookingForm(privacy.checked); });
form.addEventListener('submit', async (submitEvent) => {
submitEvent.preventDefault();
const values = Object.fromEntries(new FormData(form).entries());
const booking = { name: values.name ?? '', email: values.email ?? '', phone: values.phone ?? '', privacyAccepted: privacy.checked, introductionAttended: form.elements.namedItem('introductionAttended')?.checked ?? false, introductionDate: values.introductionDate ?? '', event };
const errors = validateBookingForm(booking);
fieldNames.forEach((fieldName) => showFieldError(form, fieldName, errors[fieldName] ?? ''));
if (Object.keys(errors).length) { form.elements.namedItem(Object.keys(errors)[0]).focus(); return; }
submitButton.disabled = true;
formError.hidden = true;
try {
const response = await fetch(state.apiUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-SUFW-Booking-CSRF': state.csrfToken }, body: JSON.stringify({ project: event.project, eventId: event.id, name: booking.name, email: booking.email, phone: booking.phone, privacyAccepted: true, introductionAttended: booking.introductionAttended, introductionDate: booking.introductionDate }) });
const result = await response.json();
if (!response.ok) throw new Error(result.error ?? 'Die Anmeldung konnte nicht gespeichert werden.');
saveSessionProfile({ name: booking.name, email: booking.email, phone: booking.phone });
dialog.close();
await state.reload();
openConfirmationDialog(container, event);
} catch (error) {
formError.textContent = error instanceof Error ? error.message : 'Die Anmeldung konnte nicht gespeichert werden.';
formError.hidden = false;
submitButton.disabled = false;
}
});
dialog.querySelector('[data-close-dialog]').addEventListener('click', () => dialog.close());
dialog.addEventListener('close', () => dialog.remove());
container.append(dialog);
if (typeof dialog.showModal === 'function') dialog.showModal(); else { dialog.setAttribute('open', ''); form.elements.namedItem('name').focus(); }
}
function renderComponent(container) {
const project = container.dataset.project === 'produktionsschule' ? 'produktionsschule' : 'perspektivwerk';
const now = new Date();
const state = { apiUrl: container.dataset.apiUrl || 'booking/api.php', csrfToken: '', events: [], currentMonth: new Date(now.getFullYear(), now.getMonth(), 1), selectedDate: '' };
const fetchEvents = async () => {
const from = formatDateKey(state.currentMonth);
const to = formatDateKey(new Date(state.currentMonth.getFullYear(), state.currentMonth.getMonth() + 1, 1));
const response = await fetch(`${state.apiUrl}?${new URLSearchParams({ project, from, to })}`, { credentials: 'same-origin' });
const result = await response.json();
if (!response.ok) throw new Error(result.error ?? 'Der Kalender konnte nicht geladen werden.');
state.events = result.events;
state.csrfToken = result.csrfToken;
if (!state.selectedDate && state.events.length) state.selectedDate = state.events[0].startsAt.slice(0, 10);
};
const render = () => {
const slots = state.selectedDate ? getSlotsForDate(project, state.selectedDate, state.events) : [];
const selectedLabel = state.selectedDate ? dateFormatter.format(parseDate(state.selectedDate)) : 'einen Tag';
container.innerHTML = `<section class="sufw-booking" aria-labelledby="sufw-booking-title"><header class="sufw-booking__header"><p class="sufw-booking__eyebrow">Terminbuchung</p><h2 id="sufw-booking-title">${project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule'}</h2><p>Wählen Sie einen Tag. Termine zeigen Dauer, Format und freie Plätze.</p></header><div class="sufw-booking__legend" aria-label="Legende"><span><i class="sufw-booking__marker sufw-booking__marker--available"></i> Buchbar</span><span><i class="sufw-booking__marker sufw-booking__marker--booked"></i> Ausgebucht</span></div><div class="sufw-booking__month-nav"><button class="sufw-booking__nav" type="button" data-action="previous" aria-label="Vorheriger Monat">‹</button><h3 aria-live="polite">${monthFormatter.format(state.currentMonth)}</h3><button class="sufw-booking__nav" type="button" data-action="next" aria-label="Nächster Monat">›</button></div><div class="sufw-booking__weekdays" aria-hidden="true">${weekdays.map((weekday) => `<span>${weekday}</span>`).join('')}</div><div class="sufw-booking__calendar" role="grid" aria-label="Kalender ${monthFormatter.format(state.currentMonth)}">${createMonthDates(state.currentMonth).map((date) => {
if (!date) return '<span class="sufw-booking__empty" aria-hidden="true"></span>';
const key = formatDateKey(date); const daySlots = getSlotsForDate(project, key, state.events); const available = daySlots.some((event) => event.status === 'available'); const full = daySlots.length > 0 && !available; const selected = key === state.selectedDate;
const label = daySlots.length ? `${dateFormatter.format(date)}: ${available ? 'Termine buchbar' : 'Termine ausgebucht'}` : dateFormatter.format(date);
return `<button type="button" role="gridcell" class="sufw-booking__day sufw-booking__day--${available ? 'available' : full ? 'booked' : 'none'}${selected ? ' is-selected' : ''}" data-date="${key}" aria-pressed="${selected}" aria-label="${escapeHtml(label)}"><time datetime="${key}">${date.getDate()}</time>${daySlots.length ? `<small>${available ? 'freie Plätze' : 'ausgebucht'}</small>` : ''}</button>`;
}).join('')}</div><section class="sufw-booking__slots" aria-labelledby="sufw-slot-title"><h3 id="sufw-slot-title">Termine am ${escapeHtml(selectedLabel)}</h3>${slots.length ? `<ul>${slots.map((event) => `<li><button type="button" class="sufw-booking__slot" data-event-id="${event.id}" ${event.status === 'full' ? 'disabled aria-disabled="true"' : ''}><strong>${escapeHtml(formatEventTime(event))}</strong><span>${escapeHtml(event.title)}<small>${escapeHtml(formatEventDuration(event))} · ${escapeHtml(formatEventFormat(event))}</small></span><em>${event.status === 'available' ? `${event.availableCapacity} ${event.availableCapacity === 1 ? 'Platz frei' : 'Plätze frei'}` : 'Ausgebucht'}</em></button></li>`).join('')}</ul>` : '<p class="sufw-booking__empty-state">Für diesen Tag liegen keine Termine vor.</p>'}<p class="sufw-booking__status" role="status" aria-live="polite"></p></section></section>`;
container.querySelector('[data-action="previous"]').addEventListener('click', async () => { state.currentMonth = new Date(state.currentMonth.getFullYear(), state.currentMonth.getMonth() - 1, 1); state.selectedDate = ''; await loadAndRender(); });
container.querySelector('[data-action="next"]').addEventListener('click', async () => { state.currentMonth = new Date(state.currentMonth.getFullYear(), state.currentMonth.getMonth() + 1, 1); state.selectedDate = ''; await loadAndRender(); });
container.querySelectorAll('[data-date]').forEach((button) => button.addEventListener('click', () => { state.selectedDate = button.dataset.date ?? ''; render(); }));
container.querySelectorAll('[data-event-id]').forEach((button) => button.addEventListener('click', () => { const event = state.events.find((entry) => entry.id === button.dataset.eventId); if (event) openBookingDialog(container, event, state); }));
};
const loadAndRender = async () => {
container.setAttribute('aria-busy', 'true');
try { await fetchEvents(); render(); }
catch (error) { container.innerHTML = `<p class="sufw-booking__load-error" role="alert">${escapeHtml(error instanceof Error ? error.message : 'Der Kalender konnte nicht geladen werden.')}</p>`; }
finally { container.removeAttribute('aria-busy'); }
};
state.reload = loadAndRender;
loadAndRender();
}
export function initializeBookingComponents(root = document) { root.querySelectorAll('[data-sufw-booking]').forEach(renderComponent); }
if (typeof document !== 'undefined') { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => initializeBookingComponents()); else initializeBookingComponents(); }
@@ -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=\"../\">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";