Compare commits

...
Author SHA1 Message Date
LarsandClaude Sonnet 5.5 edfe743d7d Lege fehlende Vorschau-Fassungen beim ersten Abruf über die Warteschlange an
CI Feature / test (push) Successful in 5m47s
Deploy Test / test (push) Successful in 7m2s
Deploy Test / deploy (push) Successful in 40s
Die Verwaltungsrouten lieferten bei fehlender Fassung nur die volle Datei und
stießen nichts an; Bestand blieb dadurch ohne kleine Fassungen. Jetzt legt der
erste Abruf (höchstens einmal je Tag und Bild) einen Auftrag an.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 09:55:26 +01:00
LarsandClaude Sonnet 5.5 63b42b366c Lege Bildfassungen an und liefere sie zwischengespeichert aus (ADR-63)
CI Feature / test (push) Successful in 6m26s
Deploy Test / test (push) Successful in 5m14s
Deploy Test / deploy (push) Successful in 31s
Vorschaubilder entstehen zusätzlich als klein (360 px) und mittel (960 px),
Website-Bilder in den Breiten 640, 1280 und 1920. Auswahl, Listen und Karten
laden die kleinen Fassungen; die Website nutzt srcset. Adressen tragen Größe und
Version und werden dauerhaft zwischengespeichert (ETag, 304). Die Website-Route
läuft ohne Sitzung und Cookies. Bestand füllt sich über die Warteschlange oder
mit media:varianten. Die Optionsliste des CMS fragt nicht mehr je Eintrag ab.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 09:37:00 +01:00
LarsandClaude Sonnet 5.5 0492133201 Benenne die Widget-Einstellungen eindeutig: Mehrstufig und Pop-up-Fenster statt zweimal Dialog
CI Feature / test (push) Successful in 6m1s
Deploy Test / test (push) Successful in 6m24s
Deploy Test / deploy (push) Successful in 39s
Formularführung (Aufbau des Formulars) und Präsentation (Ort des Formulars) sind getrennte Einstellungen. Die Bezeichnung
"Mehrstufiger Dialog" ließ erwarten, dass sie ein Pop-up öffnet. Neu: "Mehrstufig, Schritt für Schritt" und "Im Pop-up-Fenster
über der Seite"; die Hilfetexte verweisen aufeinander. Verhalten unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 08:40:28 +01:00
LarsandClaude Sonnet 5.5 23978d26da Belege die Formularansicht des Aufbaus mit Abnahme und Screenshots von luf-test
CI Feature / test (push) Successful in 5m31s
Deploy Test / test (push) Successful in 5m54s
Deploy Test / deploy (push) Successful in 54s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 08:24:50 +01:00
LarsandClaude Sonnet 5.5 41bf9a0220 Dokumentiere die Formularansicht des Aufbaus (ADR-62)
CI Feature / test (push) Successful in 4m21s
Deploy Test / test (push) Successful in 4m27s
Deploy Test / deploy (push) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 08:12:11 +01:00
LarsandClaude Sonnet 5.5 380a3013c7 Ersetze die Builder-Liste des Formular-Editors durch eine Formularansicht mit Ziehen und Ablegen
CI Feature / test (push) Successful in 4m18s
Der Aufbau eines Formulars zeigt Bereiche als Karten, Teilbereiche als eingerahmte Einheit darin und Felder als Zeilen
(Frage, Art der Antwort, Pflicht). Hilfetext, Auswahlwerte, Bedingung und weitere Einstellungen öffnen als Pop-up.
Bereiche, Teilbereiche und Felder lassen sich ziehen (SortableJS aus Filament) oder per Pfeiltasten und über
"Verschieben nach" ordnen; Rückgängig nimmt Änderungen bis zum Speichern zurück.

Der Browser führt den Baum und übergibt ihn beim Speichern als Text; FormEditor prüft ihn (validateTree) und überführt ihn
über fromTree in dieselbe flache Ansicht wie bisher. Entwurf, Katalog und Engine bleiben unverändert, keine Migration.

Tests: Die Livewire-Tests des Editors setzen jetzt den Baumtext (editor_json) statt der Builder-Blöcke; neu sind
Baumumwandlung ohne Verlust, Teilbereich mit Feldern, Prüfung und Konfiguration. Das ist bewusst: Der Builder entfällt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 08:08:39 +01:00
LarsandClaude Sonnet 5.5 79c4e877ab Belege den Formular-Editor und die Anfragegründe mit Abnahme und Screenshots von luf-test
CI Feature / test (push) Successful in 6m43s
Deploy Test / test (push) Successful in 6m19s
Deploy Test / deploy (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 23:18:20 +01:00
LarsandClaude Sonnet 5.5 5bc362d25c Dokumentiere den Formular-Editor und die Anfragegründe (ADR-61)
CI Feature / test (push) Successful in 6m46s
Deploy Test / test (push) Successful in 5m38s
Deploy Test / deploy (push) Successful in 29s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:57:16 +01:00
LarsandClaude Sonnet 5.5 374fd95576 Zeige das Widget Anfrage in der Vorschau des Seiteneditors und gib der Fassungsliste deutsche Texte
CI Feature / test (push) Successful in 5m32s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:55:40 +01:00
LarsandClaude Sonnet 5.5 2eca612108 Verbessere Karten der Grundauswahl und halte die Aktionen im Dialog erreichbar
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:43:28 +01:00
LarsandClaude Sonnet 5.5 7302ac78e9 Bearbeite ein Formular vollständig in einem Editor und reduziere die Navigation der Kommunikation
CI Feature / test (push) Successful in 4m17s
Der Editor zeigt Bereiche mit Feldern und Teilbereichen; Felder werden direkt im Bereich angelegt oder aus dem Katalog
übernommen und landen im selben Katalog wie bisher. Bedingungen stehen am Feld, Teilbereich oder Bereich und werden zu
denselben Regeln wie die Regelliste; alles andere bleibt unter „Weitere Regeln“. Navigation: Anfragen, Formulare &
Befragungen, Einstellungen. Anliegen, Feldkatalog, Feldgruppen und Einstiege bleiben erreichbar (Einstellungen).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:37:32 +01:00
LarsandClaude Sonnet 5.5 fb479c1b01 Liefere das Anfrageformular je Anfragegrund aus und gib dem Widget Gründe, Formularführung und Präsentation
Das Widget Anfrage wählt statt eines Anfrage-Einstiegs mehrere Anfragegründe, jeder zeigt auf ein veröffentlichtes Formular
(optional mit vorgewähltem Anliegen). Der Besucher erhält genau das Formular seines Grundes: /anfrage/formular/{vorlage}
mit Grund in der Adresse, dasselbe Token, dieselbe Auswertung und Annahme. Ein Dialog (dialog-Element) und die Grundauswahl
als Karten oder Auswahlfeld kommen aus resources/js/inquiry-widget.js. Seiten mit einem Einstieg bleiben darstellbar.
Bereiche lassen sich wie Gruppen anzeigen oder ausblenden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:29:31 +01:00
LarsandClaude Sonnet 5.5 f255bf5200 Belege die Kommunikationsverwaltung mit Abnahme und Screenshots von luf-test
CI Feature / test (push) Successful in 5m54s
Deploy Test / test (push) Successful in 4m54s
Deploy Test / deploy (push) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 18:37:20 +01:00
LarsandClaude Sonnet 5.5 b9407c2f98 Halte Seiten mit zurückgezogenem Einstieg speicherbar und berechne den Link der Benachrichtigung in der Web-Anfrage
CI Feature / test (push) Successful in 5m30s
Deploy Test / test (push) Successful in 5m17s
Deploy Test / deploy (push) Successful in 41s
Das Widget prüft nur noch, dass der Einstieg existiert; die Auswahl im Editor bietet weiter nur veröffentlichte
an. Der Worker kennt keine Anfrage und APP_URL ist unzuverlässig, daher gibt die Web-Anfrage die Adresse der Anfrage
in der Verwaltung an die Aufgabe weiter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 18:06:40 +01:00
LarsandClaude Sonnet 5.5 a495b0d740 Benenne den Feldkatalog, zeige Schrittnamen in Regeln und gliedere die Antworten im Posteingang
CI Feature / test (push) Successful in 4m9s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 18:03:45 +01:00
LarsandClaude Sonnet 5.5 22f8afdcd6 Ergänze Aufbewahrung, Dokumentation und den Vertrag der Widget-Registry für das Widget Anfrage
CI Feature / test (push) Successful in 4m41s
Der Registry-Test erlaubt bewusst Widgets, die nur aus einem Verweis bestehen (Anfrage: nur die Kennung eines
Einstiegs) und kennt die neue Widget-Art. ADR-60, Beschreibung der Kommunikationsverwaltung, Rückfall und
Migration in der Release-Vorbereitung. Der Browser meldet laufende Zustandsabfragen über aria-busy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:51:04 +01:00
LarsandClaude Sonnet 5.5 c6a8167601 Baue die Verwaltung Kommunikation, die öffentliche Anfrageschnittstelle und das CMS-Widget Anfrage
Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen mit Fassungen, Anfrage-Einstiege, Posteingang mit
Status und Notizen, Einstellungen mit Empfängern. Das Widget speichert nur die Kennung eines veröffentlichten
Einstiegs; Formular, Bedingungen und Annahme kommen zur Laufzeit vom Server (Kompaktformular und
mehrstufiger Dialog aus derselben Beschreibung).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:41:55 +01:00
LarsandClaude Sonnet 5.5 2ee1fc9866 Lege das Datenmodell und den Anfrageservice der Kommunikationsverwaltung an
Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen mit unveränderlichen Fassungen,
Anfrage-Einstiege und eingegangene Anfragen. Eine gemeinsame Regelauswertung bedient
Besucher, Vorschau und Anfrageservice; Werte nicht mehr relevanter Felder werden verworfen,
Anliegen und Auswahlwerte serverseitig geprüft, doppeltes Absenden bleibt eine Anfrage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:26:42 +01:00
201 changed files with 14344 additions and 85 deletions

No files matched your search

@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use App\Jobs\DeriveImageVariants;
use App\Jobs\DeriveWebsiteVariants;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
/**
* Legt für vorhandene Bilder die kleineren Fassungen an (docs/architektur/bildvarianten.md). Neue Bilder bekommen sie beim
* Ableiten; dieser Befehl holt den Bestand nach. Die Arbeit macht die Warteschlange (nur sie darf in derived/ und public/
* schreiben); mit --now läuft sie hier im Prozess, den man dafür im Queue-Container startet.
*/
class DeriveMediaVariants extends Command
{
protected $signature = 'media:varianten {--now : Sofort hier ausführen statt in die Warteschlange zu legen} {--pretend : Nur zählen}';
protected $description = 'Legt für vorhandene Vorschaubilder und freigegebene Website-Bilder die kleineren Fassungen an';
public function handle(): int
{
$derived = Storage::disk('media_derived');
$paths = [];
foreach ([ContentElement::query(), Composition::query()] as $query) {
$query->where('thumbnail_path', 'like', 'vorschau/%')
->pluck('thumbnail_path')
->each(function (mixed $path) use (&$paths): void {
if (is_string($path)) {
$paths[$path] = true;
}
});
}
$missing = array_values(array_filter(
array_keys($paths),
fn (string $path): bool => ! str_contains($path, '..')
&& ! $derived->exists(ImageVariants::path($path, 'klein'))
&& $derived->exists($path),
));
$websiteIds = ContentElement::query()
->where('output_class', 'bild')
->whereNotNull('website_released_at')
->whereNotNull('website_public_path')
->pluck('id')
->all();
$this->info(count($missing).' Vorschaubilder ohne Fassungen, '.count($websiteIds).' freigegebene Website-Bilder.');
if ($this->option('pretend')) {
return self::SUCCESS;
}
foreach ($missing as $path) {
$this->option('now') ? DeriveImageVariants::dispatchSync($path) : DeriveImageVariants::dispatch($path);
}
foreach ($websiteIds as $id) {
$this->option('now') ? DeriveWebsiteVariants::dispatchSync((int) $id) : DeriveWebsiteVariants::dispatch((int) $id);
}
$this->info($this->option('now') ? 'Fassungen angelegt.' : 'In die Warteschlange gelegt.');
return self::SUCCESS;
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Console\Commands;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\Inquiry;
use Illuminate\Console\Command;
/**
* Löscht Anfragen, die älter sind als die in „Kommunikation → Einstellungen“ gewählte Aufbewahrungsdauer. Ohne
* Aufbewahrungsdauer geschieht nichts. Mit --pretend wird nur gezählt.
*/
class PurgeInquiries extends Command
{
protected $signature = 'communication:purge {--pretend : Nur zählen, nichts löschen}';
protected $description = 'Löscht Anfragen nach Ablauf der Aufbewahrungsdauer (Einstellungen der Kommunikationsverwaltung)';
public function handle(): int
{
$months = CommunicationSettings::current()->retention_months;
if ($months === null || $months < 1) {
$this->info('Keine Aufbewahrungsdauer eingestellt; es wird nichts gelöscht.');
return self::SUCCESS;
}
$query = Inquiry::query()->where('created_at', '<', now()->subMonths($months));
$count = $query->count();
if ($this->option('pretend')) {
$this->info("$count Anfragen wären älter als $months Monate.");
return self::SUCCESS;
}
$query->delete();
$this->info("$count Anfragen gelöscht (älter als $months Monate).");
return self::SUCCESS;
}
}
+2 -2
View File
@@ -49,7 +49,7 @@ public function rows(Model $subject): array
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
@@ -134,7 +134,7 @@ public function describe(array $staged): array
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
+1 -1
View File
@@ -104,7 +104,7 @@ public static function previewUrl(?string $target): ?string
return route('website.media', $element);
}
return app(EditorialCatalog::class)->cardUrl('element', $element->id, $element->thumbnail_path);
return app(EditorialCatalog::class)->cardUrl('element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
/**
@@ -319,7 +319,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
notice: $notice,
visual: 'catalog',
visualLabel: $kind,
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at) : null,
missing: $missing,
texts: $texts,
);
@@ -221,7 +221,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
$missing[] = 'Kein Anzeigetitel gepflegt; die Karte zeigt den Arbeitstitel.';
}
$previewImage = $includeNonPublic ? ThumbnailRef::url('editorial.card', 'element', (int) $element->id, $shown->thumbnail_path) : null;
$previewImage = $includeNonPublic ? ThumbnailRef::url('editorial.card', 'element', (int) $element->id, $shown->thumbnail_path, 'mittel', $shown->updated_at) : null;
return new CardSubject(
title: $title,
+1 -1
View File
@@ -115,7 +115,7 @@ private function renderSection(array $section, array $cells, int $index, RenderC
$style = SectionStyle::fromStored($section['style'] ?? []);
$columns = SectionLayouts::columns(array_column($cells, 'units'));
// Hintergrundbild aus dem Medienmanager: öffentlich nur mit Website-Freigabe (WebsiteImage → WebsiteMedia).
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview) : null;
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview, 1920) : null;
$hasImage = $imageUrl !== null;
$classes = [
+22 -13
View File
@@ -86,7 +86,7 @@ public function elementId(mixed $value): ?int
return is_int($id) ? $id : null;
}
public function presentation(mixed $value): ?WebsitePresentation
public function presentation(mixed $value, ?ContentElement $loaded = null): ?WebsitePresentation
{
$id = $this->elementId($value);
@@ -95,7 +95,8 @@ public function presentation(mixed $value): ?WebsitePresentation
}
if (! array_key_exists($id, $this->presentations)) {
$this->presentations[$id] = $this->media->present($id) ?? false;
// Ein schon geladenes Medium wird weitergereicht (kein zweiter Zugriff je Eintrag in der Auswahl).
$this->presentations[$id] = $this->media->present($loaded?->getKey() === $id ? $loaded : $id) ?? false;
}
return $this->presentations[$id] ?: null;
@@ -105,12 +106,12 @@ public function presentation(mixed $value): ?WebsitePresentation
* Bildadresse für die Darstellung. Öffentlich nur freigegebene Medien (oder frühere CMS-Bilder ohne Zuordnung);
* in der Redaktionsvorschau zusätzlich das Vorschaubild eines nicht freigegebenen Mediums.
*/
public function url(mixed $value, bool $preview = false): ?string
public function url(mixed $value, bool $preview = false, ?int $width = null): ?string
{
$presentation = $this->presentation($value);
if ($presentation !== null) {
return $presentation->kind === 'bild' ? $presentation->url : null;
return $presentation->kind === 'bild' ? $presentation->urlForWidth($width) : null;
}
$id = $this->elementId($value);
@@ -122,7 +123,7 @@ public function url(mixed $value, bool $preview = false): ?string
$element = ContentElement::query()->find($id);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
$legacy = self::normalize($value);
@@ -134,6 +135,14 @@ public function url(mixed $value, bool $preview = false): ?string
return is_string($legacy) ? PublicMedia::url($legacy) : null;
}
/** `srcset` des freigegebenen Bildes (mehrere Breiten), sonst null. Für Hero, Bild mit Text, Karten. */
public function srcset(mixed $value): ?string
{
$presentation = $this->presentation($value);
return $presentation !== null && $presentation->kind === 'bild' ? $presentation->srcset : null;
}
/** Alternativtext: Angabe im Widget, sonst der Alternativtext des Mediums. */
public function alt(mixed $value, mixed $override = null): string
{
@@ -169,7 +178,7 @@ public function previewNotice(mixed $value, string $label = 'Das gewählte Bild'
*
* @return array{public: bool, state: string, title: string, note: string, thumb: ?string, manageUrl: ?string}|null
*/
public function status(mixed $value): ?array
public function status(mixed $value, ?ContentElement $loaded = null): ?array
{
$value = self::normalize($value);
@@ -194,16 +203,16 @@ public function status(mixed $value): ?array
];
}
$element = ContentElement::query()->with('editorialContentKind')->find($id);
$element = $loaded?->getKey() === $id ? $loaded : ContentElement::query()->with('editorialContentKind')->find($id);
if ($element === null) {
return ['public' => false, 'state' => 'missing', 'title' => 'Medium '.$id, 'note' => 'Das Medium gibt es nicht mehr.', 'thumb' => null, 'manageUrl' => null];
}
$title = (string) ($element->display_title ?: $element->working_title);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
$manageUrl = ContentElementResource::getUrl('view', ['record' => $element]);
$public = $this->presentation($id) !== null;
$public = $this->presentation($id, $element) !== null;
$note = match (true) {
$public => 'Für die Website freigegeben.',
@@ -292,7 +301,7 @@ public function options(?string $search = null, int $limit = 60): array
$options = [];
foreach ($elements as $element) {
if (self::isSelectable($element)) {
$options[$element->id] = $this->optionHtml($element->id);
$options[$element->id] = $this->optionHtml($element->id, $element);
}
}
@@ -300,9 +309,9 @@ public function options(?string $search = null, int $limit = 60): array
}
/** HTML-Bezeichnung einer Option oder des gewählten Werts (auch für frühere Pfade). */
public function optionHtml(mixed $value): ?string
public function optionHtml(mixed $value, ?ContentElement $loaded = null): ?string
{
$status = $this->status($value);
$status = $this->status($value, $loaded);
if ($status === null) {
return null;
@@ -315,7 +324,7 @@ public function optionHtml(mixed $value): ?string
default => ['warn', 'Website: nicht freigegeben'],
};
$thumb = $status['thumb'] !== null
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy">'
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy" decoding="async">'
: '<span class="luf-media-option-empty" aria-hidden="true"></span>';
return '<span class="luf-media-option">'.$thumb
@@ -302,6 +302,7 @@ public function resolve(array $widget, RenderContext $context): array
'linkLabel' => filled($item['link_label'] ?? null) ? $item['link_label'] : self::DEFAULT_LINK_LABEL,
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
'imageSrcset' => $images->srcset($item['image'] ?? null),
];
if ($context->preview && ($notice = $images->previewNotice($item['image'] ?? null, 'Das Bild der Karte „'.$item['title'].'“')) !== null) {
@@ -250,6 +250,7 @@ public function resolve(array $widget, RenderContext $context): array
return [
'video' => $video,
'imageUrl' => $images->url($image, $context->preview),
'imageSrcset' => $images->srcset($image),
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'actions' => $actions,
@@ -329,6 +329,7 @@ public function resolve(array $widget, RenderContext $context): array
return [
'imageUrl' => $imageUrl,
'imageSrcset' => $imageUrl === null ? null : $images->srcset($image),
'imageAlt' => $imageAlt,
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'video' => $video,
@@ -0,0 +1,352 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Validation\Rule;
/**
* Kontakt-Widget (ADR-60, ADR-61). Der Redakteur legt fest, welche Anfragegründe auf der Seite angeboten werden und
* welches veröffentlichte Formular jeder Grund öffnet; Formularführung (Langformular oder mehrstufig) und Darstellung
* (im Abschnitt oder als Dialog) sind zwei getrennte Einstellungen. Der Besucher wählt einen Grund und erhält genau das
* zugehörige Formular. Felder, Bedingungen, Texte und Empfänger gibt es im CMS nicht: Sie werden im Formular-Editor der
* Kommunikationsverwaltung gepflegt und gelten sofort auf allen Seiten.
*
* Seiten aus der ersten Fassung (ein Anfrage-Einstieg unter refs.entry) werden weiter dargestellt.
*/
class InquiryWidget extends WidgetType
{
public const MAX_REASONS = 8;
public function key(): string
{
return 'inquiry';
}
public function label(): string
{
return 'Anfrage';
}
public function description(): string
{
return 'Kontaktformular mit Auswahl des Anfragegrundes: Der Besucher wählt, worum es geht, und erhält genau das passende Formular.';
}
public function icon(): string
{
return 'heroicon-o-envelope';
}
public function supportedUnits(): array
{
return [3, 4];
}
public function preferredUnits(): int
{
return 4;
}
public function narrowBehavior(): string
{
return 'Das Formular nutzt die Breite des Platzes; Felder stehen untereinander, Karten der Grundauswahl stapeln, der Dialog füllt auf dem Smartphone den Bildschirm.';
}
public function stages(): array
{
return ['fluid' => 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art und Karten stehen bei viel Platz nebeneinander'];
}
public function schematic(): array
{
return [[6, 4, 24, 3, 'ink'], [6, 10, 22, 6, 'line'], [32, 10, 22, 6, 'line'], [6, 20, 48, 5, 'line'], [6, 28, 18, 5, 'accent']];
}
/**
* Formularführung und Präsentation sind unabhängig: Jede Kombination ist zulässig.
*
* @return array<string, array<string, string>>
*/
public function settings(): array
{
return [
'mode' => ['compact' => 'Langes Formular', 'wizard' => 'Mehrstufig, Schritt für Schritt'],
'open' => ['inline' => 'Im Abschnitt', 'modal' => 'Im Pop-up-Fenster über der Seite'],
'picker' => ['cards' => 'Karten', 'select' => 'Auswahlfeld'],
'width' => ['normal' => 'Standard', 'narrow' => 'Schmal', 'wide' => 'Breit'],
'spacing' => ['normal' => 'Standard', 'compact' => 'Kompakt', 'airy' => 'Großzügig'],
'columns' => ['auto' => 'Automatisch', 'one' => 'Immer eine Spalte'],
'button' => ['solid' => 'Gefüllt', 'outline' => 'Umrandet'],
];
}
public function settingLabels(): array
{
return [
'mode' => ['Formularführung', 'Wie das Formular aufgebaut ist, nicht wo es steht. Langes Formular: alle Bereiche stehen untereinander, bedingte Felder erscheinen je nach Eingabe. Mehrstufig: die Bereiche werden Schritt für Schritt mit Fortschrittsanzeige durchlaufen. Ob das Formular im Abschnitt oder in einem Pop-up-Fenster erscheint, legt „Präsentation“ fest. Vorgabe: Langes Formular.'],
'open' => ['Präsentation', 'Wo das Formular erscheint, unabhängig von „Formularführung“. Im Abschnitt: das Formular steht direkt auf der Seite. Im Pop-up-Fenster: ein Button öffnet das Formular in einem Fenster über der Seite; auf dem Smartphone füllt es den Bildschirm. Vorgabe: Im Abschnitt.'],
'picker' => ['Auswahl des Anfragegrundes', 'Karten zeigen die Gründe mit Beschreibung nebeneinander, das Auswahlfeld braucht wenig Platz. Bei nur einem Grund entfällt die Auswahl. Vorgabe: Karten.'],
'width' => ['Breite des Formulars', 'Vorgabe: Standard. Das Formular nutzt höchstens die Breite des Platzes.'],
'spacing' => ['Abstände', 'Abstand zwischen den Feldern. Vorgabe: Standard.'],
'columns' => ['Anordnung der Felder', 'Automatisch: Felder gleicher Art (zum Beispiel Vor- und Nachname) stehen bei viel Platz nebeneinander. Vorgabe: Automatisch.'],
'button' => ['Buttondarstellung', 'Gilt für den Button, der das Pop-up-Fenster öffnet, und für „Weiter“ und „Absenden“. Vorgabe: Gefüllt.'],
];
}
public function settingGroups(): array
{
return [
'Formularführung und Präsentation' => ['mode', 'open'],
'Gestaltung' => ['picker', 'width', 'spacing', 'columns', 'button'],
];
}
public function dataRules(): array
{
return [
// Nur die Existenz: Eine später zurückgezogene Vorlage darf eine Seite nicht unspeicherbar machen. Öffentlich
// erscheint ein Grund nur, solange sein Formular veröffentlicht ist (resolve()).
'reasons' => ['nullable', 'array', 'max:'.self::MAX_REASONS],
'reasons.*.key' => ['nullable', 'string', 'max:60'],
'reasons.*.label' => ['required', 'string', 'max:80'],
'reasons.*.description' => ['nullable', 'string', 'max:200'],
'reasons.*.template' => ['required', 'integer', Rule::exists('inquiry_templates', 'id')],
'reasons.*.issue' => ['nullable', 'string', 'max:60'],
'reasons.*.subissue' => ['nullable', 'string', 'max:60'],
'question' => ['nullable', 'string', 'max:160'],
'open_label' => ['nullable', 'string', 'max:60'],
];
}
public function dataFields(): array
{
return [
Repeater::make('reasons')
->label('Anfragegründe')
->helperText('Diese Gründe bietet die Seite an. Wählt der Besucher einen Grund, erscheint genau das zugeordnete Formular. Bei nur einem Grund entfällt die Auswahl. Ein Button kann einen Grund vorwählen: Adresse der Seite mit „?grund=Kennung“ (die Kennung steht unter dem Grund).')
->schema([
Hidden::make('key'),
TextInput::make('label')->label('Bezeichnung für Besucher')->required()->maxLength(80)->placeholder('Zum Beispiel: Kurse & Workshops'),
Textarea::make('description')->label('Kurzbeschreibung (optional)')->rows(2)->maxLength(200)->helperText('Erscheint auf der Karte unter der Bezeichnung.'),
Select::make('template')->label('Formular')->required()->searchable()->live()
->options(fn (): array => self::templateOptions())
->afterStateUpdated(function (Set $set): void {
$set('issue', null);
$set('subissue', null);
})
->helperText('Nur veröffentlichte Formulare stehen zur Auswahl. Inhalt, Felder und Bedingungen pflegst du unter „Kommunikation → Formulare & Befragungen“.'),
Select::make('issue')->label('Anliegen im Formular vorwählen (optional)')->live()
->options(fn (Get $get): array => self::issueOptions((int) $get('template')))
->placeholder('Keines: das Formular fragt selbst')
->visible(fn (Get $get): bool => self::issueOptions((int) $get('template')) !== [])
->afterStateUpdated(fn (Set $set) => $set('subissue', null))
->helperText('Mehrere Gründe können dasselbe Formular nutzen und sich im Anliegen unterscheiden. Die Frage nach dem Anliegen entfällt dann.'),
Select::make('subissue')->label('Unteranliegen vorwählen (optional)')
->options(fn (Get $get): array => self::subissueOptions((int) $get('template'), (string) $get('issue')))
->placeholder('Keines')
->visible(fn (Get $get): bool => filled($get('issue')) && self::subissueOptions((int) $get('template'), (string) $get('issue')) !== []),
Text::make(fn (Get $get): string => filled($get('key')) ? 'Kennung für Links: grund='.$get('key') : 'Die Kennung für Links entsteht beim Speichern.'),
])
->minItems(1)
->maxItems(self::MAX_REASONS)
->reorderableWithButtons()
->collapsible()
->addActionLabel('Anfragegrund hinzufügen')
->itemLabel(fn (array $state): ?string => $state['label'] ?? null),
TextInput::make('question')->label('Frage zur Auswahl des Grundes')->maxLength(160)->placeholder('Worum geht es?')
->helperText('Steht über der Auswahl, wenn mehr als ein Grund angeboten wird. Leer: „Worum geht es?“.'),
TextInput::make('open_label')->label('Beschriftung des Buttons (nur Pop-up-Fenster)')->maxLength(60)->placeholder('Anfrage stellen')
->helperText('Erscheint nur bei der Präsentation „Im Pop-up-Fenster über der Seite“.'),
];
}
public function refRules(): array
{
return [
// Nur die Existenz (Seiten der ersten Fassung): Ein später zurückgezogener Einstieg darf eine Seite nicht unspeicherbar machen.
'entry' => ['nullable', 'integer', Rule::exists('inquiry_entries', 'id')],
];
}
public function refFields(): array
{
return [
Select::make('entry')
->label('Bisheriger Anfrage-Einstieg')
->searchable()
->options(fn (): array => InquiryEntry::query()->orderBy('name')->pluck('name', 'id')->all())
->visible(fn (Get $get): bool => filled($get('entry')))
->helperText('Diese Seite nutzt noch einen Anfrage-Einstieg der ersten Fassung. Er wird nur angezeigt, solange oben kein Anfragegrund eingetragen ist. Neue Seiten brauchen keinen Einstieg.'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$reasons = [];
$taken = [];
foreach (array_values((array) ($data['reasons'] ?? [])) as $reason) {
$reason = is_array($reason) ? $reason : [];
$key = Keys::valid($reason['key'] ?? null) && ! in_array($reason['key'], $taken, true) ? $reason['key'] : Keys::from((string) ($reason['label'] ?? ''), $taken);
$taken[] = $key;
$reasons[] = [
'key' => $key,
'label' => trim((string) ($reason['label'] ?? '')),
'description' => filled($reason['description'] ?? null) ? trim((string) $reason['description']) : null,
'template' => (int) ($reason['template'] ?? 0),
'issue' => filled($reason['issue'] ?? null) ? (string) $reason['issue'] : null,
'subissue' => filled($reason['issue'] ?? null) && filled($reason['subissue'] ?? null) ? (string) $reason['subissue'] : null,
];
}
$data['reasons'] = $reasons;
if ($reasons === [] && ! filled($refs['entry'] ?? null)) {
$errors->add('data.reasons', 'Mindestens ein Anfragegrund ist nötig.');
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array'));
if ($reasons === []) {
$id = $widget['refs']['entry'] ?? null;
$entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null;
return ['legacy' => true, 'entry' => $entry, 'entryLive' => $entry?->isLive() ?? false, 'config' => null, 'unavailable' => []];
}
$templates = InquiryTemplate::query()->with('publishedVersion')->whereIn('id', array_unique(array_map(fn (array $r): int => (int) ($r['template'] ?? 0), $reasons)))->get()->keyBy('id');
$settings = (array) ($widget['settings'] ?? []);
$mode = ($settings['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact';
$live = [];
$unavailable = [];
foreach ($reasons as $reason) {
$template = $templates[(int) ($reason['template'] ?? 0)] ?? null;
$label = (string) ($reason['label'] ?? '');
if ($template === null || $template->archived_at !== null || $template->publishedVersion === null) {
$unavailable[] = $label;
continue;
}
$query = array_filter([
'anliegen' => $reason['issue'] ?? null,
'unteranliegen' => $reason['subissue'] ?? null,
'modus' => $mode,
], fn (mixed $value): bool => filled($value));
$suffix = '?'.http_build_query($query);
$live[] = [
'key' => (string) ($reason['key'] ?? ''),
'label' => $label,
'description' => $reason['description'] ?? null,
'definitionUrl' => route('inquiry.form.definition', $template).$suffix,
'stateUrl' => route('inquiry.form.state', $template).$suffix,
'submitUrl' => route('inquiry.form.submit', $template).$suffix,
];
}
$config = $live === [] ? null : [
'open' => ($settings['open'] ?? 'inline') === 'modal' ? 'modal' : 'inline',
'picker' => ($settings['picker'] ?? 'cards') === 'select' ? 'select' : 'cards',
'question' => filled($widget['data']['question'] ?? null) ? (string) $widget['data']['question'] : 'Worum geht es?',
'openLabel' => filled($widget['data']['open_label'] ?? null) ? (string) $widget['data']['open_label'] : 'Anfrage stellen',
'preview' => $context->preview,
'reasons' => $live,
];
return ['legacy' => false, 'entry' => null, 'entryLive' => false, 'config' => $config, 'unavailable' => $unavailable];
}
public function summary(array $widget): string
{
$reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array'));
if ($reasons === []) {
$id = $widget['refs']['entry'] ?? null;
$name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null;
return $name !== null ? 'Anfrage: '.$name : 'Kein Anfragegrund gewählt';
}
$labels = array_map(fn (array $reason): string => (string) ($reason['label'] ?? ''), $reasons);
$mode = ($widget['settings']['mode'] ?? 'compact') === 'wizard' ? 'mehrstufig' : 'langes Formular';
$open = ($widget['settings']['open'] ?? 'inline') === 'modal' ? 'Pop-up' : 'im Abschnitt';
return 'Anfrage: '.implode(', ', $labels).' ('.$mode.', '.$open.')';
}
/**
* @return array<int, string>
*/
private static function templateOptions(): array
{
return InquiryTemplate::query()->whereNotNull('published_version_id')->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all();
}
/**
* @return array<string, string>
*/
private static function issueOptions(int $templateId): array
{
$options = [];
foreach ((array) (self::definition($templateId)['issues'] ?? []) as $issue) {
$options[(string) $issue['key']] = (string) $issue['label'];
}
return $options;
}
/**
* @return array<string, string>
*/
private static function subissueOptions(int $templateId, string $issue): array
{
$options = [];
foreach ((array) (self::definition($templateId)['issues'] ?? []) as $top) {
if ($top['key'] !== $issue) {
continue;
}
foreach ((array) $top['children'] as $child) {
$options[(string) $child['key']] = (string) $child['label'];
}
}
return $options;
}
/**
* @return array<string, mixed>
*/
private static function definition(int $templateId): array
{
if ($templateId <= 0) {
return [];
}
return (array) (InquiryTemplate::query()->with('publishedVersion')->find($templateId)?->publishedVersion?->definition ?? []);
}
}
@@ -130,7 +130,7 @@ protected function filmFieldData(?ContentElement $film): array
? route('content.website-frame', ['element' => $film])
: null,
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path) : null,
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path, 'mittel', $film->updated_at) : null,
'filmStartSecond' => $film instanceof ContentElement ? ($stills->thumbnailSecond($film) ?? '0') : '0',
];
}
@@ -349,6 +349,7 @@ public function resolve(array $widget, RenderContext $context): array
'clip' => $clip,
'cardStyle' => $subject?->style ?? $this->cardStyle(),
'imageUrl' => app(WebsiteImage::class)->url($imageRef, $context->preview),
'imageSrcset' => app(WebsiteImage::class)->srcset($imageRef),
'alt' => app(WebsiteImage::class)->alt($imageRef, $data['alt'] ?? null),
'imageNotice' => $context->preview ? app(WebsiteImage::class)->previewNotice($imageRef, 'Das Kartenbild') : null,
'focus' => PremiumFields::focus($data, 66, 45),
@@ -65,7 +65,7 @@ protected function imageSourceFields(): array
'composition' => $composition,
'compositionTitle' => $composition instanceof Composition ? (string) ($composition->display_title ?: $composition->designation) : '',
'compositionThumbnailUrl' => $composition instanceof Composition && app(CompositionStill::class)->hasThumbnail($composition)
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at)
: null,
];
}),
@@ -0,0 +1,44 @@
<?php
namespace App\Domain\Communication;
use App\Domain\Identity\StaffRole;
use App\Models\User;
use Filament\Facades\Filament;
/**
* Wer die Kommunikationsverwaltung bedienen darf. Konfigurieren (Anliegen, Felder, Gruppen, Vorlagen, Einstiege):
* Redaktion und Systemverwaltung. Anfragen lesen und bearbeiten sowie Einstellungen: Kundenbetreuung und
* Systemverwaltung. Anfragen enthalten personenbezogene Daten und sind deshalb enger gefasst als die Konfiguration.
*/
final class CommunicationAccess
{
public static function user(): ?User
{
$user = Filament::auth()->user() ?? auth('staff')->user();
return $user instanceof User ? $user : null;
}
public static function configure(?User $user = null): bool
{
$user ??= self::user();
return $user !== null && ($user->hasStaffRole(StaffRole::Redakteur) || $user->hasStaffRole(StaffRole::Systemverwalter));
}
public static function inbox(?User $user = null): bool
{
$user ??= self::user();
return $user !== null && ($user->hasStaffRole(StaffRole::Kundenbetreuung) || $user->hasStaffRole(StaffRole::Systemverwalter));
}
/** Anfragen endgültig löschen (Datenschutz): nur Systemverwaltung. */
public static function erase(?User $user = null): bool
{
$user ??= self::user();
return $user !== null && $user->hasStaffRole(StaffRole::Systemverwalter);
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Model;
/**
* Allgemeine Kommunikationsvorgaben (eine Zeile): Empfänger der internen Benachrichtigung und Aufbewahrungsdauer.
* Empfänger werden nur hier gepflegt; Besucher und das CMS können keine Empfänger angeben.
*/
class CommunicationSettings extends Model
{
protected $fillable = ['recipients', 'retention_months'];
protected function casts(): array
{
return ['recipients' => 'array', 'retention_months' => 'integer'];
}
public static function current(): self
{
return self::query()->first() ?? self::query()->create(['recipients' => []]);
}
/**
* @return list<string>
*/
public function recipientList(): array
{
return array_values(array_filter(
(array) $this->recipients,
fn (mixed $address): bool => is_string($address) && filter_var($address, FILTER_VALIDATE_EMAIL) !== false,
));
}
}
@@ -0,0 +1,268 @@
<?php
namespace App\Domain\Communication;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* Beispielkonfiguration für die Kommunikationsverwaltung: Anliegen, Felder, Feldgruppen, drei Anfragevorlagen und
* fünf Anfrage-Einstiege. Sie entsteht nur auf ausdrücklichen Wunsch („Beispielkonfiguration anlegen“) und nur in einer
* noch leeren Verwaltung. Alles daraus lässt sich in der Verwaltung ändern; die Vorlagen sind gewöhnliche Entwürfe,
* keine Sonderfälle im Code.
*/
final class ExampleConfiguration
{
public function __construct(private readonly Publisher $publisher) {}
public static function isEmpty(): bool
{
return ! InquiryIssue::query()->exists() && ! InquiryField::query()->exists() && ! InquiryTemplate::query()->exists();
}
public function install(?User $by = null): void
{
if (! self::isEmpty()) {
throw new RuntimeException('Die Kommunikationsverwaltung enthält bereits Konfiguration; die Beispiele werden nicht daneben angelegt.');
}
DB::transaction(function () use ($by): void {
$this->issues();
$this->fields();
$this->groups();
$templates = $this->templates();
$this->entries($templates, $by);
});
}
private function issues(): void
{
$tree = [
['allgemein', 'Allgemeine Informationen', 'Allgemeine Fragen zu Lara & Felix, dem Trainingskonzept oder Sonstiges.', []],
['kurse', 'Kurse & Workshops', 'Präsenzkurse und individuelle Kursvorhaben.', [
['kursinfo', 'Allgemeine Kursinformation', 'Ich möchte mich zunächst informieren.'],
['kursvorhaben', 'Konkretes Kursvorhaben', 'Ich plane ein konkretes Kursvorhaben.'],
]],
['materialien', 'Programme & Materialien', 'Trainingsprogramme, Module, Filmgeschichten, Übungen, Materialien und Nutzungsrechte.', []],
['kooperation', 'Kooperationen', 'Anfragen möglicher Trainer, Institutionen und anderer Kooperationspartner.', []],
];
foreach ($tree as $i => [$key, $label, $description, $children]) {
$parent = InquiryIssue::query()->create(['key' => $key, 'label' => $label, 'description' => $description, 'sort_order' => ($i + 1) * 10]);
foreach ($children as $j => [$childKey, $childLabel, $childDescription]) {
InquiryIssue::query()->create(['parent_id' => $parent->id, 'key' => $childKey, 'label' => $childLabel, 'description' => $childDescription, 'sort_order' => ($j + 1) * 10]);
}
}
}
private function fields(): void
{
$text = fn (string $key, string $name, string $label, ?string $purpose = null, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'text', 'purpose' => $purpose, 'help' => $help];
$select = fn (string $key, string $name, string $label, array $options, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'select', 'help' => $help, 'options' => array_map(fn (string $k, string $l): array => ['key' => $k, 'label' => $l], array_keys($options), $options)];
$yesNo = fn (string $key, string $name, string $label): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'boolean'];
$number = fn (string $key, string $name, string $label, int $min = 1, int $max = 1000): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'number', 'settings' => ['min' => $min, 'max' => $max]];
$fields = [
$text('name', 'Name (ein Feld)', 'Ihr Name', 'name'),
['key' => 'email', 'name' => 'E-Mail-Adresse', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'purpose' => 'email'],
['key' => 'nachricht', 'name' => 'Nachricht', 'label' => 'Ihre Nachricht', 'type' => 'textarea', 'purpose' => 'nachricht', 'help' => 'Bitte nennen Sie hier keine Namen oder persönlichen Daten einzelner Kinder.'],
$text('vorname', 'Vorname', 'Vorname', 'vorname'),
$text('nachname', 'Nachname', 'Nachname', 'nachname'),
['key' => 'telefon', 'name' => 'Telefonnummer', 'label' => 'Telefonnummer (optional)', 'type' => 'phone', 'purpose' => 'telefon'],
$text('funktion', 'Funktion / Rolle', 'Ihre Funktion oder Rolle', null, 'Zum Beispiel Schulleitung, Lehrkraft, Vereinsvorstand.'),
$text('region', 'Region / Ort', 'Region oder Ort', null, 'Wo würde das Angebot stattfinden? Die Region genügt.'),
$text('einrichtung_name', 'Name der Einrichtung', 'Name der Schule oder Einrichtung', 'organisation'),
$select('einrichtungstyp', 'Einrichtungstyp', 'Einrichtungstyp', [
'grundschule' => 'Grundschule', 'weiterfuehrend' => 'Weiterführende Schule', 'verein' => 'Verein',
'jugendeinrichtung' => 'Kinder- oder Jugendeinrichtung', 'bildungstraeger' => 'Sonstiger Bildungsträger', 'sonstiges' => 'Sonstiges',
]),
$select('schulart', 'Schulart', 'Schulart', ['gs' => 'Grundschule', 'foerder' => 'Förderschule', 'gemeinschaft' => 'Gemeinschaftsschule', 'sek' => 'Sekundarschule', 'gym' => 'Gymnasium', 'andere' => 'Andere']),
$text('einrichtung_strasse', 'Straße und Hausnummer (Einrichtung)', 'Straße und Hausnummer'),
$text('einrichtung_plz', 'Postleitzahl (Einrichtung)', 'Postleitzahl'),
$text('einrichtung_ort', 'Ort (Einrichtung)', 'Ort'),
$yesNo('traeger_abweichend', 'Träger weicht von der Einrichtung ab', 'Weicht der Bildungsträger bzw. Auftraggeber von der Einrichtung ab?'),
$text('traeger_name', 'Name des Trägers', 'Name des Trägers oder Auftraggebers'),
$select('traeger_art', 'Art des Trägers', 'Art des Trägers', ['kommune' => 'Kommune oder Land', 'freier' => 'Freier Träger', 'verein' => 'Verein', 'sonstiges' => 'Sonstiges']),
$text('traeger_ansprechpartner', 'Ansprechpartner beim Träger', 'Ansprechpartner beim Träger (optional)'),
$yesNo('ort_abweichend', 'Abweichender Durchführungsort', 'Findet der Kurs an einem anderen Ort statt als in der Einrichtung?'),
$text('ort_strasse', 'Straße und Hausnummer (Durchführungsort)', 'Straße und Hausnummer des Durchführungsorts'),
$text('ort_plz', 'Postleitzahl (Durchführungsort)', 'Postleitzahl des Durchführungsorts'),
$text('ort_ort', 'Ort (Durchführungsort)', 'Ort des Durchführungsorts'),
['key' => 'ort_hinweise', 'name' => 'Hinweise zum Durchführungsort', 'label' => 'Organisatorische Hinweise zum Ort (optional)', 'type' => 'textarea'],
$text('alter', 'Alter / Altersbereich', 'Alter oder Altersbereich der Kinder', null, 'Zum Beispiel 8 bis 10 Jahre.'),
$text('klassenstufe', 'Klassenstufe', 'Klassenstufe (falls zutreffend)'),
$number('anzahl_kinder', 'Anzahl der Kinder', 'Anzahl der Kinder insgesamt'),
$number('anzahl_gruppen', 'Anzahl der Gruppen oder Klassen', 'Anzahl der Gruppen oder Klassen', 1, 100),
['key' => 'besonderheiten', 'name' => 'Organisatorische Anforderungen', 'label' => 'Besondere organisatorische Anforderungen (optional)', 'type' => 'textarea', 'help' => 'Bitte keine Angaben zu einzelnen Kindern.'],
$select('kursformat', 'Kursformat', 'Welches Format interessiert Sie?', [
'kompakt' => 'Kompakttraining', 'vertiefung' => 'Vertiefungsprogramm', 'schul_ag' => 'Schul-AG', 'unentschieden' => 'Noch unentschieden',
], 'Kompakttraining: kurzes, individuell abgestimmtes Schultraining mit wenigen Terminen. Vertiefungsprogramm: mehrere aufeinander aufbauende Einheiten über einen längeren Zeitraum. Schul-AG: regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Die Formate sind Arbeitsvorschläge; Termine, Preise und Umfang werden erst im Gespräch festgelegt.'),
['key' => 'zeitraum', 'name' => 'Geplanter Zeitraum', 'label' => 'Geplanter Zeitraum', 'type' => 'period'],
$text('zeitwuensche', 'Zeitwünsche', 'Zeitwünsche (optional)', null, 'Zum Beispiel Wochentage oder Tageszeiten.'),
$number('einheiten', 'Anzahl geplanter Einheiten', 'Anzahl geplanter Einheiten (optional)', 1, 200),
$select('haeufigkeit', 'Gewünschte Häufigkeit', 'Gewünschte Häufigkeit', ['woechentlich' => 'Einmal pro Woche', 'zweiwoechentlich' => 'Alle zwei Wochen', 'absprache' => 'Nach Absprache']),
$select('laufzeit', 'Laufzeit der Schul-AG', 'Gewünschte Laufzeit', ['halbjahr' => 'Ein Schulhalbjahr', 'schuljahr' => 'Ein Schuljahr', 'absprache' => 'Nach Absprache']),
['key' => 'kurs_hinweise', 'name' => 'Ergänzende Informationen (Kurs)', 'label' => 'Ergänzende Informationen (optional)', 'type' => 'textarea'],
$select('material_interesse', 'Interesse an Materialien', 'Wofür interessieren Sie sich?', [
'programme' => 'Trainingsprogramme', 'module' => 'Module', 'filmgeschichten' => 'Filmgeschichten', 'uebungen' => 'Übungen',
'materialien' => 'Materialien', 'rechte' => 'Nutzungsrechte',
]),
$select('koop_art', 'Art der Kooperation', 'Wer sind Sie?', ['trainer' => 'Trainerin oder Trainer', 'institution' => 'Institution', 'sonstiges' => 'Sonstiges']),
$text('koop_organisation', 'Organisation (Kooperation)', 'Organisation (optional)', 'organisation'),
];
foreach ($fields as $i => $field) {
InquiryField::query()->create([
'key' => $field['key'],
'name' => $field['name'],
'label' => $field['label'],
'help' => $field['help'] ?? null,
'type' => $field['type'],
'options' => $field['options'] ?? null,
'settings' => $field['settings'] ?? null,
'purpose' => $field['purpose'] ?? null,
]);
}
}
private function groups(): void
{
$groups = [
['kontakt_einfach', 'Kontakt (einfach)', 'Ihre Kontaktdaten', [['name', true], ['email', true]]],
['ansprechpartner', 'Ansprechpartner', 'Ihre Kontaktdaten', [['vorname', true], ['nachname', true], ['email', true], ['telefon', false], ['funktion', false]]],
['einrichtung', 'Einrichtung', 'Ihre Einrichtung', [['einrichtung_name', true], ['einrichtungstyp', true], ['schulart', false], ['einrichtung_strasse', true], ['einrichtung_plz', true], ['einrichtung_ort', true]]],
['traeger_frage', 'Träger', 'Bildungsträger oder Auftraggeber', [['traeger_abweichend', true]]],
['traeger_angaben', 'Trägerangaben', 'Angaben zum Träger', [['traeger_name', true], ['traeger_art', false], ['traeger_ansprechpartner', false]]],
['ort_frage', 'Durchführungsort', 'Wo soll der Kurs stattfinden?', [['ort_abweichend', true]]],
['ort_angaben', 'Abweichender Durchführungsort', 'Adresse des Durchführungsorts', [['ort_strasse', true], ['ort_plz', true], ['ort_ort', true], ['ort_hinweise', false]]],
['kindergruppe', 'Kindergruppe', 'Die Kindergruppe', [['alter', true], ['klassenstufe', false], ['anzahl_kinder', true], ['anzahl_gruppen', false], ['besonderheiten', false]]],
['kursplanung', 'Kursplanung', 'Ihre Planung', [['zeitraum', false], ['zeitwuensche', false], ['einheiten', false], ['kurs_hinweise', false]]],
['schul_ag', 'Schul-AG', 'Zur Schul-AG', [['laufzeit', true], ['haeufigkeit', true]]],
['material', 'Programm- und Materialbezug', 'Ihr Interesse', [['material_interesse', true]]],
['kooperation', 'Kooperation', 'Zu Ihrer Kooperationsanfrage', [['koop_art', true], ['koop_organisation', false]]],
];
foreach ($groups as $i => [$key, $name, $label, $items]) {
InquiryFieldGroup::query()->create([
'key' => $key,
'name' => $name,
'label' => $label,
'items' => array_map(fn (array $row): array => ['field' => $row[0], 'required' => $row[1]], $items),
'sort_order' => ($i + 1) * 10,
]);
}
}
/**
* @return array<string, InquiryTemplate>
*/
private function templates(): array
{
$cond = fn (string $source, string $op, string ...$values): array => ['source' => $source, 'op' => $op, 'values' => $values];
$rule = fn (string $effect, string $target, array $conditions, ?string $value = null): array => ['effect' => $effect, 'target' => $target, 'match' => 'all', 'conditions' => $conditions, 'value' => $value];
$group = fn (string $key): array => ['kind' => 'group', 'group' => $key];
$general = [
'texts' => ['heading' => 'Schreiben Sie uns', 'intro' => 'Wir freuen uns über Ihre Frage.', 'success_text' => 'Danke, wir melden uns in der Regel innerhalb weniger Werktage.'],
'issues' => ['allgemein'],
'steps' => [['key' => 'sallg1', 'title' => 'Ihre Nachricht', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
'rules' => [],
];
$courses = [
'texts' => [
'heading' => 'Kursanfrage',
'intro' => 'Beschreiben Sie uns, was Sie planen. Alle Angaben sind unverbindlich; Termine, Preise und Umfang besprechen wir gemeinsam.',
'privacy_note' => 'Wir verwenden Ihre Angaben ausschließlich, um Ihre Anfrage zu beantworten. Bitte nennen Sie keine Namen oder persönlichen Daten einzelner Kinder.',
'success_text' => 'Wir haben Ihre Kursanfrage erhalten und melden uns bei Ihnen. Eine Buchung ist damit noch nicht verbunden.',
],
'issues' => ['kurse'],
'steps' => [
['key' => 'skurs1', 'title' => 'Ihr Anliegen', 'intro' => null, 'items' => [['kind' => 'issue'], ['kind' => 'field', 'field' => 'kursformat', 'required' => false]]],
['key' => 'skurs2', 'title' => 'Ihr Vorhaben', 'intro' => 'Einrichtung, Träger, Standort, Zielgruppe und Planung.', 'items' => [
$group('einrichtung'), $group('traeger_frage'), $group('traeger_angaben'), $group('ort_frage'), $group('ort_angaben'),
$group('kindergruppe'), $group('schul_ag'), $group('kursplanung'),
]],
['key' => 'skurs3', 'title' => 'Kontakt und Zusammenfassung', 'intro' => null, 'items' => [
['kind' => 'field', 'field' => 'region', 'required' => true], $group('ansprechpartner'), ['kind' => 'field', 'field' => 'nachricht', 'required' => false],
]],
],
'rules' => [
$rule('show', 'field:kursformat', [$cond('anliegen', 'eq', 'kurse')]),
$rule('skip', 'step:skurs2', [$cond('unteranliegen', 'eq', 'kursinfo')]),
$rule('show', 'group:traeger_angaben', [$cond('traeger_abweichend', 'eq', 'ja')]),
$rule('show', 'group:ort_angaben', [$cond('ort_abweichend', 'eq', 'ja')]),
$rule('show', 'group:schul_ag', [$cond('kursformat', 'eq', 'schul_ag')]),
$rule('show', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]),
$rule('require', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]),
$rule('show', 'field:region', [$cond('unteranliegen', 'eq', 'kursinfo')]),
],
];
$materials = [
'texts' => ['heading' => 'Frage zu Programmen und Materialien', 'intro' => 'Zu Trainingsprogrammen, Modulen, Filmgeschichten, Übungen, Materialien und Nutzungsrechten.'],
'issues' => ['materialien'],
'steps' => [['key' => 'smat1', 'title' => 'Ihre Frage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('material'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
'rules' => [],
];
$cooperation = [
'texts' => ['heading' => 'Kooperation anfragen', 'intro' => 'Für Trainerinnen, Trainer, Institutionen und weitere Partner.'],
'issues' => ['kooperation'],
'steps' => [['key' => 'skoop1', 'title' => 'Ihre Anfrage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kooperation'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
'rules' => [],
];
$templates = [];
foreach ([
['allgemein', 'Allgemeine Kontaktaufnahme', $general],
['kursanfragen', 'Kursanfragen', $courses],
['materialanfragen', 'Materialanfragen', $materials],
['kooperationsanfragen', 'Kooperationsanfragen', $cooperation],
] as [$key, $name, $draft]) {
$templates[$key] = InquiryTemplate::query()->create(['key' => $key, 'name' => $name, 'draft' => $draft]);
}
return $templates;
}
/**
* @param array<string, InquiryTemplate> $templates
*/
private function entries(array $templates, ?User $by): void
{
foreach ($templates as $template) {
$result = $this->publisher->publishTemplate($template, $by, 'Beispielkonfiguration');
$template->refresh();
}
$entries = [
['allgemeiner_kontakt', 'Allgemeiner Kontakt', 'allgemein', ['mode' => 'compact', 'allowed_issues' => ['allgemein']]],
['kurse_workshops', 'Kurse & Workshops', 'kursanfragen', [
'mode' => 'wizard', 'allowed_issues' => ['kurse'],
'texts' => ['heading' => 'Kurse & Workshops anfragen'],
]],
['schul_ag', 'Schul-AG', 'kursanfragen', [
'mode' => 'wizard', 'allowed_issues' => ['kurse'],
'defaults' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag'],
'texts' => ['heading' => 'Schul-AG anfragen', 'intro' => 'Regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Alle Angaben sind unverbindlich.'],
]],
['programme_materialien', 'Programme & Materialien', 'materialanfragen', ['mode' => 'compact', 'allowed_issues' => ['materialien']]],
['kooperation', 'Kooperation', 'kooperationsanfragen', ['mode' => 'compact', 'allowed_issues' => ['kooperation']]],
];
foreach ($entries as [$key, $name, $template, $config]) {
$entry = InquiryEntry::query()->create([
'key' => $key,
'name' => $name,
'template_id' => $templates[$template]->id,
'config' => array_merge(InquiryEntry::emptyConfig(), $config),
]);
$this->publisher->publishEntry($entry);
}
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Domain\Communication;
/**
* Fachliche Verwendung eines Feldes in der Anfrageübersicht. Ohne Verwendung erscheint die Antwort nur in der Liste
* der Antworten.
*/
enum FieldPurpose: string
{
case FirstName = 'vorname';
case LastName = 'nachname';
case FullName = 'name';
case Email = 'email';
case Phone = 'telefon';
case Organisation = 'organisation';
case Message = 'nachricht';
public function label(): string
{
return match ($this) {
self::FirstName => 'Vorname des Ansprechpartners',
self::LastName => 'Nachname des Ansprechpartners',
self::FullName => 'Name des Ansprechpartners',
self::Email => 'E-Mail-Adresse für Rückfragen',
self::Phone => 'Telefonnummer',
self::Organisation => 'Organisation oder Einrichtung',
self::Message => 'Nachricht',
};
}
/** @return list<FieldType> */
public function types(): array
{
return match ($this) {
self::Email => [FieldType::Email],
self::Phone => [FieldType::Phone],
self::Message => [FieldType::Textarea, FieldType::Text],
default => [FieldType::Text],
};
}
/**
* @return array<string, string>
*/
public static function options(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Domain\Communication;
/**
* Unterstützte Feldtypen des Feldkatalogs (ADR-60). Ein neuer technischer Typ ist eine kontrollierte
* Softwareerweiterung: hier ergänzen, in {@see FieldValue} prüfen und in resources/js/inquiry-form.js darstellen.
*/
enum FieldType: string
{
case Text = 'text';
case Textarea = 'textarea';
case Email = 'email';
case Phone = 'phone';
case Number = 'number';
case Select = 'select';
case Multiselect = 'multiselect';
case Boolean = 'boolean';
case Date = 'date';
case Period = 'period';
public function label(): string
{
return match ($this) {
self::Text => 'Text, einzeilig',
self::Textarea => 'Text, mehrzeilig',
self::Email => 'E-Mail-Adresse',
self::Phone => 'Telefonnummer',
self::Number => 'Zahl',
self::Select => 'Einfachauswahl',
self::Multiselect => 'Mehrfachauswahl',
self::Boolean => 'Ja/Nein',
self::Date => 'Datum',
self::Period => 'Zeitraum (von – bis)',
};
}
public function hasOptions(): bool
{
return in_array($this, [self::Select, self::Multiselect], true);
}
/** Ob Bedingungen auf den Wert dieses Feldes aufbauen dürfen. */
public function canControl(): bool
{
return $this === self::Select || $this === self::Multiselect || $this === self::Boolean;
}
/**
* @return array<string, string>
*/
public static function options(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
+286
View File
@@ -0,0 +1,286 @@
<?php
namespace App\Domain\Communication;
use Carbon\Carbon;
use Throwable;
/**
* Prüft und bereinigt einen einzelnen Antwortwert nach dem Feldtyp. Die einzige Stelle, an der Werte eines Besuchers
* in gespeicherte Werte übergehen. Eingabe ist die Feldbeschreibung aus der Fassung (siehe InquiryField::snapshot()).
*/
final class FieldValue
{
public const TEXT_MAX = 200;
public const TEXTAREA_MAX = 4000;
/**
* Rohwert für Bedingungen: ungültige oder fehlende Werte zählen als nicht gesetzt (null).
*
* @param array<string, mixed> $field
*/
public static function forRules(array $field, mixed $raw): string|array|null
{
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
return match ($type) {
FieldType::Select => self::option($field, $raw),
FieldType::Multiselect => self::options($field, $raw) ?: null,
FieldType::Boolean => self::yesNo($raw),
default => null,
};
}
/**
* @param array<string, mixed> $field
* @return array{0: mixed, 1: ?string} bereinigter Wert (null = nicht beantwortet) und Fehlermeldung
*/
public static function check(array $field, mixed $raw, bool $required): array
{
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
$label = (string) ($field['label'] ?? 'Dieses Feld');
$settings = (array) ($field['settings'] ?? []);
$missing = 'Bitte füllen Sie dieses Feld aus.';
if ($type === null) {
return [null, 'Dieses Feld ist nicht verfügbar.'];
}
if (is_string($raw)) {
$raw = str_replace(["\r\n", "\r"], "\n", $raw);
$raw = preg_replace('/[^\P{C}\n\t]/u', '', $raw) ?? '';
$raw = trim($raw);
}
$empty = $raw === null || $raw === '' || $raw === [] || (is_array($raw) && $type === FieldType::Period && trim((string) ($raw['von'] ?? '')) === '' && trim((string) ($raw['bis'] ?? '')) === '');
if ($empty) {
return [null, $required ? $missing : null];
}
switch ($type) {
case FieldType::Text:
case FieldType::Textarea:
if (! is_string($raw)) {
return [null, 'Bitte geben Sie einen Text ein.'];
}
$max = (int) ($settings['max_length'] ?? ($type === FieldType::Text ? self::TEXT_MAX : self::TEXTAREA_MAX));
$max = max(1, min($max, $type === FieldType::Text ? 500 : 8000));
if ($type === FieldType::Text) {
$raw = preg_replace('/\s*\n\s*/', ' ', $raw) ?? $raw;
}
if (mb_strlen($raw) > $max) {
return [null, "Bitte höchstens $max Zeichen."];
}
return [$raw, null];
case FieldType::Email:
if (! is_string($raw) || mb_strlen($raw) > 200 || filter_var($raw, FILTER_VALIDATE_EMAIL) === false) {
return [null, 'Bitte geben Sie eine gültige E-Mail-Adresse ein.'];
}
return [$raw, null];
case FieldType::Phone:
if (! is_string($raw) || preg_match('/^\+?[0-9][0-9 ()\/.\-]{3,28}[0-9]$/', $raw) !== 1) {
return [null, 'Bitte geben Sie eine gültige Telefonnummer ein.'];
}
return [$raw, null];
case FieldType::Number:
if (is_string($raw)) {
$raw = str_replace(',', '.', $raw);
}
if (! is_numeric($raw) || is_nan((float) $raw) || is_infinite((float) $raw)) {
return [null, 'Bitte geben Sie eine Zahl ein.'];
}
$number = $raw + 0;
if (isset($settings['min']) && $settings['min'] !== '' && $number < (float) $settings['min']) {
return [null, 'Bitte mindestens '.self::plain($settings['min']).'.'];
}
if (isset($settings['max']) && $settings['max'] !== '' && $number > (float) $settings['max']) {
return [null, 'Bitte höchstens '.self::plain($settings['max']).'.'];
}
return [$number, null];
case FieldType::Select:
$option = self::option($field, $raw);
return $option === null ? [null, 'Bitte wählen Sie einen der angebotenen Werte.'] : [$option, null];
case FieldType::Multiselect:
if (! is_array($raw)) {
return [null, 'Bitte wählen Sie aus den angebotenen Werten.'];
}
$values = self::options($field, $raw);
if ($values === [] || count($values) !== count(array_unique(array_filter($raw, 'is_string')))) {
return [null, 'Bitte wählen Sie aus den angebotenen Werten.'];
}
return [$values, null];
case FieldType::Boolean:
$answer = self::yesNo($raw);
return $answer === null ? [null, 'Bitte antworten Sie mit Ja oder Nein.'] : [$answer, null];
case FieldType::Date:
$date = self::date($raw);
return $date === null ? [null, 'Bitte geben Sie ein gültiges Datum ein.'] : [$date, null];
case FieldType::Period:
if (! is_array($raw)) {
return [null, 'Bitte geben Sie einen Zeitraum an.'];
}
$from = trim((string) ($raw['von'] ?? '')) === '' ? null : self::date($raw['von']);
$to = trim((string) ($raw['bis'] ?? '')) === '' ? null : self::date($raw['bis']);
if ((trim((string) ($raw['von'] ?? '')) !== '' && $from === null) || (trim((string) ($raw['bis'] ?? '')) !== '' && $to === null)) {
return [null, 'Bitte geben Sie gültige Daten ein.'];
}
if ($required && ($from === null || $to === null)) {
return [null, 'Bitte geben Sie Beginn und Ende an.'];
}
if ($from !== null && $to !== null && $to < $from) {
return [null, 'Das Ende liegt vor dem Beginn.'];
}
return [['von' => $from, 'bis' => $to], null];
}
return [null, "$label ist nicht verfügbar."];
}
/**
* Lesbare Darstellung eines bereinigten Wertes, wie sie in der Anfrage gespeichert wird.
*
* @param array<string, mixed> $field
*/
public static function display(array $field, mixed $value): string
{
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
$labels = [];
foreach ((array) ($field['options'] ?? []) as $option) {
$labels[$option['key']] = $option['label'];
}
return match ($type) {
FieldType::Select => (string) ($labels[$value] ?? $value),
FieldType::Multiselect => implode(', ', array_map(fn (string $key): string => (string) ($labels[$key] ?? $key), (array) $value)),
FieldType::Boolean => $value === 'ja' ? 'Ja' : 'Nein',
FieldType::Date => Carbon::parse((string) $value)->format('d.m.Y'),
FieldType::Period => self::periodText((array) $value),
default => (string) $value,
};
}
/**
* @param array<string, mixed> $field
*/
private static function option(array $field, mixed $raw): ?string
{
if (! is_string($raw)) {
return null;
}
foreach ((array) ($field['options'] ?? []) as $option) {
if (($option['key'] ?? null) === $raw) {
return $raw;
}
}
return null;
}
/**
* @param array<string, mixed> $field
* @return list<string>
*/
private static function options(array $field, mixed $raw): array
{
if (! is_array($raw)) {
return [];
}
$values = [];
foreach ($raw as $item) {
$option = self::option($field, $item);
if ($option === null) {
return [];
}
$values[$option] = $option;
}
return array_values($values);
}
private static function yesNo(mixed $raw): ?string
{
return match (true) {
$raw === true, $raw === 'ja', $raw === '1', $raw === 'true', $raw === 1 => 'ja',
$raw === false, $raw === 'nein', $raw === '0', $raw === 'false', $raw === 0 => 'nein',
default => null,
};
}
private static function date(mixed $raw): ?string
{
if (! is_string($raw) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $raw) !== 1) {
return null;
}
try {
$date = Carbon::createFromFormat('!Y-m-d', $raw);
} catch (Throwable) {
return null;
}
if ($date === false || $date->format('Y-m-d') !== $raw || $date->year < 1900 || $date->year > 2200) {
return null;
}
return $raw;
}
/**
* @param array<string, mixed> $value
*/
private static function periodText(array $value): string
{
$from = isset($value['von']) ? Carbon::parse($value['von'])->format('d.m.Y') : null;
$to = isset($value['bis']) ? Carbon::parse($value['bis'])->format('d.m.Y') : null;
return match (true) {
$from !== null && $to !== null => "$from bis $to",
$from !== null => "ab $from",
$to !== null => "bis $to",
default => '',
};
}
private static function plain(mixed $number): string
{
return rtrim(rtrim(number_format((float) $number, 4, ',', ''), '0'), ',');
}
}
+741
View File
@@ -0,0 +1,741 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Übersetzung zwischen dem Entwurf einer Vorlage (Schritte mit Feldgruppen und Einzelfeldern, Regeln; ADR-60) und der
* flachen Bearbeitungsansicht des Formular-Editors (ADR-61): Bereiche mit Feldern und Teilbereichen, Bedingungen direkt am
* Element. Die Engine bleibt unverändert; der Editor schreibt Felder und Teilbereiche in denselben Katalog, aus dem die
* Vorlage sie liest, und erzeugt aus den Bedingungen am Element dieselben Regeln wie die Regelliste.
*
* Ansicht (Builder-Format der Verwaltung):
* areas[] {key, title, intro, cond, items[]}
* items[] {type: field|section|end|issue, data: {...}} (end: Ende eines Teilbereichs; danach folgen Einzelfelder)
* cond {effect, match, conditions[{source, op, values[]}], pos} (leer: keine Bedingung)
* rules[] Regeln, die sich nicht an ein Element heften lassen (zusätzliche Regeln desselben Ziels, Vorbelegungen)
*
* Ein Teilbereich ist eine Überschrift im Fluss: Die Felder bis zum nächsten Teilbereich gehören zu ihm (Feldgruppe).
* Neue Elemente tragen eine vorläufige Kennung (tmp_…), die beim Speichern durch eine feste ersetzt wird.
*/
final class FormEditor
{
/** Wirkungen, die ein Element selbst trägt, je Art des Ziels. */
public const EFFECTS = [
'step' => ['show', 'hide', 'skip'],
'group' => ['show', 'hide'],
'field' => ['show', 'hide', 'require'],
];
/**
* @param array<string, mixed> $draft
* @param ?int $exceptTemplate die bearbeitete Vorlage: Sie zählt nicht als „auch verwendet in“
* @return array{issues: list<string>, areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function expand(array $draft, ?int $exceptTemplate = null): array
{
$fields = InquiryField::query()->get()->keyBy('key');
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = $this->usage($exceptTemplate);
$byTarget = [];
$rules = array_values(array_filter((array) ($draft['rules'] ?? []), 'is_array'));
foreach ($rules as $index => $rule) {
$byTarget[(string) ($rule['target'] ?? '')][] = $index;
}
$consumed = [];
$take = function (string $target, string $kind) use (&$byTarget, &$consumed, $rules): array {
foreach ($byTarget[$target] ?? [] as $index) {
if (isset($consumed[$index]) || ! in_array($rules[$index]['effect'] ?? null, self::EFFECTS[$kind], true)) {
continue;
}
$consumed[$index] = true;
return $this->cond($rules[$index], $index);
}
return [];
};
$areas = [];
$issueDone = false;
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$step = is_array($step) ? $step : [];
$key = (string) ($step['key'] ?? '');
$items = [];
$list = array_values((array) ($step['items'] ?? []));
foreach ($list as $position => $item) {
$item = is_array($item) ? $item : [];
$kind = (string) ($item['kind'] ?? '');
if ($kind === 'issue') {
$items[] = ['type' => 'issue', 'data' => ['issues' => $issueDone ? [] : array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'))]];
$issueDone = true;
} elseif ($kind === 'group') {
$groupKey = (string) ($item['group'] ?? '');
$group = $groups[$groupKey] ?? null;
$items[] = ['type' => 'section', 'data' => [
'key' => $groupKey,
'label' => $group === null ? 'Nicht mehr verfügbare Feldgruppe' : ($group->label ?: $group->name),
'description' => $group?->description,
'missing' => $group === null,
'used_in' => implode(', ', $usage['groups'][$groupKey] ?? []),
'cond' => $take('group:'.$groupKey, 'group'),
]];
foreach ($group?->itemList() ?? [] as $row) {
$field = $fields[$row['field']] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, $row['required'], $usage, $take)];
}
}
// Ein Einzelfeld direkt nach einer Feldgruppe gehört nicht zu ihr: Das Ende des Teilbereichs ist ausdrücklich.
if (($list[$position + 1]['kind'] ?? null) === 'field') {
$items[] = ['type' => 'end', 'data' => []];
}
} elseif ($kind === 'field') {
$field = $fields[(string) ($item['field'] ?? '')] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, (bool) ($item['required'] ?? false), $usage, $take)];
}
}
}
$areas[] = [
'key' => $key,
'title' => (string) ($step['title'] ?? ''),
'intro' => $step['intro'] ?? null,
'cond' => $take('step:'.$key, 'step'),
'items' => $items,
];
}
$rest = [];
foreach ($rules as $index => $rule) {
if (! isset($consumed[$index])) {
$rest[] = $this->cond($rule, $index) + ['target' => (string) ($rule['target'] ?? ''), 'value' => $rule['value'] ?? null];
}
}
return [
'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')),
'areas' => $areas,
'rules' => $rest,
];
}
/**
* Speichert die Ansicht: legt neue Felder und Teilbereiche im Katalog an, aktualisiert bearbeitete und liefert den
* Entwurf (ohne Texte, die der Editor getrennt führt).
*
* @param array<string, mixed> $editor
* @return array{issues: list<string>, steps: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function persist(array $editor): array
{
return DB::transaction(function () use ($editor): array {
$takenFields = InquiryField::query()->pluck('key')->all();
$takenGroups = InquiryFieldGroup::query()->pluck('key')->all();
$existingFields = InquiryField::query()->get()->keyBy('key');
$existingGroups = InquiryFieldGroup::query()->get()->keyBy('key');
$map = [];
$issues = [];
$steps = [];
$rules = [];
$order = 0;
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$stepKey = Keys::valid($area['key'] ?? null) || preg_match('/^s[a-z0-9]{3,12}$/', (string) ($area['key'] ?? '')) === 1 ? (string) $area['key'] : 's'.Str::lower(Str::random(6));
$items = [];
$group = null;
$flush = function () use (&$group, &$items): void {
if ($group !== null) {
$items[] = $group;
$group = null;
}
};
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$block = is_array($block) ? $block : [];
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
switch ((string) ($block['type'] ?? '')) {
case 'issue':
$flush();
$items[] = ['kind' => 'issue'];
if ($issues === []) {
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
}
break;
case 'end':
$flush();
break;
case 'section':
$flush();
$original = (string) ($data['key'] ?? '');
$isMissing = (bool) ($data['missing'] ?? false);
$current = isset($existingGroups[$original]) ? $existingGroups[$original] : null;
$key = $current?->key ?? Keys::from((string) ($data['label'] ?? ''), $takenGroups);
$takenGroups[] = $key;
$map[$original] = $key;
$group = ['kind' => 'group', 'group' => $key, '_label' => trim((string) ($data['label'] ?? '')), '_description' => $data['description'] ?? null, '_rows' => [], '_current' => $current, '_missing' => $isMissing, '_new' => $current === null];
$this->rule($rules, 'group:'.$key, (array) ($data['cond'] ?? []), 'group', $order);
break;
case 'field':
$field = $this->saveField($data, $existingFields, $takenFields);
$original = (string) ($data['key'] ?? '');
$map[$original] = $field->key;
$required = (bool) ($data['required'] ?? false);
if ($group !== null) {
$group['_rows'][] = ['field' => $field->key, 'required' => $required];
} else {
$items[] = ['kind' => 'field', 'field' => $field->key, 'required' => $required];
}
$this->rule($rules, 'field:'.$field->key, (array) ($data['cond'] ?? []), 'field', $order);
break;
}
}
$flush();
$this->rule($rules, 'step:'.$stepKey, (array) ($area['cond'] ?? []), 'step', $order);
foreach ($items as $index => $item) {
if (($item['kind'] ?? null) !== 'group') {
continue;
}
$items[$index] = $this->saveGroup($item, $existingGroups, $takenGroups);
}
$steps[] = [
'key' => $stepKey,
'title' => mb_substr(trim((string) ($area['title'] ?? '')), 0, 120),
'intro' => filled($area['intro'] ?? null) ? mb_substr(trim((string) $area['intro']), 0, 600) : null,
'items' => $items,
];
}
foreach (array_values((array) ($editor['rules'] ?? [])) as $rule) {
$rule = is_array($rule) ? $rule : [];
$target = (string) ($rule['target'] ?? '');
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$rules[] = [
'effect' => (string) ($rule['effect'] ?? ''),
'target' => $kind === '' ? $target : $kind.':'.($map[$key] ?? $key),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $this->conditions((array) ($rule['conditions'] ?? []), $map),
'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null,
'_pos' => is_numeric($rule['pos'] ?? null) ? (int) $rule['pos'] : 1000 + $order++,
];
}
foreach ($rules as $index => $rule) {
$rules[$index]['conditions'] = $this->conditions((array) $rule['conditions'], $map);
}
usort($rules, fn (array $a, array $b): int => $a['_pos'] <=> $b['_pos']);
return [
'issues' => $issues,
'steps' => $steps,
'rules' => array_map(function (array $rule): array {
unset($rule['_pos']);
return $rule;
}, $rules),
];
});
}
/** Beschriftungen der Wirkungen am Element, je Art des Ziels. */
public const EFFECT_LABELS = [
'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'],
'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'],
'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'],
];
/**
* Baumansicht für die Formularoberfläche (ADR-62): Ein Teilbereich trägt seine Felder selbst (items), die
* Ende-Markierung der flachen Ansicht entfällt. Die Umwandlung ist verlustfrei: fromTree(toTree(x)) liefert dieselbe
* Struktur, die persist() in denselben Entwurf überführt.
*
* @param array<string, mixed> $view Ergebnis von expand()
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public static function toTree(array $view): array
{
$areas = [];
foreach (array_values((array) ($view['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$items = [];
$section = null;
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$block = is_array($block) ? $block : [];
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
switch ((string) ($block['type'] ?? '')) {
case 'issue':
$section = null;
$items[] = ['kind' => 'issue', 'issues' => array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'))];
break;
case 'end':
$section = null;
break;
case 'section':
$items[] = ['kind' => 'section', ...$data, 'items' => []];
$section = array_key_last($items);
break;
case 'field':
if ($section !== null) {
$items[$section]['items'][] = ['kind' => 'field', ...$data];
} else {
$items[] = ['kind' => 'field', ...$data];
}
break;
}
}
$areas[] = [...Arr::except($area, ['items']), 'items' => $items];
}
return ['areas' => $areas, 'rules' => array_values((array) ($view['rules'] ?? []))];
}
/**
* Umkehrung von toTree(): die flache Ansicht, die persist() erwartet. Nach jedem Teilbereich steht eine
* Ende-Markierung, damit folgende Einzelfelder nicht in ihn fallen.
*
* @param array<string, mixed> $tree
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public static function fromTree(array $tree): array
{
$areas = [];
$field = fn (array $item): array => ['type' => 'field', 'data' => Arr::except($item, ['kind', '_id'])];
foreach (array_values((array) ($tree['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$blocks = [];
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
switch ((string) ($item['kind'] ?? '')) {
case 'issue':
$blocks[] = ['type' => 'issue', 'data' => ['issues' => array_values(array_filter((array) ($item['issues'] ?? []), 'is_string'))]];
break;
case 'section':
$blocks[] = ['type' => 'section', 'data' => Arr::except($item, ['kind', '_id', 'items'])];
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
$blocks[] = $field(is_array($inner) ? $inner : []);
}
$blocks[] = ['type' => 'end', 'data' => []];
break;
case 'field':
$blocks[] = $field($item);
break;
}
}
$areas[] = [...Arr::except($area, ['items', '_id']), 'items' => $blocks];
}
return ['areas' => $areas, 'rules' => array_values((array) ($tree['rules'] ?? []))];
}
/**
* Prüft die Baumansicht vor dem Speichern. Was nur gekürzt oder ignoriert würde, wird hier benannt, damit die
* Verwaltung nichts stillschweigend verliert.
*
* @param array<string, mixed> $tree
* @return list<string>
*/
public function validateTree(array $tree): array
{
$errors = [];
$seen = [];
$issueQuestions = 0;
$limit = function (string $where, string $what, mixed $value, int $max) use (&$errors): void {
if (mb_strlen(trim((string) $value)) > $max) {
$errors[] = "$where: $what darf höchstens $max Zeichen lang sein.";
}
};
foreach (array_values((array) ($tree['areas'] ?? [])) as $index => $area) {
$area = is_array($area) ? $area : [];
$title = trim((string) ($area['title'] ?? ''));
$where = 'Bereich '.($index + 1).($title !== '' ? ' „'.$title.'“' : '');
if ($title === '') {
$errors[] = "$where: Der Titel fehlt.";
}
$limit($where, 'Der Titel', $title, 120);
$limit($where, 'Die Einleitung', $area['intro'] ?? '', 600);
$checkField = function (array $field) use (&$errors, &$seen, $where, $limit): void {
$label = trim((string) ($field['label'] ?? ''));
$name = $label !== '' ? '„'.$label.'“' : 'Ein Feld';
if ($label === '') {
$errors[] = "$where: Ein Feld hat keine Frage oder Beschriftung.";
}
$limit($where, "Die Frage $name", $label, 200);
$limit($where, "Der Hilfetext von $name", $field['help'] ?? '', 600);
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
if ($type === null) {
$errors[] = "$where: Bei $name fehlt die Art der Antwort.";
} elseif ($type->hasOptions()) {
$options = array_filter((array) ($field['options'] ?? []), fn (mixed $option): bool => is_array($option) && trim((string) ($option['label'] ?? '')) !== '');
if ($options === []) {
$errors[] = "$where: Bei $name fehlen die Auswahlwerte.";
}
foreach ($options as $option) {
$limit($where, "Ein Auswahlwert von $name", $option['label'], 120);
}
}
$key = (string) ($field['key'] ?? '');
if ($key !== '' && ! str_starts_with($key, 'tmp_')) {
if (isset($seen[$key])) {
$errors[] = "$where: $name steht mehrfach im Formular.";
}
$seen[$key] = true;
}
};
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
if (($item['kind'] ?? null) === 'issue') {
$issueQuestions++;
} elseif (($item['kind'] ?? null) === 'section') {
$label = trim((string) ($item['label'] ?? ''));
if ($label === '') {
$errors[] = "$where: Ein Teilbereich hat keine Überschrift.";
}
$limit($where, 'Die Überschrift eines Teilbereichs', $label, 200);
$limit($where, 'Die Erläuterung eines Teilbereichs', $item['description'] ?? '', 600);
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
$checkField(is_array($inner) ? $inner : []);
}
} elseif (($item['kind'] ?? null) === 'field') {
$checkField($item);
}
}
}
if ($issueQuestions > 1) {
$errors[] = 'Die Frage nach dem Anliegen darf nur einmal im Formular vorkommen.';
}
return array_values(array_unique($errors));
}
/**
* Auswahllisten für die Formularoberfläche: Feldarten, Verwendungen, Wirkungen, Vergleiche, Anliegen und die Felder
* des Katalogs mit Verwendung in anderen Formularen.
*
* @return array<string, mixed>
*/
public function clientConfig(?int $exceptTemplate = null): array
{
$usage = $this->usage($exceptTemplate);
return [
'types' => array_map(fn (FieldType $type): array => ['value' => $type->value, 'label' => $type->label(), 'options' => $type->hasOptions(), 'control' => $type->canControl()], FieldType::cases()),
'purposes' => array_map(fn (FieldPurpose $purpose): array => ['value' => $purpose->value, 'label' => $purpose->label(), 'types' => array_map(fn (FieldType $type): string => $type->value, $purpose->types())], FieldPurpose::cases()),
'effects' => self::EFFECT_LABELS,
'operators' => TemplateCompiler::OPERATORS,
'issues' => InquiryIssue::tree(),
'catalog' => InquiryField::query()->offered()->orderBy('name')->get()->map(fn (InquiryField $field): array => [
'key' => $field->key,
'name' => $field->name,
'label' => $field->label,
'help' => $field->help,
'type' => $field->type->value,
'options' => $field->optionList(),
'purpose' => $field->purpose?->value,
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
])->values()->all(),
];
}
/**
* Eine neue Zeile in der Karteikarte der Bedingungen (leer: Standardwerte).
*
* @return array<string, mixed>
*/
public static function newCondition(): array
{
return ['source' => null, 'op' => 'eq', 'values' => []];
}
/** Vorläufige Kennung eines neuen Feldes oder Teilbereichs. */
public static function temporaryKey(): string
{
return 'tmp_'.Str::lower(Str::random(8));
}
/**
* Verwendung von Feldern und Feldgruppen in Vorlagen: [Art => [Kennung => [Vorlagennamen]]]. Zeigt im Editor, wo
* eine Änderung noch wirkt (bei der nächsten Veröffentlichung dieser Vorlagen).
*
* @return array{fields: array<string, list<string>>, groups: array<string, list<string>>}
*/
public function usage(?int $exceptTemplate = null): array
{
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = ['fields' => [], 'groups' => []];
foreach (InquiryTemplate::query()->whereNull('archived_at')->when($exceptTemplate !== null, fn ($query) => $query->whereKeyNot($exceptTemplate))->get() as $template) {
foreach ((array) ($template->draft['steps'] ?? []) as $step) {
foreach ((array) ($step['items'] ?? []) as $item) {
if (($item['kind'] ?? null) === 'field') {
$usage['fields'][(string) ($item['field'] ?? '')][$template->id] = $template->name;
} elseif (($item['kind'] ?? null) === 'group') {
$key = (string) ($item['group'] ?? '');
$usage['groups'][$key][$template->id] = $template->name;
foreach ($groups[$key]?->itemList() ?? [] as $row) {
$usage['fields'][$row['field']][$template->id] = $template->name;
}
}
}
}
}
return $usage;
}
/**
* @param array<string, mixed> $rule
* @return array<string, mixed>
*/
private function cond(array $rule, int $pos): array
{
return [
'effect' => (string) ($rule['effect'] ?? ''),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => array_values(array_map(fn (mixed $condition): array => [
'source' => (string) ($condition['source'] ?? ''),
'op' => (string) ($condition['op'] ?? 'eq'),
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
], array_filter((array) ($rule['conditions'] ?? []), 'is_array'))),
'pos' => $pos,
];
}
/**
* @param array{fields: array<string, list<string>>, groups: array<string, list<string>>} $usage
* @return array<string, mixed>
*/
private function fieldData(InquiryField $field, bool $required, array $usage, callable $take): array
{
return [
'key' => $field->key,
'label' => $field->label,
'name' => $field->name,
'help' => $field->help,
'type' => $field->type->value,
'options' => $field->optionList(),
'required' => $required,
'purpose' => $field->purpose?->value,
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
'cond' => $take('field:'.$field->key, 'field'),
];
}
/**
* @param list<array<string, mixed>> $rules
* @param array<string, mixed> $cond
*/
private function rule(array &$rules, string $target, array $cond, string $kind, int &$order): void
{
$effect = (string) ($cond['effect'] ?? '');
$conditions = array_values(array_filter((array) ($cond['conditions'] ?? []), fn (mixed $c): bool => is_array($c) && filled($c['source'] ?? null)));
if ($effect === '' || ! in_array($effect, self::EFFECTS[$kind], true) || $conditions === []) {
return;
}
$rules[] = [
'effect' => $effect,
'target' => $target,
'match' => ($cond['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $conditions,
'value' => null,
'_pos' => is_numeric($cond['pos'] ?? null) ? (int) $cond['pos'] : 1000 + $order++,
];
}
/**
* @param array<int|string, mixed> $conditions
* @param array<string, string> $map
* @return list<array{source: string, op: string, values: list<string>}>
*/
private function conditions(array $conditions, array $map): array
{
$result = [];
foreach (array_values($conditions) as $condition) {
$condition = is_array($condition) ? $condition : [];
$source = (string) ($condition['source'] ?? '');
if ($source === '') {
continue;
}
$result[] = [
'source' => $map[$source] ?? $source,
'op' => in_array($condition['op'] ?? 'eq', array_keys(TemplateCompiler::OPERATORS), true) ? (string) ($condition['op'] ?? 'eq') : 'eq',
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
];
}
return $result;
}
/**
* @param array<string, mixed> $data
* @param Collection<string, InquiryField> $existing
* @param list<string> $taken
*/
private function saveField(array $data, $existing, array &$taken): InquiryField
{
$key = (string) ($data['key'] ?? '');
$label = mb_substr(trim((string) ($data['label'] ?? '')), 0, 200);
$help = filled($data['help'] ?? null) ? mb_substr(trim((string) $data['help']), 0, 600) : null;
$type = FieldType::tryFrom((string) ($data['type'] ?? '')) ?? FieldType::Text;
$purpose = FieldPurpose::tryFrom((string) ($data['purpose'] ?? ''));
$field = $existing[$key] ?? null;
if ($field !== null) {
$type = $field->type;
}
if ($purpose !== null && ! in_array($type, $purpose->types(), true)) {
$purpose = null;
}
$options = $type->hasOptions() ? Keys::withKeys(array_values((array) ($data['options'] ?? []))) : null;
if ($field === null) {
$final = Keys::from($label, $taken);
$taken[] = $final;
return InquiryField::query()->create([
'key' => $final,
'name' => mb_substr($label, 0, 120),
'label' => $label,
'help' => $help,
'type' => $type->value,
'options' => $options,
'settings' => null,
'purpose' => $purpose?->value,
'active' => true,
]);
}
$field->fill(['label' => $label, 'help' => $help, 'options' => $options ?? $field->options, 'purpose' => $purpose?->value]);
if ($field->isDirty()) {
$field->save();
}
return $field;
}
/**
* @param array<string, mixed> $group Teilbereich mit gesammelten Feldern (_rows)
* @param Collection<string, InquiryFieldGroup> $existing
* @param list<string> $taken
* @return array{kind: string, group: string}
*/
private function saveGroup(array $group, $existing, array &$taken): array
{
$item = ['kind' => 'group', 'group' => $group['group']];
if ($group['_missing']) {
return $item;
}
$label = mb_substr($group['_label'], 0, 200);
$description = filled($group['_description']) ? mb_substr(trim((string) $group['_description']), 0, 600) : null;
$current = $group['_current'];
if ($current === null) {
InquiryFieldGroup::query()->create([
'key' => $group['group'],
'name' => mb_substr($label, 0, 120),
'label' => $label,
'description' => $description,
'items' => $group['_rows'],
'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10,
'active' => true,
]);
return $item;
}
// Die Bezeichnung bleibt, wenn der Teilbereich vorher keine eigene öffentliche Überschrift hatte und unverändert ist.
$keepLabel = blank($current->label) && $label === $current->name;
$current->fill(['label' => $keepLabel ? null : $label, 'description' => $description, 'items' => $group['_rows']]);
if ($current->isDirty()) {
$current->save();
}
return $item;
}
}
+212
View File
@@ -0,0 +1,212 @@
<?php
namespace App\Domain\Communication;
/**
* Die einzige Auswertung der Bedingungen (ADR-60). Browser, Vorschau und Anfrageservice fragen dieselbe Funktion; der
* Browser entscheidet nichts allein.
*
* Die Auswertung läuft einmal in Dokumentreihenfolge. Eine Bedingung sieht nur Werte von Feldern, die vor ihr stehen und
* selbst sichtbar sind; Werte ausgeblendeter Felder zählen als nicht vorhanden. Daraus folgt: keine Zyklen, und
* nicht mehr relevante Werte erreichen nie die Speicherung.
*/
final class FormEvaluator
{
/**
* @param array<string, mixed> $form wirksames Formular (FormFactory::effective)
* @param array<string, mixed> $values Eingaben des Besuchers, nach Feldkennung
* @return array{steps: array<string, bool>, groups: array<string, bool>, fields: array<string, bool>, required: array<string, bool>, presets: array<string, string>, issue: ?string, subissue: ?string, issue_active: bool}
*/
public function evaluate(array $form, array $values): array
{
$state = ['steps' => [], 'groups' => [], 'fields' => [], 'required' => [], 'presets' => [], 'issue' => null, 'subissue' => null, 'issue_active' => false];
$context = [];
$byTarget = [];
foreach ((array) ($form['rules'] ?? []) as $rule) {
$byTarget[$rule['target']][] = $rule;
}
foreach ((array) $form['steps'] as $step) {
// Ein Bereich lässt sich wie eine Gruppe anzeigen oder ausblenden; „überspringen“ bleibt für ältere Vorlagen gültig.
$stepRules = $byTarget['step:'.$step['key']] ?? [];
$stepVisible = ! $this->any($stepRules, 'skip', $context) && $this->visible($stepRules, $context);
$state['steps'][$step['key']] = $stepVisible;
foreach ($step['items'] as $item) {
if ($item['kind'] === 'issue') {
$this->issue($form, $values, $stepVisible, $state, $context);
continue;
}
$groupVisible = $stepVisible && ($item['key'] === null || $this->visible($byTarget['group:'.$item['key']] ?? [], $context));
if ($item['key'] !== null) {
$state['groups'][$item['key']] = $groupVisible;
}
foreach ($item['fields'] as $row) {
$key = $row['field'];
$rules = $byTarget["field:$key"] ?? [];
$visible = $groupVisible && $this->visible($rules, $context);
$state['fields'][$key] = $visible;
$state['required'][$key] = $visible && ($row['required'] || $this->any($rules, 'require', $context));
if (! $visible) {
continue;
}
$context[$key] = FieldValue::forRules($form['fields'][$key], $values[$key] ?? null);
foreach ($rules as $rule) {
if ($rule['effect'] === 'preset' && $this->matches($rule, $context)) {
$state['presets'][$key] ??= (string) $rule['value'];
}
}
}
}
}
return $state;
}
/**
* @param array<string, mixed> $form
* @param array<string, mixed> $values
* @param array<string, mixed> $state
* @param array<string, string|array<int, string>|null> $context
*/
private function issue(array $form, array $values, bool $stepVisible, array &$state, array &$context): void
{
$state['fields']['anliegen'] = false;
$state['fields']['unteranliegen'] = false;
$state['required']['anliegen'] = false;
$state['required']['unteranliegen'] = false;
if (! $stepVisible) {
return;
}
$state['issue_active'] = true;
$tops = (array) $form['issues'];
$selected = null;
if (count($tops) === 1) {
$selected = $tops[0];
} else {
$state['fields']['anliegen'] = $tops !== [];
$state['required']['anliegen'] = $tops !== [];
$wanted = $values['anliegen'] ?? null;
foreach ($tops as $top) {
if ($top['key'] === $wanted) {
$selected = $top;
}
}
}
$context['anliegen'] = $selected['key'] ?? null;
$state['issue'] = $selected['key'] ?? null;
if ($selected === null) {
return;
}
$children = (array) $selected['children'];
$child = null;
if (count($children) === 1) {
$child = $children[0];
} elseif (count($children) > 1) {
$state['fields']['unteranliegen'] = true;
$state['required']['unteranliegen'] = true;
$wanted = $values['unteranliegen'] ?? null;
foreach ($children as $candidate) {
if ($candidate['key'] === $wanted) {
$child = $candidate;
}
}
}
$context['unteranliegen'] = $child['key'] ?? null;
$state['subissue'] = $child['key'] ?? null;
}
/**
* Sichtbar, wenn keine „Anzeigen“-Regel besteht oder eine zutrifft, und keine „Ausblenden“-Regel zutrifft.
*
* @param list<array<string, mixed>> $rules
* @param array<string, mixed> $context
*/
private function visible(array $rules, array $context): bool
{
$show = array_filter($rules, fn (array $rule): bool => $rule['effect'] === 'show');
if ($show !== [] && ! $this->any($show, 'show', $context)) {
return false;
}
return ! $this->any($rules, 'hide', $context);
}
/**
* @param list<array<string, mixed>> $rules
* @param array<string, mixed> $context
*/
private function any(array $rules, string $effect, array $context): bool
{
foreach ($rules as $rule) {
if ($rule['effect'] === $effect && $this->matches($rule, $context)) {
return true;
}
}
return false;
}
/**
* @param array<string, mixed> $rule
* @param array<string, mixed> $context
*/
private function matches(array $rule, array $context): bool
{
$results = [];
foreach ($rule['conditions'] as $condition) {
$results[] = $this->condition($condition, $context);
}
if ($results === []) {
return false;
}
return $rule['match'] === 'any' ? in_array(true, $results, true) : ! in_array(false, $results, true);
}
/**
* Eine Bedingung auf einem nicht sichtbaren Feld ist nie erfüllt, auch nicht „ist nicht“.
*
* @param array<string, mixed> $condition
* @param array<string, mixed> $context
*/
private function condition(array $condition, array $context): bool
{
if (! array_key_exists($condition['source'], $context)) {
return false;
}
$actual = $context[$condition['source']];
$wanted = (array) $condition['values'];
$hit = is_array($actual)
? array_intersect($actual, $wanted) !== []
: ($actual !== null && in_array($actual, $wanted, true));
return match ($condition['op']) {
'eq', 'in' => $hit,
'neq', 'not_in' => ! $hit,
default => false,
};
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace App\Domain\Communication;
/**
* Baut aus einer veröffentlichten Fassung und der Konfiguration eines Anfrage-Einstiegs das wirksame Formular:
* zugelassene Anliegen, Texte, Darstellung und Vorbelegung. Dieselbe Funktion bedient Besucher, Vorschau und
* Anfrageservice, damit nirgends eine zweite Auslegung entsteht.
*/
final class FormFactory
{
/**
* @param array<string, mixed> $definition aufgelöste Fassung (TemplateCompiler)
* @param array<string, mixed> $config Konfiguration des Einstiegs (veröffentlichter Stand oder Entwurf)
* @return array<string, mixed>
*/
public function effective(array $definition, array $config): array
{
$allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string'));
$allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string'));
$tree = [];
foreach ((array) ($definition['issues'] ?? []) as $issue) {
if ($allowed !== [] && ! in_array($issue['key'], $allowed, true)) {
continue;
}
$children = (array) $issue['children'];
$chosen = array_values(array_filter($children, fn (array $child): bool => in_array($child['key'], $allowedSub, true)));
$issue['children'] = $chosen !== [] ? $chosen : $children;
$tree[] = $issue;
}
$form = $definition;
$form['issues'] = $tree;
$form['texts'] = FormTexts::merge((array) ($definition['texts'] ?? []), (array) ($config['texts'] ?? []));
$form['mode'] = ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact';
$form['open'] = ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline';
$form['defaults'] = $this->defaults($form, (array) ($config['defaults'] ?? []));
$form['controls'] = $this->controls($form);
return $form;
}
/**
* @param array<string, mixed> $form
* @param array<string, mixed> $wanted
* @return array<string, string>
*/
private function defaults(array $form, array $wanted): array
{
$defaults = [];
$tops = array_column((array) $form['issues'], 'key');
if (isset($wanted['anliegen']) && in_array($wanted['anliegen'], $tops, true)) {
$defaults['anliegen'] = $wanted['anliegen'];
foreach ($form['issues'] as $issue) {
if ($issue['key'] === $wanted['anliegen'] && isset($wanted['unteranliegen']) && in_array($wanted['unteranliegen'], array_column($issue['children'], 'key'), true)) {
$defaults['unteranliegen'] = $wanted['unteranliegen'];
}
}
}
foreach ((array) $form['fields'] as $key => $field) {
$value = $wanted[$key] ?? null;
if (! is_string($value) || ! in_array($field['type'], ['select', 'boolean'], true)) {
continue;
}
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
if (in_array($value, $valid, true)) {
$defaults[$key] = $value;
}
}
return $defaults;
}
/**
* Felder, auf deren Änderung das Formular die Regeln neu auswerten lassen muss.
*
* @param array<string, mixed> $form
* @return list<string>
*/
private function controls(array $form): array
{
$controls = [];
foreach ((array) $form['rules'] as $rule) {
foreach ($rule['conditions'] as $condition) {
$controls[$condition['source']] = true;
}
}
return array_keys($controls);
}
/**
* Prüft die Konfiguration eines Einstiegs gegen eine Fassung. Leere Liste: gültig.
*
* @param array<string, mixed> $definition
* @param array<string, mixed> $config
* @return list<string>
*/
public function problems(array $definition, array $config): array
{
$problems = [];
$tops = array_column((array) ($definition['issues'] ?? []), 'key');
$subs = [];
foreach ((array) ($definition['issues'] ?? []) as $issue) {
foreach ($issue['children'] as $child) {
$subs[$child['key']] = $issue['key'];
}
}
$allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string'));
$allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string'));
foreach ($allowed as $key) {
if (! in_array($key, $tops, true)) {
$problems[] = "Das Anliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten.";
}
}
foreach ($allowedSub as $key) {
if (! isset($subs[$key])) {
$problems[] = "Das Unteranliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten.";
} elseif ($allowed !== [] && ! in_array($subs[$key], $allowed, true)) {
$problems[] = "Das Unteranliegen „{$key}“ gehört zu einem Anliegen, das dieser Einstieg nicht zulässt.";
}
}
if (($definition['has_issue'] ?? false) && $allowed !== [] && array_diff($allowed, $tops) === $allowed) {
$problems[] = 'Keines der zugelassenen Anliegen ist in der Vorlage vorhanden.';
}
foreach ((array) ($config['defaults'] ?? []) as $key => $value) {
if ($key === 'anliegen') {
if (! in_array($value, $allowed !== [] ? $allowed : $tops, true)) {
$problems[] = 'Das vorausgewählte Anliegen ist nicht zugelassen oder nicht in der Vorlage.';
}
continue;
}
if ($key === 'unteranliegen') {
if (! isset($subs[$value])) {
$problems[] = 'Das vorausgewählte Unteranliegen ist nicht in der Vorlage.';
}
continue;
}
$field = $definition['fields'][$key] ?? null;
if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) {
$problems[] = "Die Vorbelegung für „{$key}“ ist in der veröffentlichten Vorlage nicht möglich.";
continue;
}
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
if (! in_array($value, $valid, true)) {
$problems[] = "Der vorausgewählte Wert für „{$field['label']}“ gibt es nicht mehr.";
}
}
if (isset($config['mode']) && ! in_array($config['mode'], ['compact', 'wizard'], true)) {
$problems[] = 'Die Darstellung muss „kompakt“ oder „mehrstufig“ sein.';
}
return $problems;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Domain\Communication;
/**
* Vergleichbare Form für gespeicherte Konfigurationen: Schlüssel sortiert, Listen unverändert, Skalare als Text.
*/
final class FormJson
{
/**
* @param array<mixed> $value
* @return array<mixed>
*/
public static function normalize(array $value): array
{
$isList = array_is_list($value);
foreach ($value as $key => $item) {
if (is_array($item)) {
$value[$key] = self::normalize($item);
} elseif (is_int($item) || is_float($item)) {
$value[$key] = (string) $item;
} elseif (is_bool($item)) {
$value[$key] = $item ? '1' : '0';
}
}
if (! $isList) {
ksort($value);
}
return $value;
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Domain\Communication;
/**
* Die Beschreibung des Formulars für den Browser. Sie enthält, was zur Darstellung nötig ist (Texte, Schritte, Felder,
* Auswahlwerte), und den ersten Zustand der Bedingungen, aber keine Regeln und keine Verwendungszwecke: Entscheidungen
* über Sichtbarkeit und Pflicht trifft ausschließlich der Server (FormEvaluator).
*/
final class FormPayload
{
/**
* @param array<string, mixed> $form wirksames Formular (FormFactory::effective)
* @return array<string, mixed>
*/
public static function definition(array $form, FormEvaluator $evaluator): array
{
$fields = [];
foreach ((array) $form['fields'] as $key => $field) {
$settings = (array) ($field['settings'] ?? []);
$fields[$key] = array_filter([
'key' => $key,
'label' => $field['label'],
'help' => $field['help'],
'type' => $field['type'],
'options' => $field['options'] ?: null,
'max_length' => $settings['max_length'] ?? null,
'min' => $settings['min'] ?? null,
'max' => $settings['max'] ?? null,
], fn (mixed $value): bool => $value !== null);
}
return [
'mode' => $form['mode'] ?? 'compact',
'open' => $form['open'] ?? 'inline',
'texts' => $form['texts'],
'issues' => $form['issues'],
'defaults' => (object) ($form['defaults'] ?? []),
'controls' => $form['controls'] ?? [],
'steps' => $form['steps'],
'fields' => $fields,
'state' => self::state($form, (array) ($form['defaults'] ?? []), $evaluator),
];
}
/**
* @param array<string, mixed> $form
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
public static function state(array $form, array $values, FormEvaluator $evaluator): array
{
$state = $evaluator->evaluate($form, $values);
return [
'steps' => (object) $state['steps'],
'groups' => (object) $state['groups'],
'fields' => (object) $state['fields'],
'required' => (object) $state['required'],
'presets' => (object) $state['presets'],
'issue' => $state['issue'],
'subissue' => $state['subissue'],
];
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Domain\Communication;
/**
* Der Anfragegrund, mit dem das Widget „Anfrage“ ein veröffentlichtes Formular lädt (ADR-61): ein vorgewähltes Anliegen,
* optional ein Unteranliegen, und die Formularführung. Das ist eine Darstellungs- und Vorauswahlentscheidung, keine
* Berechtigung: Alles, was ein Anfragegrund wählen kann, bietet das veröffentlichte Formular ohnehin an. Aus dem Grund
* entsteht dieselbe Konfiguration wie bei einem Anfrage-Einstieg, damit Auslieferung, Auswertung und Annahme nur eine
* Auslegung haben (FormFactory::effective).
*/
final class FormReason
{
/**
* Bereinigt die Angaben aus der Adresse oder der Anfrage des Browsers: nur bekannte Schlüssel, nur gültige Kennungen.
*
* @param array<string, mixed> $input
* @return array{anliegen: ?string, unteranliegen: ?string, modus: ?string}
*/
public static function clean(array $input): array
{
$key = fn (mixed $value): ?string => Keys::valid($value) ? $value : null;
$mode = $input['modus'] ?? null;
return [
'anliegen' => $key($input['anliegen'] ?? null),
'unteranliegen' => $key($input['unteranliegen'] ?? null),
'modus' => $mode === 'wizard' || $mode === 'compact' ? $mode : null,
];
}
/**
* Die Konfiguration, die FormFactory::effective erwartet. Ein Anliegen, das die Fassung nicht kennt, schränkt
* nichts ein (das Formular fragt dann wie gewohnt).
*
* @param array<string, mixed> $definition aufgelöste Fassung
* @param array<string, mixed> $reason
* @return array<string, mixed>
*/
public static function config(array $definition, array $reason): array
{
$config = ['mode' => ($reason['modus'] ?? null) === 'wizard' ? 'wizard' : 'compact', 'open' => 'inline'];
$issue = $reason['anliegen'] ?? null;
foreach ((array) ($definition['issues'] ?? []) as $top) {
if ($top['key'] !== $issue) {
continue;
}
$config['allowed_issues'] = [$issue];
$config['defaults'] = ['anliegen' => $issue];
$sub = $reason['unteranliegen'] ?? null;
if ($sub !== null && in_array($sub, array_column((array) $top['children'], 'key'), true)) {
$config['allowed_subissues'] = [$sub];
$config['defaults']['unteranliegen'] = $sub;
}
}
return $config;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Domain\Communication;
/**
* Die Texte eines Anfrageformulars. Die Vorlage legt sie fest, ein Anfrage-Einstieg darf sie überschreiben.
* Alle Texte werden ausschließlich in der Kommunikationsverwaltung gepflegt (ADR-60).
*/
final class FormTexts
{
/** Schlüssel => [Bezeichnung in der Verwaltung, Vorgabe, Hilfetext, mehrzeilig] */
public const FIELDS = [
'heading' => ['Überschrift', 'Ihre Anfrage', 'Steht über dem Formular.', false],
'intro' => ['Beschreibung', '', 'Kurzer Text unter der Überschrift.', true],
'open_label' => ['Beschriftung der Öffnen-Schaltfläche', 'Anfrage stellen', 'Nur wenn der Einstieg zunächst eine Schaltfläche zeigt.', false],
'issue_question' => ['Frage nach dem Anliegen', 'Wie können wir Ihnen helfen?', 'Steht über der Auswahl des Anliegens.', false],
'privacy_note' => ['Hinweis zum Datenschutz', '', 'Steht über der Schaltfläche zum Absenden. Der rechtlich geprüfte Wortlaut wird hier gepflegt; es gibt keine Pflicht-Einwilligungsbox.', true],
'back_label' => ['Schaltfläche „Zurück“', 'Zurück', null, false],
'next_label' => ['Schaltfläche „Weiter“', 'Weiter', null, false],
'summary_title' => ['Überschrift der Zusammenfassung', 'Ihre Angaben im Überblick', 'Letzter Schritt vor dem Absenden im mehrstufigen Dialog.', false],
'edit_label' => ['Schaltfläche „Ändern“', 'Ändern', 'Steht in der Zusammenfassung neben jedem Schritt.', false],
'submit_label' => ['Schaltfläche zum Absenden', 'Anfrage senden', null, false],
'success_title' => ['Bestätigung: Überschrift', 'Vielen Dank für Ihre Anfrage', null, false],
'success_text' => ['Bestätigung: Text', 'Wir haben Ihre Anfrage erhalten und melden uns bei Ihnen.', null, true],
'error_text' => ['Meldung bei einem Fehler', 'Ihre Anfrage konnte nicht gesendet werden. Ihre Eingaben bleiben erhalten; bitte versuchen Sie es noch einmal.', null, true],
];
/**
* @return array<string, string>
*/
public static function defaults(): array
{
$defaults = [];
foreach (self::FIELDS as $key => $field) {
$defaults[$key] = $field[1];
}
return $defaults;
}
/**
* Setzt Vorgaben und eigene Texte zusammen; leere Eigenwerte fallen auf die Vorgabe zurück.
*
* @param array<string, mixed> ...$layers von der schwächsten zur stärksten Schicht
* @return array<string, string>
*/
public static function merge(array ...$layers): array
{
$texts = self::defaults();
foreach ($layers as $layer) {
foreach (array_keys(self::FIELDS) as $key) {
$value = $layer[$key] ?? null;
if (is_string($value) && trim($value) !== '') {
$texts[$key] = trim($value);
}
}
}
return $texts;
}
/**
* Bereinigt eigene Texte aus der Verwaltung: nur bekannte Schlüssel, Länge begrenzt.
*
* @param array<string, mixed> $texts
* @return array<string, string>
*/
public static function clean(array $texts): array
{
$clean = [];
foreach (self::FIELDS as $key => $field) {
$value = $texts[$key] ?? null;
if (is_string($value) && trim($value) !== '') {
$clean[$key] = mb_substr(trim($value), 0, $field[3] ? 1500 : 200);
}
}
return $clean;
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
/**
* Verschlüsseltes Formular-Token, das mit dem Formular ausgeliefert wird. Es trägt Einstieg, Fassung, Zeitpunkt und
* eine einmalige Kennung. Daraus folgen:
* - die Anfrage bezieht sich auf die Fassung, die der Besucher tatsächlich sah,
* - eine zu schnelle Absendung und ein abgelaufenes Formular lassen sich erkennen,
* - doppeltes Absenden ergibt dieselbe Anfrage (Einmalkennung).
* Nichts davon steht in der gespeicherten Seite; die Seite enthält nur die Kennung des Einstiegs.
*/
final class FormToken
{
/**
* @param string $kind 'entry' (Anfrage-Einstieg) oder 'form' (veröffentlichte Vorlage, vom Widget „Anfrage“ gewählt);
* $entryId ist dann die Kennung des Einstiegs beziehungsweise der Vorlage
*/
public static function issue(int $entryId, int $versionId, string $kind = 'entry'): string
{
return Crypt::encryptString(json_encode([
'k' => $kind === 'form' ? 'form' : 'entry',
'e' => $entryId,
'v' => $versionId,
't' => now()->getTimestamp(),
'n' => Str::random(32),
], JSON_THROW_ON_ERROR));
}
/**
* @return array{k: string, e: int, v: int, t: int, n: string}|null
*/
public static function read(mixed $token): ?array
{
if (! is_string($token) || $token === '' || strlen($token) > 2000) {
return null;
}
try {
$data = json_decode(Crypt::decryptString($token), true, 4, JSON_THROW_ON_ERROR);
} catch (DecryptException|\JsonException) {
return null;
}
if (! is_array($data) || ! isset($data['e'], $data['v'], $data['t'], $data['n']) || ! is_string($data['n'])) {
return null;
}
return ['k' => ($data['k'] ?? 'entry') === 'form' ? 'form' : 'entry', 'e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']];
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Eine eingegangene Anfrage. answers hält Bezeichnungen und Werte, wie sie der Besucher sah; sie bleiben auch nach
* einer Änderung der zentralen Konfiguration lesbar.
*/
class Inquiry extends Model
{
protected $fillable = [
'reference', 'entry_id', 'template_version_id', 'submission_token', 'issue_key', 'issue_label', 'subissue_key',
'subissue_label', 'contact_name', 'contact_email', 'contact_phone', 'organisation', 'message', 'answers',
'source_path', 'status', 'notified_at', 'notification_error',
];
protected function casts(): array
{
return ['answers' => 'array', 'status' => InquiryStatus::class, 'notified_at' => 'datetime'];
}
public function entry(): BelongsTo
{
return $this->belongsTo(InquiryEntry::class, 'entry_id');
}
public function templateVersion(): BelongsTo
{
return $this->belongsTo(InquiryTemplateVersion::class, 'template_version_id');
}
public function notes(): HasMany
{
return $this->hasMany(InquiryNote::class)->orderByDesc('created_at')->orderByDesc('id');
}
/** Lesbare Bezeichnung des Anliegens, mit Unteranliegen. */
public function issueTitle(): string
{
return trim(implode(' › ', array_filter([$this->issue_label, $this->subissue_label])));
}
/**
* Woher die Anfrage kam: der Anfrage-Einstieg (älterer Weg) oder das Formular, das das Widget „Anfrage“ eingebunden hat.
*/
public function channelTitle(): string
{
if ($this->entry !== null) {
return $this->entry->name;
}
$template = $this->templateVersion?->template;
return $template !== null ? 'Formular „'.$template->name.'“' : 'Formular gelöscht';
}
public function contactTitle(): string
{
return $this->contact_name ?: ($this->contact_email ?: 'Unbekannt');
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Anfrage-Einstieg: die veröffentlichbare Nutzungsvariante einer Anfragevorlage. config ist der Entwurf,
* published_config der wirksame Stand.
*/
class InquiryEntry extends Model
{
protected $fillable = ['key', 'name', 'template_id', 'config', 'published_config', 'published_at', 'archived_at'];
protected function casts(): array
{
return ['config' => 'array', 'published_config' => 'array', 'published_at' => 'datetime', 'archived_at' => 'datetime'];
}
public function template(): BelongsTo
{
return $this->belongsTo(InquiryTemplate::class, 'template_id');
}
public function inquiries(): HasMany
{
return $this->hasMany(Inquiry::class, 'entry_id');
}
/** Einstiege, die Besuchern ausgeliefert werden können (Vorlage zusätzlich in isLive() prüfen). */
public function scopeLive(Builder $query): Builder
{
return $query->whereNotNull('published_at')->whereNull('archived_at')->whereNotNull('published_config');
}
public function isLive(): bool
{
return $this->published_at !== null && $this->archived_at === null && $this->published_config !== null
&& $this->template?->published_version_id !== null && $this->template->archived_at === null;
}
public function hasUnpublishedChanges(): bool
{
return $this->published_config === null || FormJson::normalize($this->published_config) !== FormJson::normalize((array) $this->config);
}
/**
* @return array<string, mixed>
*/
public static function emptyConfig(): array
{
return [
'mode' => 'compact',
'open' => 'inline',
'allowed_issues' => [],
'allowed_subissues' => [],
'defaults' => [],
'texts' => [],
];
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* Eingabefeld des Feldkatalogs. Wiederverwendbar in beliebig vielen Feldgruppen und Vorlagen.
*/
class InquiryField extends Model
{
protected $fillable = ['key', 'name', 'label', 'help', 'type', 'options', 'settings', 'purpose', 'active', 'archived_at'];
protected function casts(): array
{
return [
'type' => FieldType::class,
'purpose' => FieldPurpose::class,
'options' => 'array',
'settings' => 'array',
'active' => 'boolean',
'archived_at' => 'datetime',
];
}
public function scopeOffered(Builder $query): Builder
{
return $query->where('active', true)->whereNull('archived_at');
}
/**
* Auswahlwerte als Liste [{key, label}] in der gepflegten Reihenfolge.
*
* @return list<array{key: string, label: string}>
*/
public function optionList(): array
{
if ($this->type === FieldType::Boolean) {
return [['key' => 'ja', 'label' => 'Ja'], ['key' => 'nein', 'label' => 'Nein']];
}
if (! $this->type->hasOptions()) {
return [];
}
$list = [];
foreach ((array) $this->options as $option) {
if (is_array($option) && Keys::valid($option['key'] ?? null) && filled($option['label'] ?? null)) {
$list[] = ['key' => $option['key'], 'label' => (string) $option['label']];
}
}
return $list;
}
/**
* Die Beschreibung des Feldes, wie sie in eine Fassung übernommen wird.
*
* @return array<string, mixed>
*/
public function snapshot(): array
{
return [
'key' => $this->key,
'label' => $this->label,
'help' => $this->help,
'type' => $this->type->value,
'options' => $this->optionList(),
'settings' => (array) $this->settings,
'purpose' => $this->purpose?->value,
];
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* Fachliche Zusammenstellung von Feldern. items: geordnete Liste [{field: Kennung, required: bool}].
*/
class InquiryFieldGroup extends Model
{
protected $fillable = ['key', 'name', 'label', 'description', 'items', 'sort_order', 'active', 'archived_at'];
protected function casts(): array
{
return ['items' => 'array', 'active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer'];
}
public function scopeOffered(Builder $query): Builder
{
return $query->where('active', true)->whereNull('archived_at');
}
/**
* @return list<array{field: string, required: bool}>
*/
public function itemList(): array
{
$list = [];
foreach ((array) $this->items as $item) {
if (is_array($item) && Keys::valid($item['field'] ?? null)) {
$list[] = ['field' => $item['field'], 'required' => (bool) ($item['required'] ?? false)];
}
}
return $list;
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Anliegen (oberste Ebene) oder Unteranliegen. Wird nie gelöscht, nur deaktiviert oder archiviert.
*/
class InquiryIssue extends Model
{
protected $fillable = ['parent_id', 'key', 'label', 'description', 'sort_order', 'active', 'archived_at'];
protected function casts(): array
{
return ['active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer'];
}
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id');
}
/** Anliegen, die Besuchern angeboten werden können. */
public function scopeOffered(Builder $query): Builder
{
return $query->where('active', true)->whereNull('archived_at');
}
public function isOffered(): bool
{
return $this->active && $this->archived_at === null;
}
/**
* Baum aus angebotenen Anliegen mit ihren angebotenen Unteranliegen, wie er in eine Fassung übernommen wird.
*
* @return list<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
*/
public static function tree(): array
{
$all = self::query()->offered()->orderBy('sort_order')->orderBy('id')->get();
$children = $all->whereNotNull('parent_id')->groupBy('parent_id');
$tree = [];
foreach ($all->whereNull('parent_id') as $issue) {
$tree[] = [
'key' => $issue->key,
'label' => $issue->label,
'description' => $issue->description,
'children' => ($children[$issue->id] ?? collect())->map(fn (self $child): array => [
'key' => $child->key,
'label' => $child->label,
'description' => $child->description,
])->values()->all(),
];
}
return $tree;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Domain\Communication;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class InquiryNote extends Model
{
protected $fillable = ['inquiry_id', 'user_id', 'body'];
public function inquiry(): BelongsTo
{
return $this->belongsTo(Inquiry::class);
}
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
}
+344
View File
@@ -0,0 +1,344 @@
<?php
namespace App\Domain\Communication;
use App\Jobs\SendInquiryNotification;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;
/**
* Zentraler Anfrageservice (ADR-60): jeder öffentliche Anfrage-Einstieg sendet hierher, unabhängig von der Seite.
*
* 1. gültige veröffentlichte Konfiguration ermitteln, 2. Token prüfen, 3. Bedingungen auswerten, 4. serverseitig
* validieren, 5. speichern, 6. erst danach benachrichtigen, 7. Ergebnis melden.
* Der Browser entscheidet nichts: Werte ausgeblendeter Felder werden verworfen, unbekannte Schlüssel und Auswahlwerte
* zurückgewiesen.
*/
final class InquiryService
{
public function __construct(private readonly FormFactory $factory, private readonly FormEvaluator $evaluator) {}
/**
* Die Fassung und das wirksame Formular für einen Besucher. Null, wenn der Einstieg nicht ausgeliefert wird.
*
* @return array{form: array<string, mixed>, version: InquiryTemplateVersion}|null
*/
public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array
{
$entry->loadMissing('template.publishedVersion');
if (! $entry->isLive()) {
return null;
}
$version = $entry->template->publishedVersion;
if ($versionId !== null && $versionId !== $version->id) {
$older = InquiryTemplateVersion::query()->where('template_id', $entry->template_id)->find($versionId);
$version = $older ?? $version;
}
return ['form' => $this->factory->effective($version->definition, (array) $entry->published_config), 'version' => $version];
}
/**
* @param array<string, mixed> $payload {values: {...}, token: string, website?: string, source?: string}
* @return array{reference: string, created: bool}
*
* @throws SubmissionException
*/
public function submit(InquiryEntry $entry, array $payload): array
{
return $this->accept('entry', $entry->id, $entry->id, fn (?int $version): ?array => $this->deliver($entry, $version), $payload);
}
/**
* Die Fassung und das wirksame Formular einer veröffentlichten Vorlage für einen Besucher, wie sie das Widget
* „Anfrage“ ausliefert. $reason legt den Anfragegrund fest: ein vorgewähltes Anliegen (und Unteranliegen) und die
* Formularführung. Null, wenn die Vorlage nicht veröffentlicht oder archiviert ist.
*
* @param array{anliegen?: ?string, unteranliegen?: ?string, modus?: ?string} $reason
* @return array{form: array<string, mixed>, version: InquiryTemplateVersion}|null
*/
public function deliverForm(InquiryTemplate $template, array $reason = [], ?int $versionId = null): ?array
{
$template->loadMissing('publishedVersion');
if ($template->archived_at !== null || $template->publishedVersion === null) {
return null;
}
$version = $template->publishedVersion;
if ($versionId !== null && $versionId !== $version->id) {
$version = InquiryTemplateVersion::query()->where('template_id', $template->id)->find($versionId) ?? $version;
}
return ['form' => $this->factory->effective($version->definition, FormReason::config($version->definition, $reason)), 'version' => $version];
}
/**
* Nimmt eine Anfrage für eine veröffentlichte Vorlage an (Widget „Anfrage“). Die Verarbeitung ist dieselbe wie über
* einen Einstieg; die Anfrage trägt dann keine Einstiegskennung, sondern verweist über ihre Fassung auf die Vorlage.
*
* @param array{anliegen?: ?string, unteranliegen?: ?string, modus?: ?string} $reason
* @param array<string, mixed> $payload
* @return array{reference: string, created: bool}
*
* @throws SubmissionException
*/
public function submitForm(InquiryTemplate $template, array $reason, array $payload): array
{
return $this->accept('form', $template->id, null, fn (?int $version): ?array => $this->deliverForm($template, $reason, $version), $payload);
}
/**
* @param callable(?int): (array{form: array<string, mixed>, version: InquiryTemplateVersion}|null) $deliver
* @param array<string, mixed> $payload
* @return array{reference: string, created: bool}
*
* @throws SubmissionException
*/
private function accept(string $kind, int $targetId, ?int $entryId, callable $deliver, array $payload): array
{
$token = FormToken::read($payload['token'] ?? null);
if ($token === null || $token['k'] !== $kind || $token['e'] !== $targetId) {
throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419);
}
$age = now()->getTimestamp() - $token['t'];
if ($age > config('communication.token_ttl_hours', 24) * 3600) {
throw new SubmissionException('Das Formular war zu lange geöffnet. Bitte laden Sie die Seite neu.', [], 419);
}
$existing = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->first();
if ($existing !== null) {
return ['reference' => $existing->reference, 'created' => false];
}
$delivered = $deliver($token['v']);
if ($delivered === null) {
throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410);
}
// Automaten: ausgefülltes Köderfeld oder zu schnelle Absendung. Keine Speicherung, keine Rückmeldung an das Programm.
$website = $payload['website'] ?? null;
if ((is_string($website) && trim($website) !== '') || $age < (int) config('communication.min_fill_seconds', 3)) {
if (! (is_string($website) && trim($website) !== '')) {
throw new SubmissionException('Bitte nehmen Sie sich einen Moment Zeit und senden Sie noch einmal.', [], 429);
}
return ['reference' => 'LF-'.now()->format('ymd').'-'.Str::upper(Str::random(5)), 'created' => false];
}
$values = $payload['values'] ?? null;
if (! is_array($values) || strlen((string) json_encode($values)) > (int) config('communication.max_payload_chars', 40000)) {
throw new SubmissionException('Die Eingaben sind ungültig.');
}
$form = $delivered['form'];
$result = $this->process($form, $values);
$source = $payload['source'] ?? null;
$source = is_string($source) && preg_match('#^/[A-Za-z0-9\-_/.]{0,250}$#', $source) === 1 ? $source : null;
try {
$inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([
'reference' => $this->reference(),
'entry_id' => $entryId,
'template_version_id' => $delivered['version']->id,
'submission_token' => hash('sha256', $token['n']),
'issue_key' => $result['issue']['key'] ?? null,
'issue_label' => $result['issue']['label'] ?? null,
'subissue_key' => $result['subissue']['key'] ?? null,
'subissue_label' => $result['subissue']['label'] ?? null,
'contact_name' => $result['contact']['name'] ?? null,
'contact_email' => $result['contact']['email'] ?? null,
'contact_phone' => $result['contact']['telefon'] ?? null,
'organisation' => $result['contact']['organisation'] ?? null,
'message' => $result['contact']['nachricht'] ?? null,
'answers' => $result['answers'],
'source_path' => $source,
'status' => InquiryStatus::Neu->value,
]));
} catch (UniqueConstraintViolationException) {
// Doppelt abgesendet, zwischen Prüfung und Speicherung: dieselbe Anfrage melden.
$again = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->firstOrFail();
return ['reference' => $again->reference, 'created' => false];
}
// Erst nach der Speicherung benachrichtigen. Ein Fehler hier verliert die Anfrage nie.
try {
SendInquiryNotification::dispatch($inquiry->id, url('/verwaltung/anfragen/'.$inquiry->id))->afterCommit();
} catch (Throwable $e) {
report($e);
$inquiry->forceFill(['notification_error' => 'Die Benachrichtigung konnte nicht eingereiht werden: '.Str::limit($e->getMessage(), 300)])->save();
}
return ['reference' => $inquiry->reference, 'created' => true];
}
/**
* Wertet das Formular für Eingaben aus und prüft sie. Wird auch von der Vorschau verwendet.
*
* @param array<string, mixed> $form
* @param array<string, mixed> $values
* @return array{answers: list<array<string, mixed>>, contact: array<string, string>, issue: ?array<string, string>, subissue: ?array<string, string>}
*
* @throws SubmissionException
*/
public function process(array $form, array $values): array
{
$known = array_merge(array_keys((array) $form['fields']), ['anliegen', 'unteranliegen']);
foreach (array_keys($values) as $key) {
if (! is_string($key) || ! in_array($key, $known, true)) {
throw new SubmissionException('Die Eingaben sind ungültig.');
}
}
$state = $this->evaluator->evaluate($form, $values);
$errors = [];
// Anliegen: Auswahl aus dem zugelassenen Rahmen. Ein abweichender Wert ist eine Manipulation, auch wenn das Feld
// nicht sichtbar ist (zum Beispiel weil nur ein Anliegen zugelassen ist).
if ($state['issue_active']) {
foreach (['anliegen', 'unteranliegen'] as $key) {
$raw = $values[$key] ?? null;
$selected = $key === 'anliegen' ? $state['issue'] : $state['subissue'];
$filled = $raw !== null && $raw !== '';
if (! $filled && ($state['required'][$key] ?? false)) {
$errors[$key] = 'Bitte treffen Sie eine Auswahl.';
} elseif ($filled && $raw !== $selected) {
$errors[$key] = 'Bitte wählen Sie einen der angebotenen Werte.';
}
}
}
$answers = [];
$contact = [];
$steps = [];
foreach ((array) $form['steps'] as $step) {
foreach ($step['items'] as $item) {
if ($item['kind'] !== 'group') {
continue;
}
foreach ($item['fields'] as $row) {
$key = $row['field'];
$steps[$key] = [$step['title'], $item['label']];
if (! ($state['fields'][$key] ?? false)) {
continue;
}
$field = $form['fields'][$key];
[$value, $error] = FieldValue::check($field, $values[$key] ?? null, (bool) ($state['required'][$key] ?? false));
if ($error !== null) {
$errors[$key] = $error;
continue;
}
if ($value === null) {
continue;
}
$display = FieldValue::display($field, $value);
$answers[] = [
'key' => $key,
'label' => $field['label'],
'type' => $field['type'],
'value' => $value,
'display' => $display,
'step' => $steps[$key][0],
'group' => $steps[$key][1],
];
if ($field['purpose'] !== null) {
$contact[$field['purpose']] = $display;
}
}
}
}
if ($errors !== []) {
throw new SubmissionException('Bitte prüfen Sie Ihre Angaben.', $errors);
}
$issue = $this->issueEntry($form, $state['issue']);
$subissue = $issue === null ? null : $this->subissueEntry($form, $state['issue'], $state['subissue']);
$name = $contact['name'] ?? trim(($contact['vorname'] ?? '').' '.($contact['nachname'] ?? ''));
return [
'answers' => $answers,
'contact' => array_filter([
'name' => $name,
'email' => $contact['email'] ?? null,
'telefon' => $contact['telefon'] ?? null,
'organisation' => $contact['organisation'] ?? null,
'nachricht' => $contact['nachricht'] ?? null,
], fn (?string $value): bool => $value !== null && $value !== ''),
'issue' => $issue,
'subissue' => $subissue,
];
}
/**
* @param array<string, mixed> $form
* @return ?array{key: string, label: string}
*/
private function issueEntry(array $form, ?string $key): ?array
{
foreach ((array) $form['issues'] as $issue) {
if ($issue['key'] === $key) {
return ['key' => $issue['key'], 'label' => $issue['label']];
}
}
return null;
}
/**
* @param array<string, mixed> $form
* @return ?array{key: string, label: string}
*/
private function subissueEntry(array $form, ?string $issue, ?string $key): ?array
{
foreach ((array) $form['issues'] as $top) {
if ($top['key'] !== $issue) {
continue;
}
foreach ($top['children'] as $child) {
if ($child['key'] === $key) {
return ['key' => $child['key'], 'label' => $child['label']];
}
}
}
return null;
}
private function reference(): string
{
do {
$reference = 'LF-'.now()->format('ymd').'-'.Str::upper(substr(str_replace(['0', 'O', '1', 'I', 'L'], '', Str::upper(Str::random(12))), 0, 5));
} while (strlen($reference) < 12 || Inquiry::query()->where('reference', $reference)->exists());
return $reference;
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Domain\Communication;
enum InquiryStatus: string
{
case Neu = 'neu';
case InBearbeitung = 'in_bearbeitung';
case RueckfrageOffen = 'rueckfrage_offen';
case Erledigt = 'erledigt';
public function label(): string
{
return match ($this) {
self::Neu => 'Neu',
self::InBearbeitung => 'In Bearbeitung',
self::RueckfrageOffen => 'Rückfrage offen',
self::Erledigt => 'Erledigt',
};
}
public function color(): string
{
return match ($this) {
self::Neu => 'warning',
self::InBearbeitung => 'info',
self::RueckfrageOffen => 'danger',
self::Erledigt => 'success',
};
}
/**
* @return array<string, string>
*/
public static function options(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Anfragevorlage: bearbeitbarer Entwurf (draft) und unveränderliche, veröffentlichte Fassungen.
*/
class InquiryTemplate extends Model
{
protected $fillable = ['key', 'name', 'description', 'draft', 'published_version_id', 'archived_at'];
protected function casts(): array
{
return ['draft' => 'array', 'archived_at' => 'datetime'];
}
public function versions(): HasMany
{
return $this->hasMany(InquiryTemplateVersion::class, 'template_id')->orderByDesc('version');
}
public function publishedVersion(): BelongsTo
{
return $this->belongsTo(InquiryTemplateVersion::class, 'published_version_id');
}
public function entries(): HasMany
{
return $this->hasMany(InquiryEntry::class, 'template_id');
}
public function isPublished(): bool
{
return $this->published_version_id !== null;
}
/** Ob der Entwurf von der veröffentlichten Fassung abweicht. */
public function hasUnpublishedChanges(): bool
{
$version = $this->publishedVersion;
return $version === null || FormJson::normalize($version->source) !== FormJson::normalize((array) $this->draft);
}
/**
* @return array<string, mixed>
*/
public static function emptyDraft(): array
{
return [
'texts' => [],
'issues' => [],
'steps' => [],
'rules' => [],
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Unveränderliche Fassung einer Anfragevorlage. definition ist vollständig aufgelöst (Bezeichnungen, Auswahlwerte,
* Regeln); source ist der bearbeitbare Entwurf, aus dem sie entstand. Eine Fassung wird nie geändert.
*/
class InquiryTemplateVersion extends Model
{
public $timestamps = false;
protected $fillable = ['template_id', 'version', 'definition', 'source', 'note', 'published_by', 'published_at'];
protected function casts(): array
{
return ['definition' => 'array', 'source' => 'array', 'published_at' => 'datetime', 'version' => 'integer'];
}
public function template(): BelongsTo
{
return $this->belongsTo(InquiryTemplate::class, 'template_id');
}
protected static function booted(): void
{
// Nur die Bemerkung darf nachträglich ergänzt werden; Löschen ist ausgeschlossen.
static::updating(fn (self $version): bool => array_diff(array_keys($version->getDirty()), ['note']) === []);
static::deleting(fn (): bool => false);
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Support\Str;
/**
* Stabile technische Kennungen für Anliegen, Felder, Gruppen und Auswahlwerte. Eine Kennung entsteht einmal aus der
* Bezeichnung und ändert sich nie; die öffentliche Bezeichnung darf sich ändern (ADR-60).
*/
final class Keys
{
public const PATTERN = '/^[a-z][a-z0-9_]{1,59}$/';
/** Kennungen der eingebauten Anliegen-Felder; Felder des Katalogs dürfen sie nicht belegen. */
public const RESERVED = ['anliegen', 'unteranliegen'];
public static function valid(mixed $key): bool
{
return is_string($key) && preg_match(self::PATTERN, $key) === 1;
}
/**
* Erzeugt aus einer Bezeichnung eine freie Kennung. $taken enthält bereits vergebene Kennungen.
*
* @param list<string> $taken
*/
public static function from(string $label, array $taken = []): string
{
$base = Str::slug($label, '_', 'de');
$base = preg_replace('/^[^a-z]+/', '', $base) ?? '';
$base = substr($base, 0, 50);
if (strlen($base) < 2) {
$base = 'eintrag';
}
$taken = array_merge($taken, self::RESERVED);
$key = $base;
$n = 2;
while (in_array($key, $taken, true)) {
$key = $base.'_'.$n++;
}
return $key;
}
/**
* Ergänzt fehlende oder doppelte Kennungen von Auswahlwerten. Bestehende, gültige Kennungen bleiben unverändert,
* damit gespeicherte Antworten und Bedingungen gültig bleiben, auch wenn eine Bezeichnung umbenannt wird.
*
* @param array<int|string, mixed> $options
* @return list<array{key: string, label: string}>
*/
public static function withKeys(array $options): array
{
$result = [];
$taken = [];
foreach ($options as $option) {
$key = is_array($option) ? ($option['key'] ?? null) : null;
if (self::valid($key) && ! in_array($key, $taken, true)) {
$taken[] = $key;
}
}
foreach ($options as $option) {
$option = is_array($option) ? $option : [];
$label = trim((string) ($option['label'] ?? ''));
if ($label === '') {
continue;
}
$key = $option['key'] ?? null;
if (! self::valid($key) || in_array($key, array_column($result, 'key'), true)) {
$key = self::from($label, array_merge($taken, array_column($result, 'key')));
$taken[] = $key;
}
$result[] = ['key' => $key, 'label' => mb_substr($label, 0, 120)];
}
return $result;
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace App\Domain\Communication;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
/**
* Veröffentlichung von Anfragevorlagen und Anfrage-Einstiegen (ADR-60).
*
* Eine Vorlage wird als neue, unveränderliche Fassung veröffentlicht; bis dahin gilt die bisherige Fassung. Ein Einstieg
* veröffentlicht seine Konfiguration gegen die aktuell gültige Fassung seiner Vorlage. Wirksam ist immer nur ein
* bewusst veröffentlichter Stand, nie ein Entwurf.
*/
final class Publisher
{
public function __construct(private readonly TemplateCompiler $compiler, private readonly FormFactory $factory) {}
/**
* Einstiege, die von einer neuen Fassung betroffen sind, samt Befund gegen die neue Fassung.
*
* @param array<string, mixed> $definition
* @return list<array{entry: InquiryEntry, problems: list<string>}>
*/
public function affected(InquiryTemplate $template, ?array $definition = null): array
{
$result = [];
foreach ($template->entries()->whereNull('archived_at')->orderBy('name')->get() as $entry) {
$problems = $definition !== null && $entry->published_config !== null
? $this->factory->problems($definition, (array) $entry->published_config)
: [];
$result[] = ['entry' => $entry, 'problems' => $problems];
}
return $result;
}
/**
* Veröffentlicht den Entwurf der Vorlage als neue Fassung.
*
* @throws ValidationException
*/
public function publishTemplate(InquiryTemplate $template, ?User $by = null, ?string $note = null): InquiryTemplateVersion
{
$compiled = $this->compiler->compile((array) $template->draft);
if ($compiled['definition'] === null) {
throw ValidationException::withMessages(['draft' => $compiled['errors']]);
}
$blocking = [];
foreach ($this->affected($template, $compiled['definition']) as $row) {
if ($row['entry']->published_config !== null && $row['problems'] !== []) {
$blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zur neuen Fassung: '.implode(' ', $row['problems']);
}
}
if ($blocking !== []) {
throw ValidationException::withMessages(['draft' => $blocking]);
}
return DB::transaction(function () use ($template, $compiled, $by, $note): InquiryTemplateVersion {
$template = InquiryTemplate::query()->lockForUpdate()->findOrFail($template->id);
$next = (int) InquiryTemplateVersion::query()->where('template_id', $template->id)->max('version') + 1;
$version = InquiryTemplateVersion::query()->create([
'template_id' => $template->id,
'version' => $next,
'definition' => $compiled['definition'],
'source' => (array) $template->draft,
'note' => $note !== null && trim($note) !== '' ? mb_substr(trim($note), 0, 300) : null,
'published_by' => $by?->id,
'published_at' => now(),
]);
$template->forceFill(['published_version_id' => $version->id])->save();
return $version;
});
}
/**
* Setzt eine frühere Fassung wieder in Kraft (Rückkehr zu einer gültigen Konfiguration). Betroffene Einstiege
* müssen zur Fassung passen, sonst wird abgelehnt.
*
* @throws ValidationException
*/
public function restoreVersion(InquiryTemplate $template, InquiryTemplateVersion $version): void
{
abort_unless($version->template_id === $template->id, 404);
$blocking = [];
foreach ($this->affected($template, (array) $version->definition) as $row) {
if ($row['entry']->published_config !== null && $row['problems'] !== []) {
$blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zu dieser Fassung: '.implode(' ', $row['problems']);
}
}
if ($blocking !== []) {
throw ValidationException::withMessages(['draft' => $blocking]);
}
$template->forceFill(['published_version_id' => $version->id])->save();
}
/**
* Veröffentlicht die Konfiguration eines Einstiegs.
*
* @throws ValidationException
*/
public function publishEntry(InquiryEntry $entry): void
{
$template = $entry->template()->with('publishedVersion')->firstOrFail();
if ($template->publishedVersion === null) {
throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist noch nicht veröffentlicht. Ein Einstieg kann nur eine veröffentlichte Vorlage verwenden.']]);
}
if ($template->archived_at !== null) {
throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist archiviert.']]);
}
$problems = $this->factory->problems((array) $template->publishedVersion->definition, (array) $entry->config);
if ($problems !== []) {
throw ValidationException::withMessages(['config' => $problems]);
}
$entry->forceFill([
'published_config' => $entry->config,
'published_at' => $entry->published_at ?? now(),
'archived_at' => null,
])->save();
}
/** Nimmt einen Einstieg aus dem öffentlichen Angebot; die Konfiguration bleibt erhalten. */
public function withdrawEntry(InquiryEntry $entry): void
{
$entry->forceFill(['published_config' => null, 'published_at' => null])->save();
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Domain\Communication;
use RuntimeException;
/**
* Eine Einsendung wurde zurückgewiesen. fields: Feldkennung => Meldung. Der Code entspricht dem HTTP-Status.
*/
final class SubmissionException extends RuntimeException
{
/**
* @param array<string, string> $fields
*/
public function __construct(string $message, public readonly array $fields = [], int $code = 422)
{
parent::__construct($message, $code);
}
}
@@ -0,0 +1,452 @@
<?php
namespace App\Domain\Communication;
/**
* Übersetzt den bearbeitbaren Entwurf einer Anfragevorlage in eine vollständig aufgelöste Definition (Fassung) und prüft
* dabei die Konfiguration: Verweise, doppelte Verwendung, Regeln und deren Reihenfolge. Kein Skript, keine freien
* Ausdrücke: Regeln sind Daten aus einer festen Menge von Operatoren und Wirkungen (ADR-60).
*
* Entwurf: {texts, issues[Kennungen oberster Anliegen], steps[{key,title,intro,items[{kind,...}]}], rules[...]}
* Reihenfolge ist Dokumentreihenfolge: Schritte, darin Bausteine, darin Felder. Eine Bedingung darf nur auf Felder
* verweisen, die vor ihrem Ziel stehen; damit sind Zyklen ausgeschlossen.
*/
final class TemplateCompiler
{
public const EFFECTS = [
'show' => 'Anzeigen, wenn …',
'hide' => 'Ausblenden, wenn …',
'require' => 'Pflichtfeld, wenn …',
'skip' => 'Schritt überspringen, wenn …',
'preset' => 'Vorbelegen, wenn …',
];
public const OPERATORS = [
'eq' => 'ist',
'neq' => 'ist nicht',
'in' => 'ist eines von',
'not_in' => 'ist keines von',
];
/**
* @param array<string, mixed> $draft
* @return array{definition: ?array<string, mixed>, errors: list<string>}
*/
public function compile(array $draft): array
{
$errors = [];
$fieldsByKey = InquiryField::query()->offered()->get()->keyBy('key');
$groupsByKey = InquiryFieldGroup::query()->offered()->get()->keyBy('key');
$tree = $this->issueTree((array) ($draft['issues'] ?? []));
$steps = [];
$fields = [];
$usedFields = [];
$usedGroups = [];
$hasIssue = false;
$position = [];
$order = 0;
$stepKeys = [];
foreach (array_values((array) ($draft['steps'] ?? [])) as $index => $step) {
$number = $index + 1;
$step = is_array($step) ? $step : [];
$key = (string) ($step['key'] ?? '');
$title = trim((string) ($step['title'] ?? ''));
if (! Keys::valid($key) && ! preg_match('/^s[a-z0-9]{3,12}$/', $key)) {
$key = 's'.substr(md5($number.'|'.$title), 0, 6);
}
if (in_array($key, $stepKeys, true)) {
$errors[] = "Schritt $number: Die Kennung des Schritts kommt doppelt vor.";
}
$stepKeys[] = $key;
if ($title === '') {
$title = "Schritt $number";
}
$position["step:$key"] = $order++;
$items = [];
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
$kind = (string) ($item['kind'] ?? '');
if ($kind === 'issue') {
if ($hasIssue) {
$errors[] = "Schritt $number („{$title}“): Die Auswahl des Anliegens darf nur einmal vorkommen.";
continue;
}
$hasIssue = true;
$position['field:anliegen'] = $order++;
$position['field:unteranliegen'] = $order++;
$items[] = ['kind' => 'issue'];
continue;
}
if ($kind === 'group') {
$groupKey = (string) ($item['group'] ?? '');
$group = $groupsByKey[$groupKey] ?? null;
if ($group === null) {
$errors[] = "Schritt $number („{$title}“): Eine Feldgruppe ist nicht mehr verfügbar (gelöscht, deaktiviert oder archiviert).";
continue;
}
if (isset($usedGroups[$groupKey])) {
$errors[] = "Die Feldgruppe „{$group->name}“ ist mehrfach eingebunden.";
continue;
}
$usedGroups[$groupKey] = true;
$position["group:$groupKey"] = $order++;
$rows = [];
foreach ($group->itemList() as $row) {
$field = $fieldsByKey[$row['field']] ?? null;
if ($field === null) {
$errors[] = "Die Feldgruppe „{$group->name}“ verwendet ein Feld, das nicht mehr verfügbar ist.";
continue;
}
if (isset($usedFields[$field->key])) {
$errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor.";
continue;
}
$usedFields[$field->key] = true;
$fields[$field->key] = $field->snapshot();
$position['field:'.$field->key] = $order++;
$rows[] = ['field' => $field->key, 'required' => $row['required']];
}
$items[] = [
'kind' => 'group',
'key' => $group->key,
'label' => $group->label ?: $group->name,
'description' => $group->description,
'fields' => $rows,
];
continue;
}
if ($kind === 'field') {
$field = $fieldsByKey[(string) ($item['field'] ?? '')] ?? null;
if ($field === null) {
$errors[] = "Schritt $number („{$title}“): Ein Einzelfeld ist nicht mehr verfügbar.";
continue;
}
if (isset($usedFields[$field->key])) {
$errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor.";
continue;
}
$usedFields[$field->key] = true;
$fields[$field->key] = $field->snapshot();
$position['field:'.$field->key] = $order++;
$items[] = [
'kind' => 'group',
'key' => null,
'label' => null,
'description' => null,
'fields' => [['field' => $field->key, 'required' => (bool) ($item['required'] ?? false)]],
];
continue;
}
$errors[] = "Schritt $number („{$title}“): Ein Baustein hat keinen gültigen Typ.";
}
if ($items === []) {
$errors[] = "Schritt $number („{$title}“) enthält nichts.";
}
$steps[] = [
'key' => $key,
'title' => mb_substr($title, 0, 120),
'intro' => $this->text($step['intro'] ?? null, 600),
'items' => $items,
];
}
if ($steps === []) {
$errors[] = 'Die Vorlage hat noch keinen Schritt.';
}
$purposes = [];
foreach ($fields as $field) {
if ($field['purpose'] !== null) {
$purposes[$field['purpose']][] = $field['key'];
}
}
if (! isset($purposes[FieldPurpose::Email->value])) {
$errors[] = 'Die Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“, sonst lässt sich eine Anfrage nicht beantworten.';
}
foreach ($purposes as $purpose => $keys) {
if (count($keys) > 1) {
$errors[] = 'Die Verwendung „'.FieldPurpose::from($purpose)->label().'“ ist mehreren Feldern zugeordnet.';
}
}
if ($hasIssue && $tree === []) {
$errors[] = 'Die Auswahl des Anliegens hat kein verfügbares Anliegen. Bitte Anliegen anlegen oder aktivieren.';
}
$rules = $this->rules((array) ($draft['rules'] ?? []), $fields, $tree, $hasIssue, $position, $stepKeys, $usedGroups, $errors);
$definition = [
'v' => 1,
'texts' => FormTexts::merge(FormTexts::clean((array) ($draft['texts'] ?? []))),
'has_issue' => $hasIssue,
'issues' => $hasIssue ? $tree : [],
'fields' => $fields,
'steps' => $steps,
'rules' => $rules,
];
return ['definition' => $errors === [] ? $definition : null, 'errors' => array_values(array_unique($errors))];
}
/**
* Vollständige Auflösung ohne Fehlerfreiheit: für die Vorschau eines unfertigen Entwurfs.
*
* @param array<string, mixed> $draft
* @return array{definition: ?array<string, mixed>, errors: list<string>}
*/
public function preview(array $draft): array
{
return $this->compile($draft);
}
/**
* @param list<string> $only
* @return list<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
*/
private function issueTree(array $only): array
{
$tree = InquiryIssue::tree();
if ($only === []) {
return $tree;
}
return array_values(array_filter($tree, fn (array $issue): bool => in_array($issue['key'], $only, true)));
}
/**
* @param array<int|string, mixed> $rules
* @param array<string, array<string, mixed>> $fields
* @param list<array<string, mixed>> $tree
* @param array<string, int> $position
* @param list<string> $stepKeys
* @param array<string, true> $usedGroups
* @param list<string> $errors
* @return list<array<string, mixed>>
*/
private function rules(array $rules, array $fields, array $tree, bool $hasIssue, array $position, array $stepKeys, array $usedGroups, array &$errors): array
{
$normalized = [];
$issueKeys = array_column($tree, 'key');
$subKeys = [];
foreach ($tree as $issue) {
foreach ($issue['children'] as $child) {
$subKeys[] = $child['key'];
}
}
foreach (array_values($rules) as $index => $rule) {
$number = $index + 1;
$rule = is_array($rule) ? $rule : [];
$effect = (string) ($rule['effect'] ?? '');
$target = (string) ($rule['target'] ?? '');
if (! isset(self::EFFECTS[$effect])) {
$errors[] = "Regel $number: Die Wirkung ist ungültig.";
continue;
}
[$targetKind] = array_pad(explode(':', $target, 2), 2, '');
if (! isset($position[$target])) {
$errors[] = "Regel $number: Das Ziel „{$target}“ gibt es in dieser Vorlage nicht.";
continue;
}
$kindOk = match ($effect) {
'show', 'hide' => in_array($targetKind, ['step', 'group', 'field'], true),
'require', 'preset' => $targetKind === 'field',
'skip' => $targetKind === 'step',
default => false,
};
if (! $kindOk) {
$errors[] = "Regel $number: Die Wirkung „".self::EFFECTS[$effect].'“ passt nicht zum Ziel.';
continue;
}
if (in_array($target, ['field:anliegen', 'field:unteranliegen'], true)) {
$errors[] = "Regel $number: Die Auswahl des Anliegens lässt sich nicht durch eine Regel steuern.";
continue;
}
$presetValue = null;
if ($effect === 'preset') {
$field = $fields[substr($target, 6)] ?? null;
$presetValue = $rule['value'] ?? null;
if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) {
$errors[] = "Regel $number: Vorbelegt werden können nur Einfachauswahl- und Ja/Nein-Felder.";
continue;
}
$valid = array_column($field['options'] ?: [['key' => 'ja'], ['key' => 'nein']], 'key');
if ($field['type'] === 'boolean') {
$valid = ['ja', 'nein'];
}
if (! is_string($presetValue) || ! in_array($presetValue, $valid, true)) {
$errors[] = "Regel $number: Der Wert zum Vorbelegen ist kein Auswahlwert des Feldes.";
continue;
}
}
$match = ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all';
$conditions = [];
foreach (array_values((array) ($rule['conditions'] ?? [])) as $c => $condition) {
$condition = is_array($condition) ? $condition : [];
$source = (string) ($condition['source'] ?? '');
$op = (string) ($condition['op'] ?? 'eq');
$values = array_values(array_filter((array) ($condition['values'] ?? []), fn (mixed $v): bool => is_string($v) && $v !== ''));
if (! isset(self::OPERATORS[$op])) {
$errors[] = "Regel $number, Bedingung ".($c + 1).': Der Vergleich ist ungültig.';
continue;
}
if (in_array($op, ['eq', 'neq'], true)) {
$values = array_slice($values, 0, 1);
}
if ($values === []) {
$errors[] = "Regel $number, Bedingung ".($c + 1).': Es fehlt ein Vergleichswert.';
continue;
}
$sourceKey = "field:$source";
if ($source === 'anliegen' || $source === 'unteranliegen') {
if (! $hasIssue) {
$errors[] = "Regel $number: Die Vorlage hat keine Auswahl des Anliegens.";
continue;
}
$valid = $source === 'anliegen' ? $issueKeys : $subKeys;
} else {
$field = $fields[$source] ?? null;
if ($field === null || ! isset($position[$sourceKey])) {
$errors[] = "Regel $number: Die Bedingung bezieht sich auf ein Feld, das es in der Vorlage nicht gibt.";
continue;
}
if (! FieldType::from($field['type'])->canControl()) {
$errors[] = "Regel $number: Bedingungen sind nur für Auswahlfelder und Ja/Nein-Felder möglich („{$field['label']}“).";
continue;
}
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
}
if (array_diff($values, $valid) !== []) {
$errors[] = "Regel $number: Ein Vergleichswert ist kein Auswahlwert von „{$source}“.";
continue;
}
if ($position[$sourceKey] >= $position[$target]) {
$errors[] = "Regel $number: Die Bedingung „{$source}“ muss in der Vorlage vor ihrem Ziel stehen, sonst kann sie noch nicht ausgewertet werden.";
continue;
}
$conditions[] = ['source' => $source, 'op' => $op, 'values' => $values];
}
if ($conditions === [] || count($conditions) !== count((array) ($rule['conditions'] ?? []))) {
if ($conditions === []) {
$errors[] = "Regel $number hat keine gültige Bedingung.";
}
continue;
}
$normalized[] = [
'effect' => $effect,
'target' => $target,
'match' => $match,
'conditions' => $conditions,
'value' => $presetValue,
];
}
// Widersprüche: gleiche Bedingung zeigt und blendet dasselbe Ziel aus.
$seen = [];
foreach ($normalized as $rule) {
if (! in_array($rule['effect'], ['show', 'hide'], true)) {
continue;
}
$signature = json_encode([$rule['target'], $rule['match'], $rule['conditions']]);
$opposite = $rule['effect'] === 'show' ? 'hide' : 'show';
if (isset($seen[$opposite][$signature])) {
$errors[] = 'Widerspruch: Das Ziel „'.$rule['target'].'“ wird unter derselben Bedingung angezeigt und ausgeblendet.';
}
$seen[$rule['effect']][$signature] = true;
}
return $normalized;
}
private function text(mixed $value, int $max): ?string
{
if (! is_string($value) || trim($value) === '') {
return null;
}
return mb_substr(trim($value), 0, $max);
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Domain\Communication;
/**
* Bereinigt den Entwurf einer Anfragevorlage aus dem Formular der Verwaltung: Listen mit fortlaufenden Schlüsseln
* (Repeater liefern Zufallsschlüssel), nur bekannte Felder, Texte begrenzt. Eine inhaltliche Prüfung geschieht erst beim
* Veröffentlichen (TemplateCompiler); ein unfertiger Entwurf darf gespeichert werden.
*/
final class TemplateDraft
{
/**
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
public static function clean(array $draft): array
{
$steps = [];
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$step = is_array($step) ? $step : [];
$items = [];
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$item = is_array($item) ? $item : [];
$kind = (string) ($item['kind'] ?? '');
$items[] = match ($kind) {
'issue' => ['kind' => 'issue'],
'group' => ['kind' => 'group', 'group' => (string) ($item['group'] ?? '')],
'field' => ['kind' => 'field', 'field' => (string) ($item['field'] ?? ''), 'required' => (bool) ($item['required'] ?? false)],
default => ['kind' => $kind],
};
}
$steps[] = [
'key' => (string) ($step['key'] ?? ''),
'title' => mb_substr(trim((string) ($step['title'] ?? '')), 0, 120),
'intro' => filled($step['intro'] ?? null) ? mb_substr(trim((string) $step['intro']), 0, 600) : null,
'items' => $items,
];
}
$rules = [];
foreach (array_values((array) ($draft['rules'] ?? [])) as $rule) {
$rule = is_array($rule) ? $rule : [];
$conditions = [];
foreach (array_values((array) ($rule['conditions'] ?? [])) as $condition) {
$condition = is_array($condition) ? $condition : [];
$conditions[] = [
'source' => (string) ($condition['source'] ?? ''),
'op' => (string) ($condition['op'] ?? 'eq'),
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
];
}
$rules[] = [
'effect' => (string) ($rule['effect'] ?? ''),
'target' => (string) ($rule['target'] ?? ''),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $conditions,
'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null,
];
}
return [
'texts' => FormTexts::clean((array) ($draft['texts'] ?? [])),
'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')),
'steps' => $steps,
'rules' => $rules,
];
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace App\Domain\Media;
use Illuminate\Contracts\Filesystem\Filesystem;
/**
* Größenstufen eines Bildes (docs/architektur/bildvarianten.md).
*
* Neben der Hauptdatei (`vorschau/element-12.jpg`, „voll“: bis 2400 px bei Bildern, 640 px sonst) liegen daneben
* kleinere JPEG-Fassungen, benannt nach der Hauptdatei (`element-12-klein.jpg`). Es gibt keine Spalte dafür: Die Hauptdatei
* bleibt `thumbnail_path`, die Fassungen folgen der Namensregel. Fehlt eine Fassung, gilt die Hauptdatei (kein Bruch bei
* Bestand, der noch nicht abgeleitet ist).
*
* Verwaltungsoberfläche (Disk `media_derived`):
* - `klein` 360 px: Auswahl, Listen, Karten (Anzeige bis etwa 180 px, doppelt für scharfe Bildschirme)
* - `mittel` 960 px: Detailansicht, Vorschau, Titelbild im Editor
* - voll: die Hauptdatei
*
* Website (Disk `media_public`, `website/{id}/datei-{breite}.jpg`): Breiten {@see self::PUBLIC_WIDTHS}, daneben die
* Hauptdatei `datei.jpg`. Eine Fassung entsteht nur, wenn die Quelle breiter ist (nie vergrößern).
*
* Geschrieben wird nur in der Warteschlange; der Web-Prozess liest.
*/
class ImageVariants
{
/** @var array<string, int> */
public const SIZES = ['klein' => 360, 'mittel' => 960];
/** @var list<int> */
public const PUBLIC_WIDTHS = [640, 1280, 1920];
private const QUALITY = 80;
public static function isSize(mixed $size): bool
{
return is_string($size) && array_key_exists($size, self::SIZES);
}
public static function isPublicWidth(mixed $width): bool
{
return is_int($width) && in_array($width, self::PUBLIC_WIDTHS, true);
}
/** `vorschau/element-12.jpg` → `vorschau/element-12-klein.jpg` */
public static function path(string $base, string $size): string
{
$extension = pathinfo($base, PATHINFO_EXTENSION);
$stem = $extension === '' ? $base : substr($base, 0, -(strlen($extension) + 1));
return $stem.'-'.$size.'.jpg';
}
/** `website/12/datei.jpg` → `website/12/datei-640.jpg` */
public static function publicPath(string $base, int $width): string
{
return self::path($base, (string) $width);
}
/**
* Pfad, der für die Größe ausgeliefert wird: die Fassung, wenn es sie gibt, sonst die Hauptdatei.
*/
public static function resolve(Filesystem $disk, string $base, ?string $size): string
{
if (! self::isSize($size)) {
return $base;
}
$variant = self::path($base, (string) $size);
return $disk->exists($variant) ? $variant : $base;
}
/**
* Legt die Fassungen der Verwaltungsoberfläche zur Hauptdatei an (Warteschlange). Ist die Quelle nicht breiter als die
* Stufe, entfällt die Fassung, und eine ältere wird entfernt.
*
* @return list<string> Pfade der geschriebenen Fassungen
*/
public static function generate(Filesystem $disk, string $base): array
{
$targets = [];
foreach (self::SIZES as $name => $width) {
$targets[self::path($base, $name)] = $width;
}
return self::write($disk, $disk, $base, $targets);
}
/**
* Legt die Breiten für die Website neben der öffentlichen Hauptdatei an. Nur JPEG-Quellen: andere Formate (PNG, GIF,
* WebP) können Transparenz tragen, die ein JPEG nicht hält; sie bleiben unverändert.
*
* @return list<string> Pfade der geschriebenen Fassungen
*/
public static function generatePublic(Filesystem $source, Filesystem $target, string $sourcePath, string $publicBase): array
{
if (! in_array(strtolower(pathinfo($publicBase, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return [];
}
$targets = [];
foreach (self::PUBLIC_WIDTHS as $width) {
$targets[self::publicPath($publicBase, $width)] = $width;
}
return self::write($source, $target, $sourcePath, $targets);
}
/** Entfernt alle Fassungen zu einer öffentlichen Hauptdatei (Rücknahme, Ersatz). */
public static function deletePublic(Filesystem $disk, string $publicBase): void
{
foreach (self::PUBLIC_WIDTHS as $width) {
$disk->delete(self::publicPath($publicBase, $width));
}
}
/**
* @param array<string, int> $targets Zielpfad → Breite
* @return list<string>
*/
private static function write(Filesystem $source, Filesystem $target, string $sourcePath, array $targets): array
{
if (! $source->exists($sourcePath)) {
return [];
}
$bytes = $source->get($sourcePath);
$image = is_string($bytes) && $bytes !== '' ? @imagecreatefromstring($bytes) : false;
if ($image === false) {
return [];
}
$width = imagesx($image);
$height = imagesy($image);
$written = [];
foreach ($targets as $path => $targetWidth) {
if ($width <= $targetWidth) {
$target->delete($path);
continue;
}
$encoded = self::scaled($image, $width, $height, $targetWidth);
if ($encoded !== null && $target->put($path, $encoded)) {
$written[] = $path;
}
}
imagedestroy($image);
return $written;
}
private static function scaled(\GdImage $image, int $width, int $height, int $targetWidth): ?string
{
$targetHeight = (int) max(1, round($height * ($targetWidth / max(1, $width))));
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
imagefill($canvas, 0, 0, (int) imagecolorallocate($canvas, 255, 255, 255));
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
imageinterlace($canvas, true);
ob_start();
imagejpeg($canvas, null, self::QUALITY);
$bytes = ob_get_clean();
imagedestroy($canvas);
return is_string($bytes) && $bytes !== '' ? $bytes : null;
}
}
+2
View File
@@ -89,6 +89,7 @@ public function place(ContentElement $element, string $incoming): void
}
if ($element->output_class === 'bild') {
ImageVariants::generate(Storage::disk('media_derived'), $target);
$element->thumbnail_path = $target;
$element->thumbnail_source = 'eigen';
} else {
@@ -97,6 +98,7 @@ public function place(ContentElement $element, string $incoming): void
$element->thumbnail_error = null;
$element->save();
$element->touch();
Storage::disk('cms_incoming')->delete($incoming);
}
+6
View File
@@ -335,6 +335,7 @@ private function frame(ContentElement $element, ContentElementVersion $version,
return;
}
ImageVariants::generate($disk, $target);
$element->thumbnail_path = $target;
if (! filled($element->thumbnail_alt)) {
$element->thumbnail_alt = $element->working_title;
@@ -344,6 +345,7 @@ private function frame(ContentElement $element, ContentElementVersion $version,
$element->thumbnail_source = 'frame:'.$version->id.'@0';
}
$element->save();
$element->touch();
}
private function still(ContentElement|Composition $subject, Filesystem $disk, string $file, string $name): void
@@ -388,6 +390,7 @@ private function still(ContentElement|Composition $subject, Filesystem $disk, st
$path = 'vorschau/'.$name.'.jpg';
Storage::disk('media_derived')->put($path, $bytes);
ImageVariants::generate(Storage::disk('media_derived'), $path);
$subject->thumbnail_path = $path;
if (! filled($subject->thumbnail_alt)) {
@@ -396,6 +399,9 @@ private function still(ContentElement|Composition $subject, Filesystem $disk, st
$subject->thumbnail_error = null;
$subject->save();
// Die Adresse trägt die Version (updated_at) und wird dauerhaft zwischengespeichert: Ein neu abgeleitetes Bild
// unter gleichem Pfad muss die Version ändern, auch wenn sonst nichts an der Zeile anders ist.
$subject->touch();
}
private function rememberElement(ContentElement $element, string $source): void
+25 -2
View File
@@ -2,14 +2,37 @@
namespace App\Domain\Media;
use Carbon\CarbonInterface;
class ThumbnailRef
{
public static function url(string $route, string $kind, int $id, mixed $path): ?string
/**
* Adresse eines Vorschaubildes.
*
* @param string|null $size `klein` (Auswahl, Listen, Karten), `mittel` (Detail, Vorschau) oder null für die volle Datei
* @param CarbonInterface|int|string|null $version Stand des Bildes (zum Beispiel `updated_at`). Mit Version darf der Browser das Bild
* dauerhaft behalten; ohne Version fragt er jedes Mal nach (ETag).
*/
public static function url(string $route, string $kind, int $id, mixed $path, ?string $size = null, CarbonInterface|int|string|null $version = null): ?string
{
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
return null;
}
return route($route, ['kind' => $kind, 'subject' => $id]);
$query = [];
if (ImageVariants::isSize($size)) {
$query['g'] = $size;
}
if ($version instanceof CarbonInterface) {
$version = $version->getTimestamp();
}
if ($version !== null && $version !== '') {
$query['v'] = $version;
}
return route($route, ['kind' => $kind, 'subject' => $id] + $query);
}
}
+28 -1
View File
@@ -45,10 +45,37 @@ public function present(ContentElement|int $element): ?WebsitePresentation
'audio' => 'audio',
default => 'bild',
},
url: route('website.media', $element),
// Bilder tragen den Zeitpunkt der Freigabe in der Adresse (dauerhaft zwischenspeicherbar); Film und Hörstück bleiben unverändert.
url: $element->output_class === 'film' || $element->output_class === 'audio'
? route('website.media', $element)
: route('website.media', ['element' => $element, 'v' => $element->website_released_at->getTimestamp()]),
srcset: $this->srcset($element, $path),
);
}
/**
* `srcset` eines freigegebenen JPEG-Bildes: die Breiten aus {@see ImageVariants::PUBLIC_WIDTHS} und die volle Datei.
* Fehlt eine Breite noch (Bestand), liefert die Adresse die volle Datei und stößt das Anlegen an; die Beschreibung bleibt
* dann ungenau, das Bild aber richtig. PNG, GIF und WebP bleiben ohne Fassungen (Transparenz).
*/
private function srcset(ContentElement $element, string $path): ?string
{
if ($element->output_class !== 'bild' || ! in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return null;
}
$version = $element->website_released_at->getTimestamp();
$entries = [];
foreach (ImageVariants::PUBLIC_WIDTHS as $width) {
$entries[] = route('website.media', ['element' => $element, 'w' => $width, 'v' => $version]).' '.$width.'w';
}
$entries[] = route('website.media', ['element' => $element, 'v' => $version]).' 2400w';
return implode(', ', $entries);
}
/**
* Slideshow: freigegebene Medien in der angegebenen Reihenfolge. Nicht freigegebene Einträge entfallen.
*
+14
View File
@@ -15,5 +15,19 @@ public function __construct(
public readonly ?string $credit,
public readonly string $kind,
public readonly string $url,
/** Bildadressen in mehreren Breiten für `srcset` (nur Bilder, deren Breiten die Warteschlange anlegt), sonst null. */
public readonly ?string $srcset = null,
) {}
/**
* Adresse in einer der Breiten aus {@see ImageVariants::PUBLIC_WIDTHS}; ohne Breiten (oder bei anderer Breite) die volle Datei.
*/
public function urlForWidth(?int $width): string
{
if ($width === null || $this->srcset === null || ! ImageVariants::isPublicWidth($width)) {
return $this->url;
}
return $this->url.(str_contains($this->url, '?') ? '&' : '?').'w='.$width;
}
}
@@ -0,0 +1,191 @@
<?php
namespace App\Filament\Pages;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\ExampleConfiguration;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use App\Mail\CommunicationTestMail;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
use Throwable;
/**
* Allgemeine Kommunikationsvorgaben: Empfänger der internen Benachrichtigung und Aufbewahrungsdauer. Die Empfänger
* stehen nur hier; Besucher und das CMS können keine Empfänger festlegen.
*/
class KommunikationEinstellungen extends Page
{
protected static string|\UnitEnum|null $navigationGroup = 'Kommunikation';
protected static ?string $navigationLabel = 'Einstellungen';
protected static ?int $navigationSort = 3;
protected static ?string $slug = 'kommunikation/einstellungen';
/** @var array<string, mixed>|null */
public ?array $data = [];
public static function canAccess(): bool
{
return CommunicationAccess::inbox();
}
public function getTitle(): string|Htmlable
{
return 'Kommunikation: Einstellungen';
}
public function getSubheading(): string|Htmlable|null
{
return 'Wer bei einer neuen Anfrage benachrichtigt wird und wie lange Anfragen aufbewahrt werden.';
}
public function mount(): void
{
$settings = CommunicationSettings::current();
$this->form->fill([
'recipients' => implode("\n", (array) $settings->recipients),
'retention_months' => $settings->retention_months,
]);
}
public function form(Schema $schema): Schema
{
return $schema
->components([
Section::make('Benachrichtigung')->schema([
Textarea::make('recipients')->label('Empfänger der internen Benachrichtigung')->rows(4)
->helperText('Eine E-Mail-Adresse je Zeile. Die Benachrichtigung nennt nur Kennzeichen und Anliegen, nie Kontaktdaten oder Antworten. Ohne Empfänger werden Anfragen trotzdem gespeichert; der Posteingang weist dann auf die fehlende Benachrichtigung hin.')
->rule(fn (): \Closure => function (string $attribute, mixed $value, \Closure $fail): void {
foreach (self::lines((string) $value) as $address) {
if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
$fail('„'.$address.'“ ist keine gültige E-Mail-Adresse.');
return;
}
}
if (count(self::lines((string) $value)) > 10) {
$fail('Bitte höchstens zehn Empfänger.');
}
}),
]),
Section::make('Weitere Bausteine')->description('Anliegen und der gemeinsame Feldkatalog gehören zu den Formularen. Im Formular-Editor müssen sie nicht geöffnet werden; hier lassen sie sich einsehen und ordnen.')
->visible(fn (): bool => CommunicationAccess::configure())
->collapsed()
->schema([
Actions::make([
Action::make('issues')->label('Anliegen')->url(InquiryIssueResource::getUrl('index'))->color('gray'),
Action::make('fields')->label('Feldkatalog')->url(InquiryFieldResource::getUrl('index'))->color('gray'),
Action::make('groups')->label('Feldgruppen')->url(InquiryFieldGroupResource::getUrl('index'))->color('gray'),
Action::make('entries')->label('Anfrage-Einstiege (ältere Seiten)')->url(InquiryEntryResource::getUrl('index'))->color('gray'),
]),
]),
Section::make('Aufbewahrung')->schema([
TextInput::make('retention_months')->label('Anfragen löschen nach … Monaten')->numeric()->minValue(1)->maxValue(120)
->helperText('Leer: Anfragen werden nicht automatisch gelöscht. Der Befehl „php artisan communication:purge“ löscht Anfragen, die älter sind. Einzelne Anfragen lassen sich jederzeit im Posteingang löschen. Die Dauer ist mit dem Datenschutzkonzept abzustimmen.'),
]),
])
->statePath('data');
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([Action::make('save')->label('Einstellungen speichern')->submit('save')->keyBindings(['mod+s'])])]),
]);
}
public function save(): void
{
$data = $this->form->getState();
CommunicationSettings::current()->update([
'recipients' => self::lines((string) ($data['recipients'] ?? '')),
'retention_months' => filled($data['retention_months'] ?? null) ? (int) $data['retention_months'] : null,
]);
Notification::make()->title('Die Einstellungen sind gespeichert.')->success()->send();
}
protected function getHeaderActions(): array
{
return [
Action::make('test')
->label('Testnachricht senden')
->icon('heroicon-o-envelope')
->color('gray')
->requiresConfirmation()
->modalDescription('Sendet eine Testnachricht an die gespeicherten Empfänger. Sie enthält keine Anfragedaten.')
->action(function (): void {
$recipients = CommunicationSettings::current()->recipientList();
if ($recipients === []) {
Notification::make()->title('Es sind noch keine Empfänger gespeichert.')->warning()->send();
return;
}
try {
Mail::to($recipients)->send(new CommunicationTestMail);
} catch (Throwable $e) {
report($e);
Notification::make()->title('Der Versand ist fehlgeschlagen.')->body($e->getMessage())->danger()->send();
return;
}
Notification::make()->title('Die Testnachricht ist abgesendet.')->body('Der Mailserver hat sie angenommen. Ob sie ankommt, zeigt dein Postfach.')->success()->send();
}),
Action::make('example')
->label('Beispielkonfiguration anlegen')
->icon('heroicon-o-sparkles')
->color('gray')
->visible(fn (): bool => ExampleConfiguration::isEmpty())
->requiresConfirmation()
->modalHeading('Beispielkonfiguration anlegen?')
->modalDescription('Legt Anliegen, Felder, Feldgruppen, vier Anfragevorlagen und fünf Anfrage-Einstiege (Allgemeiner Kontakt, Kurse & Workshops, Schul-AG, Programme & Materialien, Kooperation) an und veröffentlicht sie. Alles lässt sich danach ändern. Das geht nur, solange die Kommunikationsverwaltung noch leer ist.')
->action(function (): void {
try {
app(ExampleConfiguration::class)->install(CommunicationAccess::user());
} catch (RuntimeException $e) {
Notification::make()->title($e->getMessage())->danger()->send();
return;
}
Notification::make()->title('Die Beispielkonfiguration ist angelegt und veröffentlicht.')->success()->send();
$this->redirect(static::getUrl());
}),
];
}
/**
* @return list<string>
*/
private static function lines(string $text): array
{
return array_values(array_unique(array_filter(array_map('trim', preg_split('/[\r\n,;]+/', $text) ?: []), fn (string $line): bool => $line !== '')));
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Filament\Resources\Communication;
use App\Domain\Communication\CommunicationAccess;
use Filament\Resources\Resource;
use Illuminate\Database\Eloquent\Model;
/**
* Gemeinsame Grundlage der Konfigurationsbereiche der Kommunikationsverwaltung: Gruppe „Kommunikation“, Rechte,
* kein Löschen (Einträge werden archiviert, weil Anfragen und Fassungen auf sie verweisen).
*/
abstract class CommunicationResource extends Resource
{
protected static string|\UnitEnum|null $navigationGroup = 'Kommunikation';
public static function canViewAny(): bool
{
return CommunicationAccess::configure();
}
public static function canCreate(): bool
{
return CommunicationAccess::configure();
}
public static function canEdit(Model $record): bool
{
return CommunicationAccess::configure();
}
public static function canView(Model $record): bool
{
return CommunicationAccess::configure();
}
public static function canDelete(Model $record): bool
{
return false;
}
public static function canDeleteAny(): bool
{
return false;
}
}
@@ -0,0 +1,149 @@
<?php
namespace App\Filament\Resources\Communication\Entries;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\InquiryTemplate;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Entries\Pages\EditInquiryEntry;
use App\Filament\Resources\Communication\Entries\Pages\ListInquiryEntries;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Anfrage-Einstiege: die veröffentlichbare Nutzungsvariante einer Anfragevorlage. Sie legen fest, welche Anliegen
* angeboten werden, was vorausgewählt ist, welche Texte erscheinen und ob ein Kompaktformular oder ein mehrstufiger
* Dialog gezeigt wird. Das CMS wählt nur einen veröffentlichten Einstieg aus.
*/
class InquiryEntryResource extends CommunicationResource
{
protected static ?string $model = InquiryEntry::class;
protected static ?string $navigationLabel = 'Anfrage-Einstiege';
protected static ?string $modelLabel = 'Anfrage-Einstieg';
protected static ?string $pluralModelLabel = 'Anfrage-Einstiege';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/einstiege';
protected static ?int $navigationSort = 6;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120)
->helperText('So heißt der Einstieg in der Auswahl im CMS, zum Beispiel „Kurse & Workshops“.'),
Select::make('template_id')->label('Anfragevorlage')->required()->live()
->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all())
->helperText('Die Formularstruktur kommt aus der veröffentlichten Fassung dieser Vorlage und folgt jeder neu veröffentlichten Fassung.'),
Section::make('Angebotene Anliegen')->description('Der Rahmen, in dem Besucher wählen. Ist nur ein Anliegen zugelassen, müssen sie es nicht bestätigen.')->schema([
Select::make('config.allowed_issues')->label('Zugelassene Anliegen')->multiple()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Leer: alle Anliegen der Vorlage.'),
Select::make('config.allowed_subissues')->label('Zugelassene Unteranliegen')->multiple()
->options(function (): array {
$options = [];
foreach (InquiryIssue::tree() as $issue) {
foreach ($issue['children'] as $child) {
$options[$child['key']] = $issue['label'].' › '.$child['label'];
}
}
return $options;
})
->helperText('Leer: alle Unteranliegen der zugelassenen Anliegen.'),
Repeater::make('config.preselect')
->label('Vorauswahl')
->helperText('Zum Beispiel das Kursformat „Schul-AG“. Besucher können die Auswahl ändern.')
->schema([
Select::make('field')->label('Angabe')->required()->live()->searchable()->distinct()
->options(fn (): array => ['anliegen' => 'Anliegen', 'unteranliegen' => 'Unteranliegen'] + InquiryField::query()->offered()->whereIn('type', ['select', 'boolean'])->orderBy('name')->pluck('name', 'key')->all()),
Select::make('value')->label('Wert')->required()
->options(function (Get $get): array {
$field = (string) $get('field');
if ($field === 'anliegen') {
return InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all();
}
if ($field === 'unteranliegen') {
return InquiryIssue::query()->offered()->whereNotNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all();
}
$model = InquiryField::query()->where('key', $field)->first();
return $model === null ? [] : collect($model->optionList())->pluck('label', 'key')->all();
}),
])
->addActionLabel('Vorauswahl hinzufügen')
->itemLabel(fn (array $state): ?string => ($state['field'] ?? null) ? ($state['field'] === 'anliegen' ? 'Anliegen' : ($state['field'] === 'unteranliegen' ? 'Unteranliegen' : InquiryField::query()->where('key', $state['field'])->value('name'))) : null),
]),
Section::make('Darstellung')->schema([
Select::make('config.mode')->label('Formularart')->required()->default('compact')
->options(['compact' => 'Kompaktformular: alle Fragen auf einer Seite', 'wizard' => 'Mehrstufiger Dialog: Schritt für Schritt mit Zusammenfassung'])
->helperText('Beides verwendet dieselbe Vorlage, dieselben Bedingungen und dieselbe Prüfung.'),
Select::make('config.open')->label('Beim Aufruf der Seite')->required()->default('inline')
->options(['inline' => 'Formular direkt anzeigen', 'button' => 'Zunächst nur eine Schaltfläche zeigen, die das Formular öffnet']),
]),
Section::make('Texte dieses Einstiegs')
->description('Überschreibt einzelne Texte der Vorlage. Leer lassen: es gilt der Text der Vorlage. Die Texte werden ausschließlich hier und in der Vorlage gepflegt, nie im CMS.')
->collapsed()
->schema(self::textFields()),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryEntry $record): string => (string) $record?->key)
->visible(fn (?InquiryEntry $record): bool => $record !== null),
]);
}
/**
* @return list<Component>
*/
private static function textFields(): array
{
$fields = [];
foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) {
$field = $multiline
? Textarea::make("config.texts.$key")->rows(2)->maxLength(1500)
: TextInput::make("config.texts.$key")->maxLength(200);
$fields[] = $field->label($label)->placeholder('Text der Vorlage'.($default !== '' ? ': '.$default : ''))->helperText($help);
}
return $fields;
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryEntries::route('/'),
'edit' => EditInquiryEntry::route('/{record}'),
];
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Filament\Resources\Communication\Entries\Pages;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\Publisher;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Validation\ValidationException;
class EditInquiryEntry extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryEntryResource::class;
protected ?bool $hasUnsavedDataChangesAlert = true;
public function getSubheading(): string|Htmlable|null
{
/** @var InquiryEntry $entry */
$entry = $this->getRecord();
if ($entry->archived_at !== null) {
return 'Archiviert.';
}
if ($entry->published_at === null) {
return 'Entwurf. Im CMS lässt sich dieser Einstieg erst nach „Veröffentlichen“ auswählen.';
}
if (! $entry->isLive()) {
return 'Veröffentlicht, wird aber nicht ausgeliefert: Die Anfragevorlage hat keine gültige Fassung.';
}
return 'Veröffentlicht seit '.$entry->published_at->format('d.m.Y').'.'.($entry->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : '');
}
protected function getHeaderActions(): array
{
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->tooltip('Zeigt den zuletzt gespeicherten Entwurf des Einstiegs mit der gültigen Fassung der Vorlage. Es wird nichts gesendet.')
->url(fn (): string => route('communication.preview.entry', $this->getRecord()))
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->requiresConfirmation()
->modalHeading('Anfrage-Einstieg veröffentlichen')
->modalDescription('Speichert den Entwurf und macht ihn wirksam. Alle Seiten, die diesen Einstieg einbinden, zeigen danach den neuen Stand.')
->action(function (): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
try {
app(Publisher::class)->publishEntry($this->getRecord());
} catch (ValidationException $e) {
Notification::make()->title('Der Einstieg lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['config'] ?? []))))->danger()->persistent()->send();
return;
}
Notification::make()->title('Der Einstieg ist veröffentlicht.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
Action::make('withdraw')
->label('Zurückziehen')
->color('gray')
->visible(fn (): bool => $this->getRecord()->published_at !== null)
->requiresConfirmation()
->modalDescription('Der Einstieg wird nicht mehr ausgeliefert; Seiten, die ihn einbinden, zeigen kein Formular. Die Konfiguration bleibt als Entwurf erhalten.')
->action(function (): void {
app(Publisher::class)->withdrawEntry($this->getRecord());
Notification::make()->title('Der Einstieg ist zurückgezogen.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
...$this->archiveActions(),
];
}
protected function archiveNote(): string
{
return 'Der Einstieg wird archiviert und nicht mehr ausgeliefert. Eingegangene Anfragen bleiben unverändert.';
}
protected function archiveAttributes(): array
{
return ['archived_at' => now(), 'published_config' => null, 'published_at' => null];
}
protected function indexUrl(): string
{
return InquiryEntryResource::getUrl('index');
}
protected function mutateFormDataBeforeFill(array $data): array
{
$config = array_merge(InquiryEntry::emptyConfig(), (array) ($data['config'] ?? []));
$preselect = [];
foreach ((array) ($config['defaults'] ?? []) as $field => $value) {
$preselect[] = ['field' => $field, 'value' => $value];
}
$config['preselect'] = $preselect;
$data['config'] = $config;
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$config = (array) ($data['config'] ?? []);
$defaults = [];
foreach (array_values((array) ($config['preselect'] ?? [])) as $row) {
if (is_array($row) && filled($row['field'] ?? null) && filled($row['value'] ?? null)) {
$defaults[(string) $row['field']] = (string) $row['value'];
}
}
$data['config'] = [
'mode' => ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact',
'open' => ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline',
'allowed_issues' => array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')),
'allowed_subissues' => array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')),
'defaults' => $defaults,
'texts' => FormTexts::clean((array) ($config['texts'] ?? [])),
];
return $data;
}
protected function getRedirectUrl(): ?string
{
return null;
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Filament\Resources\Communication\Entries\Pages;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryEntries extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryEntryResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Ein Anfrage-Einstieg ist die Nutzungsvariante einer Anfragevorlage: zugelassene Anliegen, Vorauswahl, Texte und Darstellung. Nur veröffentlichte Einstiege lassen sich im CMS mit dem Widget „Anfrage“ auf einer Seite einbinden. Mehrere Seiten können denselben Einstieg verwenden.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Einstieg anlegen')
->modalHeading('Neuer Anfrage-Einstieg')
->modalDescription('Zugelassene Anliegen, Vorauswahl und Texte legst du danach fest.')
->modalSubmitActionLabel('Einstieg anlegen')
->schema([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120),
Select::make('template_id')->label('Anfragevorlage')->required()
->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all()),
])
->action(function (array $data): void {
$entry = InquiryEntry::query()->create([
'key' => Keys::from($data['name'], InquiryEntry::query()->pluck('key')->all()),
'name' => $data['name'],
'template_id' => $data['template_id'],
'config' => InquiryEntry::emptyConfig(),
]);
Notification::make()->title('Der Einstieg ist angelegt.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $entry]));
}),
];
}
protected function catalogRows(): array
{
$rows = [];
foreach (InquiryEntry::query()->with('template.publishedVersion')->orderBy('name')->get() as $entry) {
$url = InquiryEntryResource::getUrl('edit', ['record' => $entry]);
$archived = $entry->archived_at !== null;
$live = $entry->isLive();
$config = (array) ($entry->published_config ?? $entry->config);
$mode = ($config['mode'] ?? 'compact') === 'wizard' ? 'Mehrstufiger Dialog' : 'Kompaktformular';
$rows[] = [
'schluessel' => 'e'.$entry->id,
'titel' => $entry->name,
'meta' => 'Anfrage-Einstieg · '.$mode.' · Vorlage „'.$entry->template->name.'“',
'text' => '',
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
$archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($live
? ['label' => 'Veröffentlicht', 'ton' => 'gut']
: ($entry->published_at !== null ? ['label' => 'Veröffentlicht, aber Vorlage nicht gültig', 'ton' => 'achtung'] : ['label' => 'Entwurf', 'ton' => 'offen'])),
$entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null,
])),
'zustand' => [$archived ? 'archiviert' : ($live ? 'veroeffentlicht' : 'entwurf'), ...($entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['aenderungen'] : [])],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Zustand',
'veroeffentlicht' => 'Veröffentlicht',
'entwurf' => 'Entwurf',
'aenderungen' => 'Mit unveröffentlichten Änderungen',
'archiviert' => 'Archiviert',
];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung';
}
protected function einheit(): array
{
return ['Anfrage-Einstieg', 'Anfrage-Einstiege'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfrage-Einstiege', 'text' => 'Mit „Einstieg anlegen“ oben entsteht der erste Einstieg. Dazu braucht es eine veröffentlichte Anfragevorlage.'];
}
}
@@ -0,0 +1,126 @@
<?php
namespace App\Filament\Resources\Communication\Fields;
use App\Domain\Communication\FieldPurpose;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Fields\Pages\EditInquiryField;
use App\Filament\Resources\Communication\Fields\Pages\ListInquiryFields;
use Closure;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Feldkatalog: wiederverwendbare Eingabefelder. Ein Feld wird einmal definiert und in beliebig vielen Feldgruppen und
* Anfragevorlagen verwendet.
*/
class InquiryFieldResource extends CommunicationResource
{
protected static ?string $model = InquiryField::class;
protected static ?string $navigationLabel = 'Feldkatalog';
protected static ?string $modelLabel = 'Feld';
protected static ?string $pluralModelLabel = 'Feldkatalog';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/felder';
protected static ?int $navigationSort = 3;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
/**
* @return list<Component>
*/
public static function optionsFields(): array
{
return [
Repeater::make('options')
->label('Auswahlwerte')
->schema([
Hidden::make('key'),
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120),
])
->minItems(1)
->reorderableWithButtons()
->addActionLabel('Auswahlwert hinzufügen')
->itemLabel(fn (array $state): ?string => $state['label'] ?? null)
->helperText('Reihenfolge wie hier. Jeder Wert erhält eine feste interne Kennung; eine Umbenennung ändert sie nicht und beschädigt keine Anfragen.')
->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false)
->required(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false),
];
}
public static function form(Schema $schema): Schema
{
return $schema->components([
Section::make('Feld')->schema([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)
->helperText('Nur für die Verwaltung, zum Beispiel „Postleitzahl (Einrichtung)“.'),
TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200)
->helperText('So heißt das Feld im Formular.'),
Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600)
->helperText('Steht unter der Beschriftung.'),
Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live()
->disabled(fn (?InquiryField $record): bool => $record !== null)
->dehydrated(fn (?InquiryField $record): bool => $record === null)
->helperText('Nach dem Anlegen nicht mehr änderbar, weil Bedingungen und Gruppen darauf aufbauen.'),
...self::optionsFields(),
TextInput::make('settings.max_length')->label('Höchste Textlänge')->numeric()->minValue(1)->maxValue(8000)
->visible(fn (Get $get): bool => in_array($get('type'), ['text', 'textarea'], true))
->helperText('Leer: Vorgabe (200 Zeichen einzeilig, 4000 mehrzeilig).'),
TextInput::make('settings.min')->label('Kleinster Wert')->numeric()
->visible(fn (Get $get): bool => $get('type') === 'number'),
TextInput::make('settings.max')->label('Größter Wert')->numeric()
->visible(fn (Get $get): bool => $get('type') === 'number'),
Select::make('purpose')->label('Verwendung in der Anfrageübersicht')->options(FieldPurpose::options())->placeholder('Keine besondere Verwendung')
->helperText('Welche Angabe der Posteingang als Name, E-Mail-Adresse oder Nachricht der Anfrage zeigt. Jede Vorlage braucht ein Feld „E-Mail-Adresse für Rückfragen“.')
->rule(fn (Get $get): Closure => function (string $attribute, mixed $value, Closure $fail) use ($get): void {
$type = FieldType::tryFrom((string) $get('type'));
if ($value !== null && $type !== null && ! in_array($type, FieldPurpose::from($value)->types(), true)) {
$fail('Diese Verwendung passt nicht zum Feldtyp „'.$type->label().'“.');
}
}),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryField $record): string => (string) $record?->key)
->visible(fn (?InquiryField $record): bool => $record !== null)
->helperText('Ändert sich nie.'),
Toggle::make('active')->label('Zur Verwendung anbieten')
->helperText('Ausgeschaltet kann das Feld in keiner neuen Fassung einer Vorlage verwendet werden; bestehende Fassungen und Anfragen bleiben unverändert.'),
]),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryFields::route('/'),
'edit' => EditInquiryField::route('/{record}'),
];
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Filament\Resources\Communication\Fields\Pages;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Resources\Pages\EditRecord;
class EditInquiryField extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryFieldResource::class;
protected function getHeaderActions(): array
{
return $this->archiveActions();
}
protected function archiveNote(): string
{
return 'Das Feld kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.';
}
protected function indexUrl(): string
{
return InquiryFieldResource::getUrl('index');
}
protected function mutateFormDataBeforeSave(array $data): array
{
/** @var InquiryField $record */
$record = $this->getRecord();
$type = $record->type;
$data['options'] = $type->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null;
$settings = array_filter((array) ($data['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== '');
$data['settings'] = match ($type) {
FieldType::Text, FieldType::Textarea => array_intersect_key($settings, ['max_length' => true]),
FieldType::Number => array_intersect_key($settings, ['min' => true, 'max' => true]),
default => [],
};
return $data;
}
protected function getRedirectUrl(): ?string
{
return InquiryFieldResource::getUrl('index');
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Filament\Resources\Communication\Fields\Pages;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryFields extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryFieldResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Der Feldkatalog enthält alle Eingabefelder, die Anfragevorlagen verwenden können. Ein Feld wie „Postleitzahl“ oder „Telefonnummer“ wird einmal angelegt und überall wiederverwendet. Felder werden nie gelöscht, nur deaktiviert oder archiviert.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Feld anlegen')
->modalHeading('Neues Feld')
->modalDescription('Weitere Angaben wie Hilfetext, Grenzen oder die Verwendung in der Anfrageübersicht legst du danach fest.')
->modalSubmitActionLabel('Feld anlegen')
->schema([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120),
TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200),
Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live(),
...InquiryFieldResource::optionsFields(),
])
->action(function (array $data): void {
$field = InquiryField::query()->create([
'key' => Keys::from($data['name'], InquiryField::query()->pluck('key')->all()),
'name' => $data['name'],
'label' => $data['label'],
'type' => $data['type'],
'options' => FieldType::from($data['type'])->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null,
]);
Notification::make()->title('Das Feld ist angelegt.')->success()->send();
$this->redirect(InquiryFieldResource::getUrl('edit', ['record' => $field]));
}),
];
}
protected function catalogRows(): array
{
$usage = [];
foreach (InquiryFieldGroup::query()->get() as $group) {
foreach ($group->itemList() as $item) {
$usage[$item['field']] = ($usage[$item['field']] ?? 0) + 1;
}
}
$rows = [];
foreach (InquiryField::query()->orderBy('name')->get() as $field) {
$url = InquiryFieldResource::getUrl('edit', ['record' => $field]);
$state = $field->archived_at !== null ? 'archiviert' : ($field->active ? 'aktiv' : 'inaktiv');
$used = $usage[$field->key] ?? 0;
$rows[] = [
'schluessel' => 'f'.$field->id,
'titel' => $field->name,
'meta' => $field->type->label().' · '.$field->key,
'text' => $field->label,
'suchtext' => $field->key.' '.$field->label,
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
['label' => $used === 0 ? 'In keiner Feldgruppe' : ($used === 1 ? 'In 1 Feldgruppe' : "In $used Feldgruppen"), 'ton' => 'neutral'],
$field->purpose !== null ? ['label' => $field->purpose->label(), 'ton' => 'neutral'] : null,
])),
'zustand' => [$state, 'typ_'.$field->type->value],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung, Beschriftung oder Kennung';
}
protected function einheit(): array
{
return ['Feld', 'Felder'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Felder', 'text' => 'Mit „Feld anlegen“ oben entsteht das erste Feld, zum Beispiel „E-Mail-Adresse“.'];
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Filament\Resources\Communication\Groups;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Groups\Pages\EditInquiryFieldGroup;
use App\Filament\Resources\Communication\Groups\Pages\ListInquiryFieldGroups;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Feldgruppen: fachliche Zusammenstellung von Feldern in fester Reihenfolge, die mehrere Anfragevorlagen verwenden.
*/
class InquiryFieldGroupResource extends CommunicationResource
{
protected static ?string $model = InquiryFieldGroup::class;
protected static ?string $navigationLabel = 'Feldgruppen';
protected static ?string $modelLabel = 'Feldgruppe';
protected static ?string $pluralModelLabel = 'Feldgruppen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/feldgruppen';
protected static ?int $navigationSort = 4;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)
->helperText('Nur für die Verwaltung, zum Beispiel „Kindergruppe“.'),
TextInput::make('label')->label('Überschrift im Formular (optional)')->maxLength(200)
->helperText('Leer: die fachliche Bezeichnung.'),
Textarea::make('description')->label('Erläuterung im Formular (optional)')->rows(2)->maxLength(600),
Repeater::make('items')
->label('Felder der Gruppe')
->schema([
Select::make('field')->label('Feld')->required()->searchable()->distinct()
->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->get()->mapWithKeys(
fn (InquiryField $field): array => [$field->key => $field->name.' ('.$field->type->label().')']
)->all()),
Toggle::make('required')->label('Pflichtfeld')->default(false)
->helperText('Eine Vorlage kann ein Feld zusätzlich unter einer Bedingung zur Pflicht machen.'),
])
->minItems(1)
->reorderableWithButtons()
->addActionLabel('Feld hinzufügen')
->itemLabel(fn (array $state): ?string => InquiryField::query()->where('key', $state['field'] ?? '')->value('name'))
->helperText('Die Reihenfolge hier ist die Reihenfolge im Formular.'),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryFieldGroup $record): string => (string) $record?->key)
->visible(fn (?InquiryFieldGroup $record): bool => $record !== null),
Toggle::make('active')->label('Zur Verwendung anbieten'),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryFieldGroups::route('/'),
'edit' => EditInquiryFieldGroup::route('/{record}'),
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Filament\Resources\Communication\Groups\Pages;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Resources\Pages\EditRecord;
class EditInquiryFieldGroup extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryFieldGroupResource::class;
protected function getHeaderActions(): array
{
return $this->archiveActions();
}
protected function archiveNote(): string
{
return 'Die Gruppe kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.';
}
protected function indexUrl(): string
{
return InquiryFieldGroupResource::getUrl('index');
}
protected function getRedirectUrl(): ?string
{
return InquiryFieldGroupResource::getUrl('index');
}
}
@@ -0,0 +1,139 @@
<?php
namespace App\Filament\Resources\Communication\Groups\Pages;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryFieldGroups extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryFieldGroupResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Feldgruppen fassen Felder fachlich zusammen, zum Beispiel „Kontaktinformationen“ oder „Kindergruppe“. Eine Gruppe wird in beliebig vielen Anfragevorlagen verwendet; Reihenfolge und Pflichtangaben pflegst du hier einmal.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Feldgruppe anlegen')
->modalHeading('Neue Feldgruppe')
->modalDescription('Die Felder legst du danach auf der Seite der Gruppe fest.')
->modalSubmitActionLabel('Feldgruppe anlegen')
->schema([TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)])
->action(function (array $data): void {
$group = InquiryFieldGroup::query()->create([
'key' => Keys::from($data['name'], InquiryFieldGroup::query()->pluck('key')->all()),
'name' => $data['name'],
'items' => [],
'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10,
]);
Notification::make()->title('Die Feldgruppe ist angelegt.')->success()->send();
$this->redirect(InquiryFieldGroupResource::getUrl('edit', ['record' => $group]));
}),
];
}
public function moveGroup(int $id, string $direction): void
{
$group = InquiryFieldGroup::query()->findOrFail($id);
$all = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get()->values();
$index = $all->search(fn (InquiryFieldGroup $item): bool => $item->id === $group->id);
$target = $direction === 'up' ? $index - 1 : $index + 1;
if ($index === false || $target < 0 || $target >= $all->count()) {
return;
}
$order = $all->all();
[$order[$index], $order[$target]] = [$order[$target], $order[$index]];
foreach ($order as $position => $item) {
$item->forceFill(['sort_order' => ($position + 1) * 10])->save();
}
}
protected function catalogRows(): array
{
$templates = InquiryTemplate::query()->get(['id', 'draft']);
$names = InquiryField::query()->pluck('name', 'key');
$groups = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get();
$rows = [];
foreach ($groups as $i => $group) {
$url = InquiryFieldGroupResource::getUrl('edit', ['record' => $group]);
$state = $group->archived_at !== null ? 'archiviert' : ($group->active ? 'aktiv' : 'inaktiv');
$used = $templates->filter(function (InquiryTemplate $template) use ($group): bool {
foreach ((array) ($template->draft['steps'] ?? []) as $step) {
foreach ((array) ($step['items'] ?? []) as $item) {
if (($item['group'] ?? null) === $group->key) {
return true;
}
}
}
return false;
})->count();
$fieldNames = array_map(fn (array $item): string => (string) ($names[$item['field']] ?? $item['field']), $group->itemList());
$rows[] = [
'schluessel' => 'g'.$group->id,
'titel' => $group->name,
'meta' => 'Feldgruppe · '.count($fieldNames).' '.(count($fieldNames) === 1 ? 'Feld' : 'Felder'),
'text' => implode(', ', $fieldNames),
'symbol' => 'modul',
'url' => $url,
'chips' => [
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
['label' => $used === 0 ? 'In keiner Vorlage' : ($used === 1 ? 'In 1 Vorlage' : "In $used Vorlagen"), 'ton' => 'neutral'],
],
'zustand' => [$state],
'aktionen' => [
['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'],
...($i > 0 ? [['label' => 'Nach oben', 'wire' => "moveGroup({$group->id}, 'up')"]] : []),
...($i < $groups->count() - 1 ? [['label' => 'Nach unten', 'wire' => "moveGroup({$group->id}, 'down')"]] : []),
],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Feldname';
}
protected function einheit(): array
{
return ['Feldgruppe', 'Feldgruppen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Feldgruppen', 'text' => 'Mit „Feldgruppe anlegen“ oben entsteht die erste Gruppe, zum Beispiel „Kontaktinformationen“.'];
}
}
@@ -0,0 +1,144 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\Inquiry;
use App\Filament\Resources\Communication\Inquiries\Pages\ListInquiries;
use App\Filament\Resources\Communication\Inquiries\Pages\ViewInquiry;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Zentraler Posteingang aller Anfragen (ADR-60). Anfragen enthalten personenbezogene Daten: Zugriff nur für
* Kundenbetreuung und Systemverwaltung.
*/
class InquiryResource extends Resource
{
protected static ?string $model = Inquiry::class;
protected static string|\UnitEnum|null $navigationGroup = 'Kommunikation';
protected static ?string $navigationLabel = 'Anfragen';
protected static ?string $modelLabel = 'Anfrage';
protected static ?string $pluralModelLabel = 'Anfragen';
protected static ?string $recordTitleAttribute = 'reference';
protected static ?string $slug = 'anfragen';
protected static ?int $navigationSort = 1;
public static function canViewAny(): bool
{
return CommunicationAccess::inbox();
}
public static function canView(Model $record): bool
{
return CommunicationAccess::inbox();
}
public static function canCreate(): bool
{
return false;
}
public static function canEdit(Model $record): bool
{
return false;
}
public static function canDelete(Model $record): bool
{
return false;
}
public static function canDeleteAny(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
if (! CommunicationAccess::inbox()) {
return null;
}
$new = Inquiry::query()->where('status', 'neu')->count();
return $new > 0 ? (string) $new : null;
}
public static function getNavigationBadgeTooltip(): ?string
{
return 'Neue Anfragen';
}
public static function infolist(Schema $schema): Schema
{
return $schema->components([
Section::make('Ansprechpartner')->columns(2)->schema([
TextEntry::make('contact_name')->label('Name')->placeholder('Nicht angegeben'),
TextEntry::make('organisation')->label('Organisation')->placeholder('Nicht angegeben'),
TextEntry::make('contact_email')->label('E-Mail-Adresse')->placeholder('Nicht angegeben')->copyable(),
TextEntry::make('contact_phone')->label('Telefon')->placeholder('Nicht angegeben'),
]),
Section::make('Anliegen')->columns(2)->schema([
TextEntry::make('issue')->label('Anliegen')->state(fn (Inquiry $record): string => $record->issueTitle() ?: 'Nicht erfragt'),
TextEntry::make('status')->label('Bearbeitungsstatus')->badge()
->formatStateUsing(fn ($state): string => $state->label())
->color(fn ($state): string => $state->color()),
TextEntry::make('channel')->label('Eingegangen über')->state(fn (Inquiry $record): string => $record->channelTitle()),
TextEntry::make('source_path')->label('Quellseite')->placeholder('Unbekannt'),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i'),
TextEntry::make('reference')->label('Kennzeichen')->copyable(),
TextEntry::make('version')->label('Formularfassung')
->state(fn (Inquiry $record): string => 'Vorlage „'.($record->templateVersion->template->name ?? '').'“, Fassung '.($record->templateVersion->version ?? '')),
TextEntry::make('notification')->label('Benachrichtigung')
->state(fn (Inquiry $record): string => $record->notified_at !== null ? 'Gesendet am '.$record->notified_at->format('d.m.Y H:i') : ($record->notification_error ?: 'Noch nicht gesendet'))
->color(fn (Inquiry $record): ?string => $record->notified_at === null && $record->notification_error !== null ? 'danger' : null),
]),
Section::make('Antworten')->schema([
ViewEntry::make('answers')->hiddenLabel()->view('filament.communication.answers'),
]),
Section::make('Nachricht')->visible(fn (Inquiry $record): bool => filled($record->message))->schema([
TextEntry::make('message')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']),
]),
Section::make('Interne Notizen')->schema([
RepeatableEntry::make('notes')->hiddenLabel()->placeholder('Noch keine Notizen.')->schema([
TextEntry::make('body')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']),
TextEntry::make('meta')->hiddenLabel()->color('gray')
->state(fn ($record): string => ($record->author->name ?? 'Unbekannt').' · '.$record->created_at->format('d.m.Y H:i')),
]),
]),
]);
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('reference')->label('Kennzeichen')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiries::route('/'),
'view' => ViewInquiry::route('/{record}'),
];
}
}
@@ -0,0 +1,128 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries\Pages;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryStatus;
use App\Filament\Resources\Communication\Inquiries\InquiryResource;
use App\Filament\Support\Bestand;
use App\Filament\Support\ListsCatalog;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Str;
use Livewire\Attributes\Url;
class ListInquiries extends ListRecords
{
use ListsCatalog {
bestand as protected baseBestand;
}
protected static string $resource = InquiryResource::class;
#[Url(as: 'anliegen', except: 'alle')]
public string $anliegen = 'alle';
#[Url(as: 'sortierung', except: 'neu')]
public string $sortierung = 'neu';
public function getSubheading(): string|Htmlable|null
{
return 'Alle eingegangenen Anfragen aus allen Anfrage-Einstiegen. Der Status wird von Hand gesetzt; Notizen sind nur intern sichtbar.';
}
protected function bestandFilterEigenschaften(): array
{
return ['suche', 'zustand', 'anliegen', 'sortierung'];
}
public function resetFilters(): void
{
$this->suche = '';
$this->zustand = 'alle';
$this->anliegen = 'alle';
$this->sortierung = 'neu';
$this->bestandGrenze = Bestand::SCHRITT;
}
public function bestand(): array
{
$b = $this->baseBestand();
$issues = Inquiry::query()->whereNotNull('issue_key')->select('issue_key', 'issue_label')->distinct()->orderBy('issue_label')->pluck('issue_label', 'issue_key')->all();
$b['filter'][] = ['eigenschaft' => 'anliegen', 'label' => 'Anliegen', 'vorgabe' => 'alle', 'optionen' => ['alle' => 'Alle Anliegen'] + $issues];
$b['sortierung'] = ['eigenschaft' => 'sortierung', 'label' => 'Sortierung', 'optionen' => ['neu' => 'Neueste zuerst', 'alt' => 'Älteste zuerst', 'name' => 'Name', 'status' => 'Status']];
return $b;
}
protected function catalogRows(): array
{
$query = Inquiry::query()->with(['entry', 'templateVersion.template']);
if ($this->anliegen !== 'alle') {
$query->where('issue_key', $this->anliegen);
}
$inquiries = match ($this->sortierung) {
'alt' => $query->orderBy('created_at')->orderBy('id')->get(),
'name' => $query->get()->sortBy(fn (Inquiry $i): string => mb_strtolower($i->contactTitle()), SORT_NATURAL)->values(),
'status' => $query->get()->sortBy(fn (Inquiry $i): string => array_search($i->status, InquiryStatus::cases(), true).'-'.(PHP_INT_MAX - $i->created_at->getTimestamp()))->values(),
default => $query->orderByDesc('created_at')->orderByDesc('id')->get(),
};
$rows = [];
foreach ($inquiries as $inquiry) {
$url = InquiryResource::getUrl('view', ['record' => $inquiry]);
$failed = $inquiry->notified_at === null && $inquiry->notification_error !== null;
$rows[] = [
'schluessel' => 'q'.$inquiry->id,
'titel' => $inquiry->contactTitle().($inquiry->organisation ? ' · '.$inquiry->organisation : ''),
'meta' => $inquiry->created_at->format('d.m.Y H:i').' · '.($inquiry->issueTitle() ?: 'Ohne Anliegen').' · '.$inquiry->channelTitle(),
'text' => Str::limit((string) $inquiry->message, 180),
'suchtext' => implode(' ', array_filter([$inquiry->contact_email, $inquiry->reference, $inquiry->contact_phone])),
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
['label' => $inquiry->status->label(), 'ton' => match ($inquiry->status) {
InquiryStatus::Neu => 'offen',
InquiryStatus::RueckfrageOffen => 'achtung',
InquiryStatus::Erledigt => 'gut',
default => 'neutral',
}],
$failed ? ['label' => 'Benachrichtigung fehlgeschlagen', 'ton' => 'achtung'] : null,
])),
'zustand' => array_values(array_filter([$inquiry->status->value, $inquiry->status !== InquiryStatus::Erledigt ? 'offen' : null, $failed ? 'mailfehler' : null])),
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Status',
'offen' => 'Nicht erledigt',
...InquiryStatus::options(),
'mailfehler' => 'Benachrichtigung fehlgeschlagen',
];
}
protected function suchPlatzhalter(): string
{
return 'Name, E-Mail, Organisation, Nachricht oder Kennzeichen';
}
protected function einheit(): array
{
return ['Anfrage', 'Anfragen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfragen', 'text' => 'Sobald jemand über einen Anfrage-Einstieg eine Anfrage sendet, erscheint sie hier.'];
}
}
@@ -0,0 +1,106 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries\Pages;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryNote;
use App\Domain\Communication\InquiryStatus;
use App\Filament\Resources\Communication\Inquiries\InquiryResource;
use App\Jobs\SendInquiryNotification;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Contracts\Support\Htmlable;
class ViewInquiry extends ViewRecord
{
protected static string $resource = InquiryResource::class;
public function getTitle(): string|Htmlable
{
/** @var Inquiry $inquiry */
$inquiry = $this->getRecord();
return $inquiry->contactTitle();
}
public function getSubheading(): string|Htmlable|null
{
/** @var Inquiry $inquiry */
$inquiry = $this->getRecord();
return 'Anfrage '.$inquiry->reference.' vom '.$inquiry->created_at->format('d.m.Y H:i');
}
protected function getHeaderActions(): array
{
return [
Action::make('status')
->label('Status ändern')
->icon('heroicon-o-arrow-path')
->modalHeading('Bearbeitungsstatus')
->modalSubmitActionLabel('Status speichern')
->fillForm(fn (): array => ['status' => $this->getRecord()->status->value])
->schema([Select::make('status')->label('Neuer Status')->options(InquiryStatus::options())->required()])
->action(function (array $data): void {
$this->getRecord()->forceFill(['status' => $data['status']])->save();
Notification::make()->title('Der Status ist geändert.')->success()->send();
$this->refreshFormData(['status']);
}),
Action::make('note')
->label('Notiz hinzufügen')
->icon('heroicon-o-pencil-square')
->color('gray')
->modalHeading('Interne Notiz')
->modalDescription('Nur für das Team sichtbar, nie für den Anfragenden.')
->modalSubmitActionLabel('Notiz speichern')
->schema([Textarea::make('body')->label('Notiz')->required()->rows(4)->maxLength(4000)])
->action(function (array $data): void {
InquiryNote::query()->create([
'inquiry_id' => $this->getRecord()->id,
'user_id' => CommunicationAccess::user()?->id,
'body' => $data['body'],
]);
$this->getRecord()->load('notes');
Notification::make()->title('Die Notiz ist gespeichert.')->success()->send();
$this->redirect(InquiryResource::getUrl('view', ['record' => $this->getRecord()]));
}),
Action::make('resend')
->label('Benachrichtigung erneut senden')
->icon('heroicon-o-envelope')
->color('gray')
->visible(fn (): bool => $this->getRecord()->notified_at === null)
->requiresConfirmation()
->modalDescription('Sendet die interne Benachrichtigung an die in den Einstellungen hinterlegten Empfänger noch einmal.')
->action(function (): void {
SendInquiryNotification::dispatchSync($this->getRecord()->id, InquiryResource::getUrl('view', ['record' => $this->getRecord()]));
$inquiry = $this->getRecord()->fresh();
if ($inquiry->notified_at !== null) {
Notification::make()->title('Die Benachrichtigung ist gesendet.')->success()->send();
} else {
Notification::make()->title('Die Benachrichtigung ist weiterhin fehlgeschlagen.')->body((string) $inquiry->notification_error)->danger()->send();
}
$this->redirect(InquiryResource::getUrl('view', ['record' => $inquiry]));
}),
Action::make('erase')
->label('Anfrage löschen')
->icon('heroicon-o-trash')
->color('danger')
->visible(fn (): bool => CommunicationAccess::erase())
->requiresConfirmation()
->modalHeading('Anfrage endgültig löschen?')
->modalDescription('Die Anfrage mit allen Antworten und Notizen wird unwiderruflich gelöscht, zum Beispiel auf Wunsch der betroffenen Person. Das lässt sich nicht rückgängig machen.')
->action(function (): void {
$this->getRecord()->delete();
Notification::make()->title('Die Anfrage ist gelöscht.')->success()->send();
$this->redirect(InquiryResource::getUrl('index'));
}),
];
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Filament\Resources\Communication\Issues;
use App\Domain\Communication\InquiryIssue;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Issues\Pages\EditInquiryIssue;
use App\Filament\Resources\Communication\Issues\Pages\ListInquiryIssues;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Anliegen und Unteranliegen: warum ein Besucher Kontakt aufnimmt. Sie steuern die Besucherführung und die bedingte
* Anzeige von Feldern.
*/
class InquiryIssueResource extends CommunicationResource
{
protected static ?string $model = InquiryIssue::class;
protected static ?string $navigationLabel = 'Anliegen';
protected static ?string $modelLabel = 'Anliegen';
protected static ?string $pluralModelLabel = 'Anliegen';
protected static ?string $recordTitleAttribute = 'label';
protected static ?string $slug = 'kommunikation/anliegen';
protected static ?int $navigationSort = 2;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120)
->helperText('So sieht es der Besucher. Die Bezeichnung darf sich ändern; die fachliche Identität bleibt.'),
Textarea::make('description')->label('Beschreibung (optional)')->rows(3)->maxLength(300)
->helperText('Ein Satz unter der Bezeichnung in der Auswahl.'),
Placeholder::make('hierarchy')->label('Einordnung')->content(
fn (?InquiryIssue $record): string => $record?->parent !== null ? 'Unteranliegen von „'.$record->parent->label.'“' : 'Anliegen auf oberster Ebene'
),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryIssue $record): string => (string) $record?->key)
->helperText('Wird beim Anlegen vergeben und ändert sich nie. Bereits eingegangene Anfragen und Bedingungen beziehen sich darauf.'),
Toggle::make('active')->label('Besuchern anbieten')
->helperText('Ausgeschaltet erscheint das Anliegen in keiner neuen Fassung einer Vorlage; bestehende Fassungen und Anfragen bleiben unverändert.'),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('label')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryIssues::route('/'),
'edit' => EditInquiryIssue::route('/{record}'),
];
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Filament\Resources\Communication\Issues\Pages;
use App\Domain\Communication\InquiryIssue;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
class EditInquiryIssue extends EditRecord
{
protected static string $resource = InquiryIssueResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('archive')
->label('Archivieren')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->requiresConfirmation()
->modalDescription('Das Anliegen wird in neuen Fassungen von Vorlagen nicht mehr angeboten. Bereits eingegangene Anfragen und veröffentlichte Fassungen bleiben unverändert.')
->action(function (): void {
/** @var InquiryIssue $issue */
$issue = $this->getRecord();
$issue->forceFill(['archived_at' => now(), 'active' => false])->save();
foreach ($issue->children as $child) {
$child->forceFill(['archived_at' => $child->archived_at ?? now(), 'active' => false])->save();
}
Notification::make()->title('Archiviert.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('index'));
}),
Action::make('restore')
->label('Wiederherstellen')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at !== null)
->action(function (): void {
$this->getRecord()->forceFill(['archived_at' => null])->save();
Notification::make()->title('Wiederhergestellt. Das Anliegen ist weiterhin deaktiviert, bis es eingeschaltet wird.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
];
}
protected function getRedirectUrl(): ?string
{
return InquiryIssueResource::getUrl('index');
}
}
@@ -0,0 +1,143 @@
<?php
namespace App\Filament\Resources\Communication\Issues\Pages;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryIssues extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryIssueResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Ein Anliegen beschreibt, weshalb Besucher Kontakt aufnehmen. Unteranliegen verfeinern es. Welche Anliegen ein Formular anbietet und welche Felder dazu erscheinen, legst du in den Anfragevorlagen und Anfrage-Einstiegen fest. Anliegen werden nie gelöscht, nur deaktiviert oder archiviert.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Anliegen anlegen')
->modalHeading('Neues Anliegen')
->modalDescription('Bezeichnung und Einordnung genügen. Die interne Kennung wird einmalig vergeben.')
->modalSubmitActionLabel('Anliegen anlegen')
->schema([
Select::make('parent_id')->label('Einordnung')
->options(fn (): array => InquiryIssue::query()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'id')->all())
->placeholder('Anliegen auf oberster Ebene')
->helperText('Alternativ als Unteranliegen eines bestehenden Anliegens.'),
TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (optional)')->rows(2)->maxLength(300),
])
->action(function (array $data): void {
$issue = InquiryIssue::query()->create([
'parent_id' => $data['parent_id'] ?? null,
'key' => Keys::from($data['label'], InquiryIssue::query()->pluck('key')->all()),
'label' => $data['label'],
'description' => $data['description'] ?? null,
'sort_order' => ((int) InquiryIssue::query()->where('parent_id', $data['parent_id'] ?? null)->max('sort_order')) + 10,
]);
Notification::make()->title('Das Anliegen ist angelegt.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $issue]));
}),
];
}
/** Ein Anliegen vor oder hinter seinem Nachbarn derselben Ebene einordnen. */
public function moveIssue(int $id, string $direction): void
{
$issue = InquiryIssue::query()->findOrFail($id);
$siblings = InquiryIssue::query()->where('parent_id', $issue->parent_id)->orderBy('sort_order')->orderBy('id')->get()->values();
$index = $siblings->search(fn (InquiryIssue $item): bool => $item->id === $issue->id);
$target = $direction === 'up' ? $index - 1 : $index + 1;
if ($index === false || $target < 0 || $target >= $siblings->count()) {
return;
}
$order = $siblings->all();
[$order[$index], $order[$target]] = [$order[$target], $order[$index]];
foreach ($order as $position => $item) {
$item->forceFill(['sort_order' => ($position + 1) * 10])->save();
}
}
protected function catalogRows(): array
{
$all = InquiryIssue::query()->orderBy('sort_order')->orderBy('id')->get();
$children = $all->whereNotNull('parent_id')->groupBy('parent_id');
$rows = [];
$tops = $all->whereNull('parent_id')->values();
$row = function (InquiryIssue $issue, ?InquiryIssue $parent, int $position, int $count) use (&$rows): void {
$url = InquiryIssueResource::getUrl('edit', ['record' => $issue]);
$state = $issue->archived_at !== null ? 'archiviert' : ($issue->active ? 'aktiv' : 'inaktiv');
$rows[] = [
'schluessel' => 'i'.$issue->id,
'titel' => ($parent !== null ? '↳ ' : '').$issue->label,
'meta' => $parent !== null ? 'Unteranliegen von „'.$parent->label.'“' : 'Anliegen',
'text' => (string) ($issue->description ?? ''),
'symbol' => 'modul',
'url' => $url,
'chips' => [
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
],
'zustand' => [$state],
'aktionen' => [
['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'],
...($position > 0 ? [['label' => 'Nach oben', 'wire' => "moveIssue({$issue->id}, 'up')"]] : []),
...($position < $count - 1 ? [['label' => 'Nach unten', 'wire' => "moveIssue({$issue->id}, 'down')"]] : []),
],
];
};
foreach ($tops as $i => $top) {
$row($top, null, $i, $tops->count());
$kids = ($children[$top->id] ?? collect())->values();
foreach ($kids as $j => $child) {
$row($child, $top, $j, $kids->count());
}
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Beschreibung';
}
protected function einheit(): array
{
return ['Anliegen', 'Anliegen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anliegen', 'text' => 'Mit „Anliegen anlegen“ oben entsteht das erste Anliegen, zum Beispiel „Kurse & Workshops“. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Communication\Templates;
use App\Domain\Communication\InquiryTemplate;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Templates\Pages\EditInquiryTemplate;
use App\Filament\Resources\Communication\Templates\Pages\ListInquiryTemplates;
use App\Filament\Resources\Communication\Templates\RelationManagers\VersionsRelationManager;
use App\Filament\Support\TemplateEditor;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Formulare & Befragungen (Anfragevorlagen): ein vollständiger fachlicher Anfrageprozess, bearbeitet im Formular-Editor (ADR-61). Der Entwurf ist frei bearbeitbar; wirksam wird nur eine
* bewusst veröffentlichte, unveränderliche Fassung.
*/
class InquiryTemplateResource extends CommunicationResource
{
protected static ?string $model = InquiryTemplate::class;
protected static ?string $navigationLabel = 'Formulare & Befragungen';
protected static ?string $modelLabel = 'Formular';
protected static ?string $pluralModelLabel = 'Formulare & Befragungen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/vorlagen';
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
return $schema->components(TemplateEditor::schema($schema->getRecord()?->getKey()));
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getRelations(): array
{
return [VersionsRelationManager::class];
}
public static function getPages(): array
{
return [
'index' => ListInquiryTemplates::route('/'),
'edit' => EditInquiryTemplate::route('/{record}'),
];
}
}
@@ -0,0 +1,204 @@
<?php
namespace App\Filament\Resources\Communication\Templates\Pages;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use App\Domain\Communication\TemplateCompiler;
use App\Domain\Communication\TemplateDraft;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Schemas\Components\Text;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Validation\ValidationException;
class EditInquiryTemplate extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryTemplateResource::class;
protected Width|string|null $maxContentWidth = Width::Full;
protected ?bool $hasUnsavedDataChangesAlert = true;
public function getSubheading(): string|Htmlable|null
{
/** @var InquiryTemplate $template */
$template = $this->getRecord();
if ($template->archived_at !== null) {
return 'Archiviert.';
}
if (! $template->isPublished()) {
return 'Noch nicht veröffentlicht. Besucher sehen dieses Formular erst nach „Veröffentlichen“.';
}
$version = $template->publishedVersion;
return 'Gültig ist Fassung '.$version->version.' (veröffentlicht am '.$version->published_at->format('d.m.Y').').'
.($template->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : ' Der Entwurf entspricht der gültigen Fassung.');
}
protected function getHeaderActions(): array
{
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->tooltip('Zeigt den zuletzt gespeicherten Entwurf als Besucher mit allen Bedingungen. Es wird nichts gesendet.')
->url(fn (): string => route('communication.preview.template', $this->getRecord()))
->openUrlInNewTab(),
Action::make('check')
->label('Konfiguration prüfen')
->color('gray')
->action(function (): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
$result = app(TemplateCompiler::class)->compile(TemplateDraft::clean((array) $this->getRecord()->draft));
if ($result['errors'] === []) {
Notification::make()->title('Die Konfiguration ist in Ordnung.')->body('Der Entwurf wurde gespeichert und lässt sich veröffentlichen.')->success()->send();
return;
}
Notification::make()->title('Die Konfiguration hat Probleme')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $result['errors'])))->danger()->persistent()->send();
}),
Action::make('publish')
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->modalHeading('Formular veröffentlichen')
->modalSubmitActionLabel('Jetzt veröffentlichen')
->modalWidth('2xl')
->schema(fn (): array => [
Text::make($this->affectedText()),
Textarea::make('note')->label('Bemerkung zur Fassung (optional)')->rows(2)->maxLength(300),
])
->action(function (array $data): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
try {
$version = app(Publisher::class)->publishTemplate($this->getRecord(), auth('staff')->user() instanceof User ? auth('staff')->user() : null, $data['note'] ?? null);
} catch (ValidationException $e) {
Notification::make()->title('Das Formular lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send();
return;
}
Notification::make()->title('Fassung '.$version->version.' ist veröffentlicht.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
...$this->archiveActions(),
];
}
/** Einstiege, die diese Vorlage verwenden und von einer neuen Fassung betroffen sind. */
private function affectedText(): string
{
$rows = app(Publisher::class)->affected($this->getRecord());
if ($rows === []) {
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
$names = array_map(fn (array $row): string => $row['entry']->name.($row['entry']->published_config !== null ? ' (veröffentlicht)' : ' (Entwurf)'), $rows);
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist, und für diese Anfrage-Einstiege (ältere Seiten): '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
protected function archiveNote(): string
{
return 'Das Formular wird archiviert. Seiten, die es einbinden, bieten es dann nicht mehr an (auch Anfrage-Einstiege liefern nichts mehr aus). Eingegangene Anfragen bleiben unverändert.';
}
protected function archiveAttributes(): array
{
return ['archived_at' => now()];
}
protected function indexUrl(): string
{
return InquiryTemplateResource::getUrl('index');
}
protected function archiveBlocked(): ?string
{
$live = $this->getRecord()->entries()->live()->count();
return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit diesem Formular. Bitte zuerst zurückziehen oder auf ein anderes Formular umstellen." : null;
}
protected function mutateFormDataBeforeFill(array $data): array
{
$tree = FormEditor::toTree(app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey()));
// Die Formularansicht führt den Baum im Browser und übergibt ihn als Text; die weiteren Regeln bleiben eine Liste.
$data['editor'] = ['rules' => $tree['rules']];
$data['editor_json'] = json_encode(['areas' => $tree['areas']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$editor = app(FormEditor::class);
$tree = json_decode((string) ($data['editor_json'] ?? ''), true);
if (! is_array($tree)) {
$this->failEditor(['Der Aufbau konnte nicht gelesen werden. Bitte lade die Seite neu und versuche es noch einmal.']);
}
$errors = $editor->validateTree($tree);
if ($errors !== []) {
$this->failEditor($errors);
}
// Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf.
$view = FormEditor::fromTree($tree);
$view['rules'] = (array) ($data['editor']['rules'] ?? []);
$saved = $editor->persist($view);
unset($data['editor'], $data['editor_json']);
$data['draft'] = TemplateDraft::clean([
'texts' => (array) ($data['draft']['texts'] ?? []),
'issues' => $saved['issues'],
'steps' => $saved['steps'],
'rules' => $saved['rules'],
]);
return $data;
}
/**
* @param list<string> $messages
* @return never
*/
private function failEditor(array $messages): void
{
Notification::make()->title('Das Formular ist noch nicht vollständig')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $messages)))->danger()->persistent()->send();
throw ValidationException::withMessages(['data.editor_json' => $messages]);
}
protected function afterSave(): void
{
// Neue Felder und Teilbereiche tragen jetzt ihre festen Kennungen. Ohne neues Laden würde ein zweites Speichern sie doppelt anlegen.
$this->fillForm();
}
protected function getRedirectUrl(): ?string
{
return null;
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Filament\Resources\Communication\Templates\Pages;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Str;
class ListInquiryTemplates extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryTemplateResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Hier entstehen Formulare und Befragungen: Bereiche mit Feldern, Bedingungen und Texte, alles in einem Editor. Änderungen sind zunächst ein Entwurf und gelten erst nach „Veröffentlichen“. Im Widget „Anfrage“ einer Seite wählst du, welches Formular zu welchem Anfragegrund gehört.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Formular anlegen')
->modalHeading('Neues Formular')
->modalDescription('Der Aufbau entsteht danach im Editor des Formulars.')
->modalSubmitActionLabel('Formular anlegen')
->schema([
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400),
])
->action(function (array $data): void {
$draft = InquiryTemplate::emptyDraft();
$draft['steps'] = [['key' => 's'.Str::lower(Str::random(6)), 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]];
$template = InquiryTemplate::query()->create([
'key' => Keys::from($data['name'], InquiryTemplate::query()->pluck('key')->all()),
'name' => $data['name'],
'description' => $data['description'] ?? null,
'draft' => $draft,
]);
Notification::make()->title('Das Formular ist angelegt.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template]));
}),
];
}
protected function catalogRows(): array
{
$rows = [];
foreach (InquiryTemplate::query()->with('publishedVersion')->withCount('entries')->orderBy('name')->get() as $template) {
$url = InquiryTemplateResource::getUrl('edit', ['record' => $template]);
$archived = $template->archived_at !== null;
$published = $template->isPublished();
$changes = $published && $template->hasUnpublishedChanges();
$steps = count((array) ($template->draft['steps'] ?? []));
$rows[] = [
'schluessel' => 't'.$template->id,
'titel' => $template->name,
'meta' => 'Formular · '.$steps.' '.($steps === 1 ? 'Bereich' : 'Bereiche').($template->entries_count > 0 ? ' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege').' (ältere Seiten)' : ''),
'text' => (string) ($template->description ?? ''),
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
$archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($published
? ['label' => 'Fassung '.$template->publishedVersion->version.' gültig', 'ton' => 'gut']
: ['label' => 'Noch nicht veröffentlicht', 'ton' => 'offen']),
$changes ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null,
])),
'zustand' => [$archived ? 'archiviert' : ($published ? 'veroeffentlicht' : 'entwurf'), ...($changes ? ['aenderungen'] : [])],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Zustand',
'veroeffentlicht' => 'Veröffentlicht',
'entwurf' => 'Noch nicht veröffentlicht',
'aenderungen' => 'Mit unveröffentlichten Änderungen',
'archiviert' => 'Archiviert',
];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Beschreibung';
}
protected function einheit(): array
{
return ['Formular', 'Formulare'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Formulare', 'text' => 'Mit „Formular anlegen“ oben entsteht das erste Formular. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Filament\Resources\Communication\Templates\RelationManagers;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\InquiryTemplateVersion;
use App\Domain\Communication\Publisher;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Validation\ValidationException;
/**
* Fassungen einer Anfragevorlage: unveränderlich, jederzeit nachvollziehbar. Eine frühere Fassung lässt sich wieder in
* Kraft setzen oder als Entwurf laden.
*/
class VersionsRelationManager extends RelationManager
{
protected static string $relationship = 'versions';
protected static ?string $title = 'Fassungen';
protected static ?bool $isLazyLoaded = false;
public function table(Table $table): Table
{
/** @var InquiryTemplate $template */
$template = $this->getOwnerRecord();
return $table
->heading('Fassungen')
->emptyStateHeading('Noch keine Fassung veröffentlicht')
->emptyStateDescription('Mit „Veröffentlichen“ entsteht die erste Fassung.')
->columns([
TextColumn::make('version')->label('Fassung')->prefix('Nr. '),
TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i'),
TextColumn::make('published_by')->label('Von')->state(fn (InquiryTemplateVersion $record): string => (string) User::query()->whereKey($record->published_by)->value('name')),
TextColumn::make('note')->label('Bemerkung')->placeholder('–'),
TextColumn::make('state')->label('Zustand')->badge()
->color(fn (string $state): string => $state === 'Gültig' ? 'success' : 'gray')
->state(fn (InquiryTemplateVersion $record): string => $record->id === $this->getOwnerRecord()->published_version_id ? 'Gültig' : 'Früher'),
TextColumn::make('inquiries')->label('Anfragen')->state(fn (InquiryTemplateVersion $record): int => Inquiry::query()->where('template_version_id', $record->id)->count()),
])
->recordActions([
Action::make('restore')
->label('Wieder in Kraft setzen')
->visible(fn (InquiryTemplateVersion $record): bool => $record->id !== $template->fresh()->published_version_id)
->requiresConfirmation()
->modalDescription('Besucher sehen danach wieder diese Fassung. Der Entwurf bleibt unverändert. Eingegangene Anfragen bleiben ihrer damaligen Fassung zugeordnet.')
->action(function (InquiryTemplateVersion $record): void {
try {
app(Publisher::class)->restoreVersion($this->getOwnerRecord(), $record);
} catch (ValidationException $e) {
Notification::make()->title('Nicht möglich')->body(implode(' ', $e->errors()['draft'] ?? []))->danger()->send();
return;
}
Notification::make()->title('Fassung '.$record->version.' ist wieder gültig.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
Action::make('load')
->label('Als Entwurf laden')
->color('gray')
->requiresConfirmation()
->modalDescription('Der aktuelle Entwurf wird durch den Stand dieser Fassung ersetzt. Veröffentlicht wird dadurch nichts.')
->action(function (InquiryTemplateVersion $record): void {
$this->getOwnerRecord()->forceFill(['draft' => $record->source])->save();
Notification::make()->title('Der Entwurf entspricht jetzt Fassung '.$record->version.'.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
])
->defaultSort('version', 'desc')
->paginated(false);
}
}
@@ -119,7 +119,7 @@ public function form(Schema $schema): Schema
Placeholder::make('thumbnail_current')->label('Aktuelles Vorschaubild')->content(function (): HtmlString {
/** @var ContentElement $element */
$element = $this->getRecord();
$url = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$url = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
$caption = match ($element->thumbnail_source) {
'eigen' => 'Eigenes Vorschaubild.',
'datei' => 'Vorschaubild aus der Datei des Mediums.',
@@ -589,7 +589,7 @@ private function viewerData(): array
&& $element->output_class === 'text'
&& $shown->status !== ContentVersionStatus::Gesperrt,
'bodyCommitted' => $committed,
'pictureUrl' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'pictureUrl' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at),
'pictureCaption' => $this->pictureCaption($element),
];
}
@@ -1076,7 +1076,7 @@ public function previewHtml(): string
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
'hide_status' => true,
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at),
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
],
]);
@@ -108,7 +108,7 @@ protected function catalogRows(): array
'titel' => $title,
'meta' => 'Lizenzartikel · '.$article->code.(filled($article->product_line) ? ' · '.$article->product_line : ''),
'text' => trim((string) ($article->teaser ?: $article->summary)),
'bild' => $cover !== null ? ThumbnailRef::url('editorial.card', 'element', $cover->id, $cover->thumbnail_path) : null,
'bild' => $cover !== null ? ThumbnailRef::url('editorial.card', 'element', $cover->id, $cover->thumbnail_path, 'klein', $cover->updated_at) : null,
'symbol' => 'dokument',
'url' => $url,
'chips' => $chips,
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Support;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
/**
* Archivieren und Wiederherstellen statt Löschen für die Konfigurationsbereiche der Kommunikationsverwaltung. Die
* Seite liefert archiveNote() (Wirkung), archiveBlocked() (Hinderungsgrund oder null) und indexUrl().
*/
trait ArchivesCommunicationRecords
{
abstract protected function archiveNote(): string;
abstract protected function indexUrl(): string;
/**
* @return array<string, mixed>
*/
protected function archiveAttributes(): array
{
return ['archived_at' => now(), 'active' => false];
}
/** Grund, warum das Archivieren gerade nicht möglich ist; null: möglich. */
protected function archiveBlocked(): ?string
{
return null;
}
/**
* @return list<Action>
*/
protected function archiveActions(): array
{
return [
Action::make('archive')
->label('Archivieren')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->requiresConfirmation()
->modalDescription(fn (): string => $this->archiveNote())
->action(function (): void {
if (($reason = $this->archiveBlocked()) !== null) {
Notification::make()->title($reason)->danger()->send();
return;
}
$this->getRecord()->forceFill($this->archiveAttributes())->save();
Notification::make()->title('Archiviert.')->success()->send();
$this->redirect($this->indexUrl());
}),
Action::make('restore')
->label('Wiederherstellen')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at !== null)
->action(function (): void {
$this->getRecord()->forceFill(['archived_at' => null])->save();
Notification::make()->title('Wiederhergestellt.')->success()->send();
$this->redirect($this->indexUrl());
}),
];
}
}
+12 -14
View File
@@ -18,12 +18,14 @@
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Media\ThumbnailRef;
use App\Filament\Resources\Combinations\CombinationResource;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Resources\Courses\CourseResource;
use App\Filament\Resources\Documents\DocumentResource;
use App\Filament\Resources\Exercises\ExerciseResource;
use App\Filament\Resources\Practices\PracticeResource;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
@@ -115,7 +117,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'usage_note' => (string) ($element->usage_note ?? ''),
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
'image' => $this->cardUrl('element', $element->id, $element->thumbnail_path),
'image' => $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at),
'version_label' => match ($version->status) {
ContentVersionStatus::Entwurf => 'Entwurf',
ContentVersionStatus::Gesperrt => 'deaktiviert',
@@ -163,7 +165,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'kind' => $kind,
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at),
'version_label' => $version->status === ContentVersionStatus::Gesperrt
? 'deaktiviert'
: 'Fassung '.$version->number,
@@ -198,7 +200,7 @@ private function draftCompositionRow(int $compositionId, int $exceptCompositionI
'kind' => $kind,
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at),
'version_label' => 'Entwurf',
'identity' => 'zusammenstellung:'.$composition->id,
'open_url' => route('editorial.draft-preview', ['composition' => $composition]),
@@ -524,7 +526,7 @@ private function rowForPresentationMedium(int $id): ?array
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
'image' => $element->output_class === 'bild'
? $this->cardUrl('element', $element->id, $element->thumbnail_path)
? $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'version_label' => 'Ohne Inhaltsfassung',
'committed' => false,
@@ -548,13 +550,9 @@ public function tone(string $outputClass, string $kindLabel): string
};
}
public function cardUrl(string $kind, int $id, ?string $path): ?string
public function cardUrl(string $kind, int $id, ?string $path, ?string $size = null, CarbonInterface|int|string|null $version = null): ?string
{
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
return null;
}
return route('editorial.card', ['kind' => $kind, 'subject' => $id]);
return ThumbnailRef::url('editorial.card', $kind, $id, $path, $size, $version);
}
/**
@@ -891,7 +889,7 @@ public function filmPictures(array $members): array
continue;
}
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path);
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
if ($image === null || isset($pictures[$element->id])) {
continue;
@@ -933,7 +931,7 @@ public function mediaPictures(string $query): array
->limit(12)
->get()
->map(function (ContentElement $element): ?array {
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path);
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
if ($image === null) {
return null;
@@ -957,7 +955,7 @@ public function mediaPictures(string $query): array
*/
public function cover(Composition $composition, array $members): array
{
$own = $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path);
$own = $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at);
if ($own !== null) {
return ['url' => $own, 'note' => null, 'own' => true];
@@ -970,7 +968,7 @@ public function cover(Composition $composition, array $members): array
}
return [
'url' => $this->cardUrl($picture['kind'], $picture['subject'], 'vorschau/gesetzt'),
'url' => $this->cardUrl($picture['kind'], $picture['subject'], 'vorschau/gesetzt', 'mittel'),
'note' => $picture['note'],
'own' => false,
];
+1 -1
View File
@@ -553,7 +553,7 @@ private function card(ContentElement $element, array $portrait, array $uses, arr
'description' => $description === '' ? null : $description,
'usageNote' => $usageNote === '' ? null : $usageNote,
'licenseNote' => $licenseNote === '' ? null : $licenseNote,
'image' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'image' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at),
'imageAlt' => trim((string) ($element->thumbnail_alt ?: $element->working_title)),
'imageNote' => $this->imageNote($element),
'presentation' => $this->isPresentationMedium($element, $portrait['versionCount']),
+295
View File
@@ -0,0 +1,295 @@
<?php
namespace App\Filament\Support;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\TemplateCompiler;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ViewField;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
/**
* Formular-Editor (ADR-61): ein Formular wird an einer Stelle bearbeitet. Es besteht aus Bereichen (im mehrstufigen Dialog
* je ein Schritt), darin Felder und Teilbereiche, Bedingungen direkt am Element. Felder werden hier angelegt und
* geändert; sie landen im selben Katalog wie bisher (FormEditor). Die Regelliste bleibt für alles, was sich nicht an ein
* Element heften lässt. Alles sind Auswahlfelder und Listen; es gibt keine freie Eingabe von Ausdrücken oder JSON.
*/
final class TemplateEditor
{
/**
* @return list<Component>
*/
public static function schema(?int $templateId = null): array
{
return [
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120)
->helperText('So heißt das Formular in der Verwaltung und in der Auswahl des Widgets „Anfrage“.'),
Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->columnSpanFull()->tabs([
Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure($templateId)),
Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()),
Tab::make('Weitere Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
]),
];
}
/**
* Der Aufbau ist eine eigene Formularansicht (resources/views/filament/communication/form-editor.blade.php). Sie führt
* den Baum aus Bereichen, Teilbereichen und Feldern im Browser und übergibt ihn beim Speichern als Text (editor_json);
* FormEditor prüft und speichert ihn.
*
* @return list<Component>
*/
private static function structure(?int $templateId): array
{
return [
ViewField::make('editor_json')
->hiddenLabel()
->view('filament.communication.form-editor')
->viewData(['config' => app(FormEditor::class)->clientConfig($templateId)])
->columnSpanFull(),
];
}
/**
* @return list<Component>
*/
private static function rules(): array
{
return [
Section::make()->schema([
Text::make('Hier stehen Regeln, die sich nicht an ein einzelnes Feld oder einen Bereich heften lassen: weitere Regeln für dasselbe Ziel und Vorbelegungen. Bedingungen für ein Feld oder einen Bereich legst du direkt am Element an. Eine Bedingung darf nur auf Felder verweisen, die im Formular weiter oben stehen.'),
Repeater::make('editor.rules')
->label('Weitere Regeln')
->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS),
Select::make('target')->label('Ziel')->required()->live()->searchable()
->options(fn ($livewire, Get $get): array => self::targets(self::flat($livewire), (string) $get('effect'))),
Select::make('value')->label('Vorbelegen mit')->live()
->options(fn (Get $get): array => str_starts_with((string) $get('target'), 'field:') ? self::fieldValues(substr((string) $get('target'), 6)) : [])
->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')->required(),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn ($livewire): array => self::sources(self::flat($livewire))),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn ($livewire, Get $get): array => self::sourceValues(self::flat($livewire), (string) $get('source'))),
])
->minItems(1)
->addActionLabel('Bedingung hinzufügen'),
])
->collapsible()
->addActionLabel('Regel hinzufügen')
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], self::flat($livewire)) : '')),
]),
];
}
/**
* @return list<Component>
*/
private static function texts(): array
{
$fields = [];
foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) {
$field = $multiline
? Textarea::make("draft.texts.$key")->rows(2)->maxLength(1500)
: TextInput::make("draft.texts.$key")->maxLength(200);
$fields[] = $field->label($label)->placeholder($default !== '' ? $default : 'Kein Text')->helperText($help);
}
return [
Section::make('Texte des Formulars')
->description('Alle Texte des Formulars werden hier gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext.')
->schema($fields),
];
}
/**
* Der aktuelle Aufbau in der flachen Ansicht (Bereiche, Felder, Teilbereiche, Ende-Markierungen), aus dem Text der Formularansicht.
*
* @return array<string, mixed>
*/
private static function flat(mixed $livewire): array
{
$tree = json_decode((string) ($livewire->data['editor_json'] ?? ''), true);
return FormEditor::fromTree(is_array($tree) ? $tree : []);
}
/**
* Inhalt des Formulars in Reihenfolge: Bereiche, Teilbereiche, Felder, und ob die Frage nach dem Anliegen vorkommt.
*
* @param array<string, mixed> $editor
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool, issues: list<string>}
*/
private static function inventory(array $editor): array
{
$steps = [];
$groups = [];
$fields = [];
$hasIssue = false;
$issues = [];
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$key = (string) ($area['key'] ?? '');
if ($key !== '') {
$steps[$key] = (string) (($area['title'] ?? '') ?: 'Bereich');
}
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$data = (array) ($block['data'] ?? []);
$type = $block['type'] ?? null;
if ($type === 'issue') {
$hasIssue = true;
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
} elseif ($type === 'section' && filled($data['key'] ?? null)) {
$groups[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Teilbereich');
} elseif ($type === 'field' && filled($data['key'] ?? null)) {
$fields[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Feld');
}
}
}
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue, 'issues' => $issues];
}
/**
* @param array<string, mixed> $editor
* @return array<string, mixed>
*/
private static function targets(array $editor, string $effect): array
{
$inventory = self::inventory($editor);
$steps = [];
foreach ($inventory['steps'] as $key => $title) {
$steps["step:$key"] = 'Bereich: '.$title;
}
$groups = [];
foreach ($inventory['groups'] as $key => $name) {
$groups["group:$key"] = 'Teilbereich: '.$name;
}
$fields = [];
foreach ($inventory['fields'] as $key => $name) {
$fields["field:$key"] = 'Feld: '.$name;
}
return match ($effect) {
'skip' => $steps,
'require', 'preset' => $fields,
default => ['Bereiche' => $steps, 'Teilbereiche' => $groups, 'Felder' => $fields],
};
}
/**
* @param array<string, mixed> $editor
*/
private static function targetName(string $target, array $editor = []): string
{
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$inventory = self::inventory($editor);
return match ($kind) {
'step' => (string) ($inventory['steps'][$key] ?? $key),
'field' => (string) ($inventory['fields'][$key] ?? InquiryField::query()->where('key', $key)->value('name') ?? $key),
'group' => (string) ($inventory['groups'][$key] ?? $key),
default => $key,
};
}
/**
* Felder, auf deren Wert sich eine Bedingung stützen darf: gespeicherte Auswahlfelder und Ja/Nein-Felder. Mit
* Zustandspfad der Bedingung nur Felder, die im Formular davor stehen (sonst lehnt die Prüfung die Regel ab).
*
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sources(array $editor): array
{
$catalog = InquiryField::query()->get()->keyBy('key');
$sources = [];
foreach ((array) ($editor['areas'] ?? []) as $area) {
foreach ((array) ($area['items'] ?? []) as $block) {
$data = (array) ($block['data'] ?? []);
$key = (string) ($data['key'] ?? '');
if (($block['type'] ?? null) === 'issue') {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
} elseif (($block['type'] ?? null) === 'field' && isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = (string) (($data['label'] ?? '') ?: $catalog[$key]->label);
}
}
}
return $sources;
}
/**
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sourceValues(array $editor, string $source): array
{
if ($source === 'anliegen' || $source === 'unteranliegen') {
$only = self::inventory($editor)['issues'];
$options = [];
foreach (InquiryIssue::tree() as $issue) {
if ($only !== [] && ! in_array($issue['key'], $only, true)) {
continue;
}
if ($source === 'anliegen') {
$options[$issue['key']] = $issue['label'];
continue;
}
foreach ($issue['children'] as $child) {
$options[$child['key']] = $issue['label'].' › '.$child['label'];
}
}
return $options;
}
return self::fieldValues($source);
}
/**
* @return array<string, string>
*/
private static function fieldValues(string $key): array
{
$field = InquiryField::query()->where('key', $key)->first();
if ($field === null || ! in_array($field->type, [FieldType::Select, FieldType::Multiselect, FieldType::Boolean], true)) {
return [];
}
return collect($field->optionList())->pluck('label', 'key')->all();
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Http\Controllers\Concerns;
use App\Domain\Media\ImageVariants;
use App\Jobs\DeriveImageVariants;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
/**
* Liefert ein Bild einer Disk mit Zwischenspeicherung aus (docs/architektur/bildvarianten.md).
*
* Mit Versionsangabe in der Adresse (`?v=`) ändert sich die Adresse, sobald sich das Bild ändert; der Browser darf es
* dann ein Jahr behalten. Ohne Version bleibt es bei einer Rückfrage mit ETag und Last-Modified (304 ohne Inhalt).
*/
trait ServesImages
{
/**
* @param 'public'|'private' $scope `private` für alles, was eine Anmeldung oder Berechtigung voraussetzt
*/
protected function respondWithImage(Request $request, string $diskName, string $path, string $scope = 'private', bool $versioned = false): Response
{
$disk = Storage::disk($diskName);
$headers = [
'Content-Disposition' => 'inline',
'X-Content-Type-Options' => 'nosniff',
];
$response = $disk->response($path, null, $headers);
$modified = (int) $disk->lastModified($path);
$size = (int) $disk->size($path);
$response->setEtag(md5($path.'|'.$modified.'|'.$size));
$response->setLastModified(Carbon::createFromTimestamp($modified));
if ($versioned) {
$response->headers->set('Cache-Control', $scope.', max-age=31536000, immutable');
} else {
$response->headers->set('Cache-Control', $scope.', max-age=0, must-revalidate');
}
$response->isNotModified($request);
return $response;
}
/** Pfad der angefragten Größe (`?g=klein|mittel`), sonst die Hauptdatei. */
protected function imagePathFor(Request $request, string $diskName, string $path): string
{
$size = $request->query('g');
$resolved = ImageVariants::resolve(Storage::disk($diskName), $path, is_string($size) ? $size : null);
// Bestand ohne Fassungen: Die Hauptdatei geht hinaus, und die Warteschlange legt die Fassungen an (der Web-Prozess
// schreibt nie). Höchstens einmal je Tag und Bild; ist die Quelle schmaler als die Stufe, bleibt es bei der Hauptdatei.
if ($resolved === $path && ImageVariants::isSize($size) && Cache::add('bildvarianten.'.md5($path), true, now()->addDay())) {
DeriveImageVariants::dispatch($path);
}
return $resolved;
}
/** `?v=` ist da und eine einfache Zahl (Zeitstempel). */
protected function hasImageVersion(Request $request): bool
{
$version = $request->query('v');
return is_string($version) && preg_match('/^[0-9]{1,12}$/', $version) === 1;
}
}
@@ -12,15 +12,18 @@
use App\Domain\Identity\StaffRole;
use App\Domain\Media\ThumbnailDeriver;
use App\Filament\Support\EditorialCatalog;
use App\Http\Controllers\Concerns\ServesImages;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class EditorialPreviewController extends Controller
{
use ServesImages;
public function show(Composition $composition, ?CompositionVersion $version = null): View
{
$this->authorizeStaff();
@@ -104,7 +107,7 @@ public function draft(Composition $composition): View
);
}
public function card(string $kind, int $subject): StreamedResponse
public function card(Request $request, string $kind, int $subject): SymfonyResponse
{
$this->authorizeStaff();
abort_unless(in_array($kind, ['element', 'komposition'], true), 404);
@@ -116,7 +119,13 @@ public function card(string $kind, int $subject): StreamedResponse
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
return $this->respondWithImage(
$request,
'media_derived',
$this->imagePathFor($request, 'media_derived', $path),
'private',
$this->hasImageVersion($request),
);
}
/**
@@ -0,0 +1,133 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Communication\FormEvaluator;
use App\Domain\Communication\FormPayload;
use App\Domain\Communication\FormReason;
use App\Domain\Communication\FormToken;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryService;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\SubmissionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Öffentliche Schnittstelle der Anfrage-Einstiege. Die Seite des CMS enthält nur die Kennung des Einstiegs; Formular,
* Bedingungen und Annahme kommen von hier, damit eine zentrale Veröffentlichung sofort auf allen Seiten wirkt und keine
* Formularstände in gespeicherten Seiten veralten.
*/
class InquiryFormController extends Controller
{
public function __construct(private readonly InquiryService $service, private readonly FormEvaluator $evaluator) {}
public function definition(InquiryEntry $entry): JsonResponse
{
$delivered = $this->service->deliver($entry);
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
return $this->json([
...FormPayload::definition($delivered['form'], $this->evaluator),
'token' => FormToken::issue($entry->id, $delivered['version']->id),
'csrf' => csrf_token(),
]);
}
public function state(Request $request, InquiryEntry $entry): JsonResponse
{
$delivered = $this->service->deliver($entry);
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
$values = $request->input('values');
if (! is_array($values) || strlen((string) json_encode($values)) > 40000) {
return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422);
}
return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator));
}
public function submit(Request $request, InquiryEntry $entry): JsonResponse
{
try {
$result = $this->service->submit($entry, [
'token' => $request->input('token'),
'values' => $request->input('values'),
'website' => $request->input('website'),
'source' => $request->input('source'),
]);
} catch (SubmissionException $e) {
return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422);
}
return $this->json(['reference' => $result['reference']], 201);
}
/**
* Widget „Anfrage“ (ADR-61): das veröffentlichte Formular einer Vorlage für den gewählten Anfragegrund. Der Grund
* (Anliegen, Unteranliegen, Formularführung) steht in der Adresse, damit Zustand und Absendung ohne weitere
* Angaben dasselbe Formular meinen.
*/
public function formDefinition(Request $request, InquiryTemplate $template): JsonResponse
{
$delivered = $this->service->deliverForm($template, FormReason::clean($request->query()));
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
return $this->json([
...FormPayload::definition($delivered['form'], $this->evaluator),
'token' => FormToken::issue($template->id, $delivered['version']->id, 'form'),
'csrf' => csrf_token(),
]);
}
public function formState(Request $request, InquiryTemplate $template): JsonResponse
{
$delivered = $this->service->deliverForm($template, FormReason::clean($request->query()));
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
$values = $request->input('values');
if (! is_array($values) || strlen((string) json_encode($values)) > 40000) {
return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422);
}
return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator));
}
public function formSubmit(Request $request, InquiryTemplate $template): JsonResponse
{
try {
$result = $this->service->submitForm($template, FormReason::clean($request->query()), [
'token' => $request->input('token'),
'values' => $request->input('values'),
'website' => $request->input('website'),
'source' => $request->input('source'),
]);
} catch (SubmissionException $e) {
return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422);
}
return $this->json(['reference' => $result['reference']], 201);
}
/**
* @param array<string, mixed> $data
*/
private function json(array $data, int $status = 200): JsonResponse
{
return response()->json($data, $status)->header('Cache-Control', 'no-store, private');
}
}
@@ -0,0 +1,141 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\FormEvaluator;
use App\Domain\Communication\FormFactory;
use App\Domain\Communication\FormPayload;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\TemplateCompiler;
use App\Domain\Communication\TemplateDraft;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Vorschau für die Verwaltung: das Formular, wie es ein Besucher sieht, aus dem gespeicherten Entwurf einer Vorlage oder
* eines Einstiegs. Dieselbe Darstellung und dieselbe Auswertung wie öffentlich; gesendet wird nichts.
*/
class InquiryPreviewController extends Controller
{
public function __construct(
private readonly TemplateCompiler $compiler,
private readonly FormFactory $factory,
private readonly FormEvaluator $evaluator,
) {}
public function template(Request $request, InquiryTemplate $template): View
{
$this->authorizeStaff();
$mode = $request->query('modus') === 'wizard' ? 'wizard' : 'compact';
$result = $this->compiler->compile(TemplateDraft::clean((array) $template->draft));
return view('communication.preview', [
'title' => 'Vorschau: Vorlage „'.$template->name.'“',
'note' => 'Entwurf der Vorlage mit allen angebotenen Anliegen. Es wird nichts gesendet.',
'errors' => $result['errors'],
'mode' => $mode,
'switchUrl' => route('communication.preview.template', ['template' => $template, 'modus' => $mode === 'wizard' ? 'compact' : 'wizard']),
'definitionUrl' => route('communication.preview.template.definition', ['template' => $template, 'modus' => $mode]),
'stateUrl' => route('communication.preview.template.state', ['template' => $template, 'modus' => $mode]),
]);
}
public function templateDefinition(Request $request, InquiryTemplate $template): JsonResponse
{
$this->authorizeStaff();
$form = $this->templateForm($request, $template);
return $form === null ? $this->unavailable() : $this->json([...FormPayload::definition($form, $this->evaluator), 'token' => 'vorschau', 'csrf' => csrf_token()]);
}
public function templateState(Request $request, InquiryTemplate $template): JsonResponse
{
$this->authorizeStaff();
$form = $this->templateForm($request, $template);
return $form === null ? $this->unavailable() : $this->json(FormPayload::state($form, (array) $request->input('values', []), $this->evaluator));
}
public function entry(InquiryEntry $entry): View
{
$this->authorizeStaff();
$problem = $this->entryForm($entry) === null ? 'Die Anfragevorlage dieses Einstiegs hat noch keine gültige Fassung.' : null;
return view('communication.preview', [
'title' => 'Vorschau: Einstieg „'.$entry->name.'“',
'note' => 'Gespeicherter Entwurf des Einstiegs mit der gültigen Fassung der Vorlage. Es wird nichts gesendet.',
'errors' => $problem === null ? [] : [$problem],
'mode' => null,
'switchUrl' => null,
'definitionUrl' => route('communication.preview.entry.definition', $entry),
'stateUrl' => route('communication.preview.entry.state', $entry),
]);
}
public function entryDefinition(InquiryEntry $entry): JsonResponse
{
$this->authorizeStaff();
$form = $this->entryForm($entry);
return $form === null ? $this->unavailable() : $this->json([...FormPayload::definition($form, $this->evaluator), 'token' => 'vorschau', 'csrf' => csrf_token()]);
}
public function entryState(Request $request, InquiryEntry $entry): JsonResponse
{
$this->authorizeStaff();
$form = $this->entryForm($entry);
return $form === null ? $this->unavailable() : $this->json(FormPayload::state($form, (array) $request->input('values', []), $this->evaluator));
}
/**
* @return array<string, mixed>|null
*/
private function templateForm(Request $request, InquiryTemplate $template): ?array
{
$result = $this->compiler->compile(TemplateDraft::clean((array) $template->draft));
if ($result['definition'] === null) {
return null;
}
return $this->factory->effective($result['definition'], ['mode' => $request->query('modus') === 'wizard' ? 'wizard' : 'compact']);
}
/**
* @return array<string, mixed>|null
*/
private function entryForm(InquiryEntry $entry): ?array
{
$version = $entry->template->publishedVersion;
return $version === null ? null : $this->factory->effective((array) $version->definition, (array) $entry->config);
}
private function authorizeStaff(): void
{
abort_unless(CommunicationAccess::configure(auth('staff')->user()), 403);
}
private function unavailable(): JsonResponse
{
return $this->json(['message' => 'Für diese Vorschau fehlt eine gültige Konfiguration.'], 404);
}
/**
* @param array<string, mixed> $data
*/
private function json(array $data, int $status = 200): JsonResponse
{
return response()->json($data, $status)->header('Cache-Control', 'no-store, private');
}
}
@@ -20,6 +20,7 @@
use App\Domain\Media\FilmPlayback;
use App\Domain\Media\HlsPlaylist;
use App\Domain\Media\MediaRendition;
use App\Http\Controllers\Concerns\ServesImages;
use App\Http\Controllers\Controller;
use App\Http\CourseOutline;
use App\Http\LibraryCatalog;
@@ -32,10 +33,13 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class LibraryController extends Controller
{
use ServesImages;
/** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */
public const TYPES = [
'programm' => 'Programme',
@@ -361,7 +365,7 @@ public function rendition(
return $disk->response($datei, basename($datei), ['Content-Disposition' => 'inline']);
}
public function thumbnail(Request $request, string $kind, int $subject): StreamedResponse
public function thumbnail(Request $request, string $kind, int $subject): SymfonyResponse
{
abort_unless(in_array($kind, ['komposition', 'element'], true), 404);
$model = $kind === 'komposition'
@@ -373,7 +377,13 @@ public function thumbnail(Request $request, string $kind, int $subject): Streame
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
return $this->respondWithImage(
$request,
'media_derived',
$this->imagePathFor($request, 'media_derived', $path),
'private',
$this->hasImageVersion($request),
);
}
/**
@@ -3,16 +3,22 @@
namespace App\Http\Controllers;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use App\Domain\Media\WebsiteMedia;
use App\Http\Controllers\Concerns\ServesByteRanges;
use App\Http\Controllers\Concerns\ServesImages;
use App\Jobs\DeriveWebsiteVariants;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
class WebsiteMediaController extends Controller
{
use ServesByteRanges;
use ServesImages;
public function show(Request $request, ContentElement $element, WebsiteMedia $media): StreamedResponse
public function show(Request $request, ContentElement $element, WebsiteMedia $media): Response
{
$presentation = $media->present($element);
abort_if($presentation === null, 404);
@@ -20,6 +26,45 @@ public function show(Request $request, ContentElement $element, WebsiteMedia $me
$path = $element->website_public_path;
abort_if(! is_string($path), 404);
return $this->respondWithRanges($request, 'media_public', $path, $presentation->kind !== 'bild');
if ($presentation->kind !== 'bild') {
return $this->respondWithRanges($request, 'media_public', $path, true);
}
$path = $this->widthPath($request, $element, $path);
// Die Adresse trägt den Zeitpunkt der Freigabe. Gilt er noch, ändert sich der Inhalt unter dieser Adresse nicht mehr
// (eine neue Freigabe liefert eine neue Adresse); eine veraltete Adresse wird nur kurz vorgehalten und geprüft.
$current = $this->hasImageVersion($request)
&& (int) $request->query('v') === $element->website_released_at?->getTimestamp();
return $this->respondWithImage($request, 'media_public', $path, 'public', $current);
}
/**
* Die angefragte Breite (`?w=640|1280|1920`), sonst die volle Datei. Fehlt die Breite noch, geht die volle Datei hinaus,
* und die Warteschlange legt die Breiten an (höchstens einmal je Stunde und Bild; der Web-Prozess schreibt nie).
*/
private function widthPath(Request $request, ContentElement $element, string $path): string
{
$width = $request->query('w');
if (! is_string($width) || preg_match('/^[0-9]{3,4}$/', $width) !== 1 || ! ImageVariants::isPublicWidth((int) $width)) {
return $path;
}
if (! in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return $path;
}
$variant = ImageVariants::publicPath($path, (int) $width);
if (Storage::disk('media_public')->exists($variant)) {
return $variant;
}
if (Cache::add('bildvarianten.website.'.$element->id, true, now()->addHour())) {
DeriveWebsiteVariants::dispatch($element->id);
}
return $path;
}
}
+3 -2
View File
@@ -92,6 +92,7 @@ public function index(User $user): array
'image_url' => $picture === null ? null : route('member.thumbnail', [
'kind' => $picture['kind'],
'subject' => $picture['subject'],
'g' => 'mittel',
]),
'url' => route('member.program', $composition),
];
@@ -113,7 +114,7 @@ public function index(User $user): array
: ($element?->id !== null ? 'element-'.$element->id : 'artikel-'.$article->id);
$subject = $element ?? $composition ?? $article;
$text = $element !== null ? $this->text($element) : null;
$imageUrl = $element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
$imageUrl = $element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
$media[$key] = ($media[$key] ?? []) + [
'used_in' => [],
'versions' => [],
@@ -376,7 +377,7 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
}
if ($view !== null && $element !== null) {
$poster = ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
$poster = ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
}
+2 -2
View File
@@ -129,8 +129,8 @@ private function entry(User $user, Grant $grant): array
if ($grant->status === GrantStatus::Aktiv) {
$imageUrl = $composition !== null
? ThumbnailRef::url('member.thumbnail', 'komposition', $composition->id, $composition->thumbnail_path)
: ($element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path));
? ThumbnailRef::url('member.thumbnail', 'komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at)
: ($element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at));
}
$title = $composition !== null
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Jobs;
use App\Domain\Media\ImageVariants;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
/**
* Legt die kleineren Fassungen (klein, mittel) zu einem vorhandenen Vorschaubild an. Läuft nur in der Warteschlange, die in
* derived/ schreiben darf. Auslöser: Bestand ohne Fassungen, den die Auslieferung oder der Befehl `media:varianten` findet.
*/
class DeriveImageVariants implements ShouldQueue
{
use Queueable;
public function __construct(public readonly string $path) {}
public function handle(): void
{
if (preg_match('#^vorschau/[A-Za-z0-9._\-/]+$#', $this->path) !== 1 || str_contains($this->path, '..')) {
return;
}
ImageVariants::generate(Storage::disk('media_derived'), $this->path);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Jobs;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
/**
* Legt die Breiten für die Website zu einem bereits freigegebenen Bild an (Bestand von vor den Bildfassungen). Verändert
* weder die Freigabe noch den Prüfverlauf; die Freigabe selbst schreibt die Fassungen in {@see PublishWebsiteMedia}.
*/
class DeriveWebsiteVariants implements ShouldQueue
{
use Queueable;
public function __construct(public readonly int $elementId) {}
public function handle(): void
{
$element = ContentElement::query()->find($this->elementId);
if (! $element instanceof ContentElement || $element->output_class !== 'bild' || $element->website_released_at === null) {
return;
}
$path = $element->website_public_path;
if (! is_string($path) || preg_match('#^website/'.$element->id.'/datei\.[a-z0-9]+$#', $path) !== 1) {
return;
}
$disk = Storage::disk('media_public');
ImageVariants::generatePublic($disk, $disk, $path, $path);
}
}
+9
View File
@@ -4,6 +4,7 @@
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\IdentityChange;
use App\Domain\Media\ImageVariants;
use App\Domain\Media\WebsiteRelease;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
@@ -51,6 +52,12 @@ public function handle(WebsiteRelease $release): void
if (is_string($previous) && $previous !== $target && str_starts_with($previous, 'website/'.$element->id.'/')) {
Storage::disk('media_public')->delete($previous);
ImageVariants::deletePublic(Storage::disk('media_public'), $previous);
}
if ($element->output_class === 'bild') {
// Breiten für die Website neben der Hauptdatei; ohne sie liefert die Website immer die volle Datei.
ImageVariants::generatePublic(Storage::disk('media_derived'), Storage::disk('media_public'), $derived, $target);
}
$this->mark($element, $element->website_released_at?->toIso8601String(), now()->toIso8601String());
@@ -69,6 +76,8 @@ private function deletePublicFile(ContentElement $element): void
}
Storage::disk('media_public')->delete($path);
// Auch die Breiten: Sonst bliebe ein zurückgenommenes Bild unter dem Namen einer Fassung erreichbar.
ImageVariants::deletePublic(Storage::disk('media_public'), $path);
}
private function mark(ContentElement $element, ?string $before, ?string $after): void
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Jobs;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\Inquiry;
use App\Mail\InquiryReceived;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Throwable;
/**
* Interne Benachrichtigung über eine neue Anfrage. Die Anfrage ist zu diesem Zeitpunkt bereits gespeichert; ein Fehler
* hier wird an der Anfrage vermerkt (notification_error), geht nie verloren und lässt sich in der Verwaltung wiederholen.
*/
class SendInquiryNotification implements ShouldQueue
{
use Queueable;
public int $tries = 1;
/**
* @param ?string $adminUrl Adresse der Anfrage in der Verwaltung, während der Web-Anfrage berechnet: Im Worker
* gibt es keine Anfrage, und APP_URL gilt in diesem Projekt nicht als verlässlich.
*/
public function __construct(public int $inquiryId, public ?string $adminUrl = null) {}
public function handle(): void
{
$inquiry = Inquiry::query()->find($this->inquiryId);
if ($inquiry === null) {
return;
}
$recipients = CommunicationSettings::current()->recipientList();
if ($recipients === []) {
$inquiry->forceFill(['notification_error' => 'Es sind keine Empfänger für Benachrichtigungen hinterlegt (Kommunikation → Einstellungen).'])->save();
return;
}
try {
Mail::to($recipients)->send(new InquiryReceived($inquiry, $this->adminUrl));
} catch (Throwable $e) {
report($e);
$inquiry->forceFill(['notification_error' => 'Der E-Mail-Versand ist fehlgeschlagen: '.Str::limit($e->getMessage(), 400)])->save();
return;
}
$inquiry->forceFill(['notified_at' => now(), 'notification_error' => null])->save();
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Mail;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
/**
* Testnachricht aus den Einstellungen der Kommunikationsverwaltung. Sie enthält keine Anfragedaten.
*/
class CommunicationTestMail extends Mailable
{
public function envelope(): Envelope
{
return new Envelope(subject: 'Testnachricht der Kommunikationsverwaltung');
}
public function content(): Content
{
return new Content(text: 'mail.communication-test');
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Mail;
use App\Domain\Communication\Inquiry;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
/**
* Interne Benachrichtigung. Sie nennt nur Kennzeichen, Anliegen und den Weg zur Anfrage; Kontaktdaten und Antworten
* stehen ausschließlich in der Verwaltung (Datensparsamkeit).
*/
class InquiryReceived extends Mailable
{
public function __construct(public Inquiry $inquiry, public ?string $adminUrl = null) {}
public function envelope(): Envelope
{
return new Envelope(subject: 'Neue Anfrage '.$this->inquiry->reference);
}
public function content(): Content
{
return new Content(
text: 'mail.inquiry-received',
with: [
'reference' => $this->inquiry->reference,
'issue' => $this->inquiry->issueTitle(),
'received' => $this->inquiry->created_at?->timezone(config('app.timezone'))->format('d.m.Y H:i'),
'url' => $this->adminUrl ?? url('/verwaltung/anfragen/'.$this->inquiry->id),
],
);
}
}
+10
View File
@@ -16,7 +16,10 @@
use App\Models\User;
use App\Policies\UserPolicy;
use Filament\Auth\Http\Responses\Contracts\LoginResponse as LoginResponseContract;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
@@ -40,6 +43,13 @@ public function boot(): void
'livewire.temporary_file_upload.max_upload_time' => 60,
]);
// Anfrageformulare (ADR-60): begrenzte Absendungen und Auswertungen je Adresse.
RateLimiter::for('inquiry-submit', fn (Request $request): array => [
Limit::perMinute((int) config('communication.submit_per_minute', 5))->by('inq-m|'.$request->ip()),
Limit::perHour((int) config('communication.submit_per_hour', 20))->by('inq-h|'.$request->ip()),
]);
RateLimiter::for('inquiry-state', fn (Request $request): Limit => Limit::perMinute((int) config('communication.state_per_minute', 120))->by('inq-s|'.$request->ip()));
$this->app->bind(LoginResponseContract::class, StaffLoginResponse::class);
Gate::policy(Page::class, PagePolicy::class);
Gate::policy(NavigationItem::class, NavigationItemPolicy::class);
+2
View File
@@ -8,6 +8,7 @@
use App\Domain\Cms\Widgets\Types\HeadingWidget;
use App\Domain\Cms\Widgets\Types\HeroWidget;
use App\Domain\Cms\Widgets\Types\ImageTextWidget;
use App\Domain\Cms\Widgets\Types\InquiryWidget;
use App\Domain\Cms\Widgets\Types\MediaCardWidget;
use App\Domain\Cms\Widgets\Types\NoticeWidget;
use App\Domain\Cms\Widgets\Types\ProgramCardWidget;
@@ -38,6 +39,7 @@
CallToActionWidget::class,
FaqWidget::class,
ShopProductsWidget::class,
InquiryWidget::class,
],
/*
+21
View File
@@ -0,0 +1,21 @@
<?php
return [
/*
| Anfrageformulare (ADR-60). Das Formular-Token bindet eine Einsendung an das ausgelieferte Formular.
*/
'token_ttl_hours' => 24,
/* Kürzeste Zeit zwischen Auslieferung und Absenden; schneller sendende Programme gelten als Automaten. */
'min_fill_seconds' => (int) env('INQUIRY_MIN_FILL_SECONDS', 3),
/* Absendungen je Minute und Adresse beziehungsweise Auswertungen je Minute. */
'submit_per_minute' => 5,
'submit_per_hour' => 20,
'state_per_minute' => 120,
/* Größte Menge an Eingaben (Zeichen), die ein Besucher senden darf. */
'max_payload_chars' => 40000,
];
@@ -0,0 +1,141 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Zentrale Kommunikationsverwaltung (ADR-60): nur neue Tabellen, nichts Bestehendes wird verändert.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('inquiry_issues', function (Blueprint $table): void {
$table->id();
$table->foreignId('parent_id')->nullable()->constrained('inquiry_issues')->restrictOnDelete();
$table->string('key', 60)->unique();
$table->string('label', 120);
$table->text('description')->nullable();
$table->unsignedInteger('sort_order')->default(0);
$table->boolean('active')->default(true);
$table->timestamp('archived_at')->nullable();
$table->timestamps();
});
Schema::create('inquiry_fields', function (Blueprint $table): void {
$table->id();
$table->string('key', 60)->unique();
$table->string('name', 120);
$table->string('label', 200);
$table->text('help')->nullable();
$table->string('type', 20);
$table->json('options')->nullable();
$table->json('settings')->nullable();
$table->string('purpose', 20)->nullable();
$table->boolean('active')->default(true);
$table->timestamp('archived_at')->nullable();
$table->timestamps();
});
Schema::create('inquiry_field_groups', function (Blueprint $table): void {
$table->id();
$table->string('key', 60)->unique();
$table->string('name', 120);
$table->string('label', 200)->nullable();
$table->text('description')->nullable();
$table->json('items');
$table->unsignedInteger('sort_order')->default(0);
$table->boolean('active')->default(true);
$table->timestamp('archived_at')->nullable();
$table->timestamps();
});
Schema::create('inquiry_templates', function (Blueprint $table): void {
$table->id();
$table->string('key', 60)->unique();
$table->string('name', 120);
$table->text('description')->nullable();
$table->json('draft');
$table->unsignedBigInteger('published_version_id')->nullable()->index();
$table->timestamp('archived_at')->nullable();
$table->timestamps();
});
Schema::create('inquiry_template_versions', function (Blueprint $table): void {
$table->id();
$table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete();
$table->unsignedInteger('version');
$table->json('definition');
$table->json('source');
$table->string('note', 300)->nullable();
$table->foreignId('published_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamp('published_at');
$table->unique(['template_id', 'version']);
});
Schema::create('inquiry_entries', function (Blueprint $table): void {
$table->id();
$table->string('key', 60)->unique();
$table->string('name', 120);
$table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete();
$table->json('config');
$table->json('published_config')->nullable();
$table->timestamp('published_at')->nullable();
$table->timestamp('archived_at')->nullable();
$table->timestamps();
});
Schema::create('inquiries', function (Blueprint $table): void {
$table->id();
$table->string('reference', 20)->unique();
$table->foreignId('entry_id')->nullable()->constrained('inquiry_entries')->restrictOnDelete();
$table->foreignId('template_version_id')->constrained('inquiry_template_versions')->restrictOnDelete();
$table->string('submission_token', 64)->unique();
$table->string('issue_key', 60)->nullable();
$table->string('issue_label', 120)->nullable();
$table->string('subissue_key', 60)->nullable();
$table->string('subissue_label', 120)->nullable();
$table->string('contact_name', 200)->nullable();
$table->string('contact_email', 200)->nullable();
$table->string('contact_phone', 60)->nullable();
$table->string('organisation', 200)->nullable();
$table->text('message')->nullable();
$table->json('answers');
$table->string('source_path', 300)->nullable();
$table->string('status', 20)->default('neu')->index();
$table->timestamp('notified_at')->nullable();
$table->text('notification_error')->nullable();
$table->timestamps();
$table->index('created_at');
});
Schema::create('inquiry_notes', function (Blueprint $table): void {
$table->id();
$table->foreignId('inquiry_id')->constrained('inquiries')->cascadeOnDelete();
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->text('body');
$table->timestamps();
});
Schema::create('communication_settings', function (Blueprint $table): void {
$table->id();
$table->json('recipients');
$table->unsignedSmallInteger('retention_months')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('communication_settings');
Schema::dropIfExists('inquiry_notes');
Schema::dropIfExists('inquiries');
Schema::dropIfExists('inquiry_entries');
Schema::dropIfExists('inquiry_template_versions');
Schema::dropIfExists('inquiry_templates');
Schema::dropIfExists('inquiry_field_groups');
Schema::dropIfExists('inquiry_fields');
Schema::dropIfExists('inquiry_issues');
}
};
@@ -885,3 +885,78 @@ ## ADR-59 – Hinweiszeile: kompakter Hinweis mit optional aufklappbarer Kurzdar
- **Gestaltung:** Schriftgrößen XS, S (Vorgabe), M, L; S, M und L sind `--text-small`, `--text-body` und `--text-lede` des Designsystems. **XS (13 px) gibt es im Designsystem nicht** und ist die einzige neue Größe (`--notice-fs` in `lf-hinweiszeile.css`), nur für Randbemerkungen. Symbol von 1 bis 3,5 rem, unabhängig von der Schrift; Fläche (Grün, Gelb, Creme), Rahmen und Akzentlinie nur mit Tokens. Auf einer Fläche gilt immer die helle Wertegruppe, auf dunklen und grünen Abschnitten ohne Fläche steht das Symbol auf einer weißen Scheibe (wie bei den Karten).
**Folgen.** Keine Migration. Neue Widget-Art; eine einmal gespeicherte Kennung `notice` bleibt (Rückfall: ein Code-Stand ohne das Widget kennt den Baustein nicht und zeigt ihn nicht an; die übrige Seite bleibt unverändert; gespeicherte Revisionen enthalten ihn weiterhin).
**Quelle.** Entwicklungsauftrag von Lars vom 27.11.2026; ADR-30, ADR-38, ADR-50.
## ADR-60 – Zentrale Kommunikationsverwaltung: Anfragevorlagen, Anfrage-Einstiege und ein schlankes CMS-Widget
**Status am 27.11.2026:** Umgesetzt auf `feature/kommunikation-grundlage` und `develop`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Beschreibung und Betrieb: `docs/architektur/kommunikationsverwaltung.md`.
**Kontext.** Lara & Felix braucht mehrere Kontaktanlässe (allgemeine Fragen, Kursanfragen, Materialien, Kooperationen), später auch für eine übergeordnete Dachmarke. Ein Formular je Seite oder ein Formularbaukasten im CMS würde Felder, Bedingungen und Empfänger über viele Seiten verteilen. Es gab bisher weder ein Kontaktformular noch einen Posteingang (belegt: im Repository kein Kontakt- oder Anfragemodell; vorhanden waren Filament-Verwaltung, Widget-Registry, Warteschlange `database`, Postausgang `OrderConfirmed`).
**Entscheidung (Auftrag von Lars, 27.11.2026).**
- **Eine führende Quelle: die Verwaltungsgruppe „Kommunikation“.** Anliegen und Unteranliegen, Feldkatalog, Feldgruppen, Anfragevorlagen, Anfrage-Einstiege, Empfänger und Posteingang werden dort gepflegt. Das CMS wählt nur einen veröffentlichten Anfrage-Einstieg aus. Im CMS gibt es keine Formularinhalte, Regeln, Texte oder Empfänger.
- **Neue Widget-Art `inquiry` („Anfrage“), Version 1.** Gespeichert wird allein `refs.entry` (Kennung des Einstiegs). Formular, Bedingungen, Token und Annahme liefert der Server zur Laufzeit (`/anfrage/{einstieg}`); die gespeicherte Seite enthält keinen Formularstand. Dadurch gilt eine zentrale Veröffentlichung sofort auf allen Seiten, ohne Seitenrevisionen anzufassen.
- **Entwurf und Fassungen.** Eine Anfragevorlage hat einen bearbeitbaren Entwurf und unveränderliche, vollständig aufgelöste Fassungen (Bezeichnungen, Auswahlwerte, Regeln, Schritte sind hineinkopiert). Wirksam ist nur die bewusst veröffentlichte Fassung; eine frühere lässt sich wieder in Kraft setzen oder als Entwurf laden. Eine Anfrage bleibt für immer der Fassung zugeordnet, die der Besucher sah, und speichert Bezeichnungen und Werte als Schnappschuss. Ein Anfrage-Einstieg hat ebenfalls Entwurf und veröffentlichten Stand und folgt der gültigen Fassung seiner Vorlage; vor dem Veröffentlichen einer Vorlage sind die betroffenen Einstiege sichtbar, und passt ein veröffentlichter Einstieg nicht zur neuen Fassung, wird sie abgelehnt.
- **Regeln sind Daten, keine Skripte.** Wirkungen: anzeigen, ausblenden, Pflicht, Schritt überspringen, vorbelegen. Bedingungen: ist / ist nicht / ist eines von / ist keines von, über Anliegen, Unteranliegen sowie Auswahl- und Ja/Nein-Felder, mit „alle“ oder „mindestens eine“. Die Verwaltung bietet nur Auswahllisten an, die sich aus dem Aufbau der Vorlage ableiten. **Eine Bedingung darf nur auf Felder vor ihrem Ziel verweisen**; so gibt es keine Zirkelbezüge, und die Auswertung ist ein einziger Durchlauf.
- **Eine Auswertung für alle.** Ein PHP-Auswerter (`FormEvaluator`) bedient Besucher, Vorschau und Anfrageservice. Der Browser fragt nach jeder Änderung einer steuernden Auswahl den Zustand beim Server ab (`/anfrage/{einstieg}/zustand`) und baut Sichtbarkeit und Pflicht daraus auf; es gibt keine zweite Regelauswertung in JavaScript. Werte ausgeblendeter Fragen bleiben im Browser erhalten (kein Datenverlust beim Zurückwechseln), werden aber nie gesendet; der Server verwirft sie ohnehin.
- **Zwei Darstellungen, eine Beschreibung.** Kompaktformular und mehrstufiger Dialog (Fortschritt, Zurück/Weiter, Zusammenfassung vor dem Absenden, Sprung zurück zu einem Schritt) bauen aus derselben Beschreibung. Übersprungene Schritte entfallen.
- **Zentraler Anfrageservice** (`InquiryService`): Token prüfen, gültige Fassung bestimmen, Bedingungen auswerten, serverseitig validieren (Typen, Auswahlwerte, Grenzen, unbekannte Schlüssel), in einer Transaktion speichern, erst danach benachrichtigen. Doppeltes Absenden ergibt dieselbe Anfrage (Einmalkennung im verschlüsselten Formular-Token). Schutz: CSRF der bestehenden Web-Gruppe, Köderfeld, Mindestdauer, Ratenbegrenzung je Adresse, Größenbegrenzung. Eine Erfolgsmeldung erscheint erst nach dem Speichern.
- **Benachrichtigung.** Warteschlangen-Aufgabe `SendInquiryNotification` an die in der Verwaltung gepflegten Empfänger (nie aus Besucher- oder CMS-Eingaben). Die Nachricht nennt nur Kennzeichen, Anliegen und den Weg zur Anfrage, keine Kontaktdaten und keine Antworten. Ein Versandfehler verliert keine Anfrage: er wird an der Anfrage vermerkt (`notification_error`), im Posteingang angezeigt und lässt sich dort wiederholen.
- **Posteingang** unter „Kommunikation → Anfragen“: Liste mit Suche, Filter (Status, Anliegen, Benachrichtigungsfehler) und Sortierung; Detail mit lesbaren Antworten, Quellseite, Einstieg, Fassung, Status von Hand (Neu, In Bearbeitung, Rückfrage offen, Erledigt) und internen Notizen. Zugriff: Kundenbetreuung und Systemverwaltung (personenbezogene Daten). Löschen einer Anfrage nur durch die Systemverwaltung. Konfiguration: Redaktion und Systemverwaltung. Keine neue Rolle.
- **Datenschutz.** Keine Namen oder Gesundheits- und Entwicklungsdaten einzelner Kinder im Standardformular (Hinweise an den Feldern); keine Weitergabe an Dritte, keine KI-Dienste. **Keine pauschale Pflicht-Einwilligungsbox.** Der Datenschutzhinweis ist ein pflegbarer Text je Vorlage oder Einstieg; Rechtsgrundlage, Wortlaut und Aufbewahrungsdauer sind mit dem Datenschutzkonzept abzugleichen (offen).
- **Anliegen sind zweistufig** (Anliegen, Unteranliegen). Tiefere Auswahlen wie das Kursformat sind **Auswahlfelder** mit bedingter Anzeige, kein dritter Baumzweig; das hält die Auswertung einfach. Der Auftrag verlangte keine Beschränkung auf genau drei Ebenen, aber keine Baum-Engine.
**Alternativen.** Formularfelder und Texte im CMS-Widget (verworfen: verteilte Pflege, Rechte, Versionierung doppelt). Livewire auf öffentlichen Seiten (verworfen: öffentliche Seiten laufen ohne Livewire, ADR-32). Regelauswertung zusätzlich in JavaScript (verworfen: zwei Auslegungen). Freie JSON-Eingabe oder Ausdrücke (verworfen: Sicherheit, Bedienbarkeit). Generische Workflow- oder Formular-Engine (verworfen: Auftrag). KI-Assistent (nicht Teil des Auftrags).
**Folgen.** Eine additive Migration `2026_12_03_100000_create_communication_tables` mit neun neuen Tabellen (`inquiry_issues`, `inquiry_fields`, `inquiry_field_groups`, `inquiry_templates`, `inquiry_template_versions`, `inquiries`, `inquiry_entries`, `inquiry_notes`, `communication_settings`); nichts Bestehendes wird verändert. Neue Widget-Art `inquiry`; eine einmal gespeicherte Kennung bleibt (Rückfall: ein Code-Stand ohne das Widget zeigt den Baustein nicht, die übrige Seite bleibt unverändert). Es entstehen keine Beispieldaten durch Migration; eine Beispielkonfiguration legt ein Betreiber mit „Kommunikation → Einstellungen → Beispielkonfiguration anlegen“ an (nur in einer leeren Verwaltung). Der Befehl `communication:purge` löscht Anfragen nach der gewählten Aufbewahrungsdauer; ein Zeitplaner ist nicht eingerichtet (offen).
**Ausblick (nicht umgesetzt, nur nicht verbaut).** Ein KI-Assistent könnte dieselben Vorlagen und Felder nutzen und am Ende denselben Anfrageservice aufrufen (kein zweiter Service, keine zweite Datenhaltung, Absenden erst nach ausdrücklicher Bestätigung, klassisches Formular bleibt). Eine Dachmarke braucht eigene Anfragevorlagen und Einstiege, keine Mehrmandantenfähigkeit. Anmeldung, Termine, Plätze und Zahlung sind ausdrücklich ausgeschlossen. Anfragen können später manuell weiterbearbeitet werden; eine automatische Weitergabe oder Trainervermittlung ist nicht vorgesehen und braucht einen eigenen rechtlichen Prozess.
**Quelle.** Entwicklungsauftrag von Lars vom 27.11.2026; ADR-30, ADR-32, ADR-38.
## ADR-61 – Kommunikation: Formular-Editor an einem Ort und Anfragegründe im CMS-Widget
**Status am 27.11.2026:** Umgesetzt auf `feature/kommunikation-ux` und `develop`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Ergänzt ADR-60, ersetzt es nicht. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` (Abschnitt 12).
**Kontext.** Die Engine aus ADR-60 funktioniert, die Bedienung war zu technisch: Für ein Formular mussten Anliegen, Feldkatalog, Feldgruppen, Anfragevorlage und Anfrage-Einstieg getrennt bedient werden, und das CMS-Widget wählte nur einen vorher angelegten Einstieg. Der Auftrag vom 27.11.2026 verlangt weniger Bedienaufwand und eine bessere CMS-Einbindung, ausdrücklich ohne Umbau der Engine, ohne neues Datenmodell und ohne Änderung der Anfrageverarbeitung, soweit nicht zwingend.
**Entscheidung.**
- **Navigation:** Anfragen, Formulare & Befragungen, Einstellungen. Anliegen, Feldkatalog, Feldgruppen und Anfrage-Einstiege bleiben als Objekte, Seiten und Adressen erhalten (Verweise, ältere Seiten, Tests), stehen aber nicht mehr in der Hauptnavigation; „Einstellungen“ verweist darauf.
- **Formular-Editor** (`FormEditor`, `TemplateEditor`): ein Formular wird an einer Stelle bearbeitet. Ansicht: Bereiche (im mehrstufigen Dialog je ein Schritt), darin Felder, Teilbereiche (Überschrift im Fluss, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“) und die Frage nach dem Anliegen. Felder entstehen direkt im Bereich oder werden aus dem Katalog übernommen. Es gibt keine zweite Datenhaltung: Der Editor schreibt neue und geänderte Felder und Teilbereiche in dieselben Katalogtabellen und liefert denselben Entwurf (`steps`, `rules`) wie bisher; beim Öffnen wird er in die flache Ansicht übersetzt. Ein Test belegt, dass jedes Beispielformular unverändert öffnet und wieder genau denselben Entwurf und denselben Katalog ergibt.
- **Gemeinsame Felder:** Ein Feld oder Teilbereich, der in mehreren Formularen vorkommt, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare („gilt dort mit der nächsten Veröffentlichung“). Bestehende Fassungen sind unveränderlich. Die Art eines vorhandenen Feldes ist nicht änderbar (Bedingungen und Antworten bauen darauf auf); eine andere Art ist ein neues Feld. Auswahlwerte behalten ihre Kennung bei Umbenennung.
- **Bedingungen am Element:** Feld, Teilbereich und Bereich tragen ihre Bedingung selbst (Wirkung, „alle/mindestens eine“, Vergleiche, alles als Auswahl). Beim Speichern entstehen daraus dieselben Regeln der Engine. Was sich nicht an ein Element heften lässt (weitere Regeln desselben Ziels, Vorbelegungen), bleibt unter „Weitere Regeln“ erhalten und wird nie verworfen. Zur Auswahl stehen nur Felder, die im Formular weiter oben stehen (die Prüfung verlangt es ohnehin). Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung.
- **Kleine Erweiterung der Engine:** `show` und `hide` wirken auch auf Bereiche (bisher nur `skip`), damit „Bereich nur anzeigen, wenn …“ ohne umgekehrte Bedingungen ausdrückbar ist. `skip` bleibt gültig.
- **Widget „Anfrage“ ohne Anfrage-Einstieg:** Das Widget speichert Anfragegründe (`data.reasons`: Kennung, Bezeichnung, Beschreibung, Formular, optional vorgewähltes Anliegen und Unteranliegen), die Frage der Auswahl und die Beschriftung des Buttons sowie Einstellungen: **Formularführung** (`mode`: langes Formular oder mehrstufiger Dialog) und **Präsentation** (`open`: im Abschnitt oder als Dialog) unabhängig voneinander; Gestaltung: Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten folgt der Containerbreite; es gibt keine Einstellung je Bildschirmgröße.
- **Genau ein Formular je Grund:** Der Besucher wählt einen Grund; erst dann lädt der Browser das Formular dieses Grundes (`/anfrage/formular/{vorlage}?anliegen=…&unteranliegen=…&modus=…`, Zustand und Absenden ebenso). Je Grund gibt es höchstens eine Formularinstanz; ein Wechsel blendet nur um, Eingaben bleiben. Bei einem einzigen Grund entfällt die Auswahl. Eine Vorauswahl über die Adresse (`?grund=Kennung`) wählt den Grund und öffnet bei „Dialog“ den Dialog.
- **Der Grund ist Vorauswahl und Darstellung, keine Berechtigung.** Alles, was ein Grund wählen kann, bietet das veröffentlichte Formular ohnehin an. Deshalb steht der Grund in der Adresse und nicht in einer signierten Konfiguration; die Auslieferung bleibt zustandslos. Aus dem Grund entsteht dieselbe Konfiguration wie bei einem Einstieg (`FormReason`, `FormFactory::effective`). Auslieferbar ist jede veröffentlichte, nicht archivierte Vorlage; die Veröffentlichung ist die bewusste Handlung.
- **Anfrageverarbeitung unverändert:** Dieselbe Auswertung, Prüfung, Doppelsende- und Köderfeld-Abwehr, Ratenbegrenzung und Benachrichtigung. Das Formular-Token erhält die Art des Ziels (`entry` oder `form`) und ist nicht zwischen beiden austauschbar. Eine Anfrage über das Widget hat keine Einstiegskennung (`entry_id` war bereits optional) und verweist über ihre Fassung auf die Vorlage; der Posteingang zeigt „Formular …“. Keine Migration.
- **Dialog:** natives `dialog`-Element (`showModal`): Esc und „Schließen“ behalten die Eingaben, der Fokus kehrt zum Button zurück, die Seite dahinter ist fixiert, auf dem Smartphone füllt der Dialog den Bildschirm, die Aktionen bleiben unten erreichbar. In den Vorschau-Iframes des Seiteneditors (nur Stile, kleine feste Fläche) steht der Dialog als gerahmtes Beispiel; Seitenvorschau und Geräteansicht öffnen den echten Dialog.
- **Ältere Seiten:** Eine Seite mit `refs.entry` und ohne Anfragegründe wird weiter dargestellt; der Anfrage-Einstieg bleibt als Objekt erhalten.
**Alternativen.** Signierte Widget-Konfiguration in der Seite (verworfen: Der Grund ist keine Berechtigung; mehr bewegliche Teile ohne Gewinn). Neue Tabellen für Widget-Konfigurationen (ausgeschlossen: kein neues Datenmodell). Verschachtelte Teilbereiche mit eigenen Feldlisten im Editor (verworfen: sechs Ebenen Formularstruktur, schwer bedienbar; die flache Liste mit „Ende des Teilbereichs“ bildet dasselbe ab). Feldänderungen je Formular als Kopie (verworfen: zweite Wahrheit; der Hinweis auf gemeinsame Verwendung genügt, Fassungen sind unveränderlich).
**Folgen.** Keine Migration. Zwei bestehende Tests wurden bewusst geändert (Widget-Vertrag: Anfragegründe statt Einstieg). Rückfall: ein Code-Stand ohne ADR-61 kennt `data.reasons` nicht und zeigt ein so gespeichertes Widget nicht an (die Seite bleibt gültig); Formulare und Anfragen bleiben unverändert, im Katalog angelegte Felder bleiben bestehen.
**Quelle.** Entwicklungsauftrag von Lars (UX-Überarbeitung der Kommunikationsverwaltung und des CMS-Kontakt-Widgets) vom 27.11.2026; ADR-60.
## ADR-62 – Kommunikation: Formularansicht mit Ziehen und Ablegen statt Builder-Liste
**Status am 28.11.2026:** Umgesetzt auf `feature/formular-editor-umbau`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Ändert die Darstellung aus ADR-61, nicht die Daten. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` (Abschnitt 13).
**Kontext.** Der Aufbau eines Formulars bestand aus verschachtelten Filament-Listen (Repeater und Builder mit aufklappbaren Blöcken). Bei einem Formular mit wenigen Feldern wirkte das riesig und unübersichtlich; ein Teilbereich sah aus wie ein geschlossener Block, dem man nichts zuordnen konnte (die Felder darunter gehörten nur über die Reihenfolge dazu). Der Betreiber verlangte eine formularähnliche Darstellung: links die Frage, daneben der Feldtyp, Hilfetext und Bedingungen über Symbole in einem Pop-up, Bereiche und Teilbereiche deutlich als Einheit, Ziehen und Ablegen für Felder und Teilbereiche.
**Entscheidung.**
- **Eigene Formularansicht** (`filament/communication/form-editor*.blade.php`, Alpine): Bereich = Karte mit Nummer, Titel und Symbolen (Einleitung, Bedingung, weitere Einstellungen, Entfernen); darin Felder als Zeilen (Griff, Frage, Art der Antwort, Pflicht, Symbole für Hilfetext, Auswahlwerte, Bedingung, weitere Einstellungen, Entfernen) und Teilbereiche als eingerahmte Einheit mit eigener Feldliste. Hilfetext, Auswahlwerte, Bedingung, Verwendung in der Anfrageübersicht, Verschieben nach … und der Katalog öffnen in einem Pop-up (natives `dialog`); gesetzte Angaben sind am Symbol markiert, die Bedingung steht als Satz unter dem Element.
- **Ziehen und Ablegen** mit SortableJS, das Filament mitliefert (`window.Sortable`, keine neue Abhängigkeit): Bereiche untereinander, Felder an jede Stelle eines Bereichs oder Teilbereichs, Teilbereiche zwischen Bereiche. Ein Teilbereich nimmt nur Felder auf. Ohne Maus: am Griff Pfeil hoch oder runter (am Rand verlässt ein Feld den Teilbereich) und „Verschieben nach …“ im Pop-up „Weitere Einstellungen“.
- **Rückgängig** nimmt Änderungen am Aufbau bis zum Speichern zurück (Hinzufügen, Entfernen, Verschieben). Entfernen fragt deshalb nicht nach.
- **Daten unverändert:** Der Browser führt den Baum (Bereiche → Felder und Teilbereiche → Felder) und übergibt ihn beim Speichern als Text. `FormEditor::validateTree` prüft ihn serverseitig (Titel, Frage, Auswahlwerte, Längen, Dopplungen, höchstens eine Frage nach dem Anliegen) und nennt Fehlendes, statt still zu kürzen; `FormEditor::fromTree` überführt ihn in dieselbe flache Ansicht wie bisher, aus der `persist` Katalog und Entwurf schreibt. Die Umwandlung `toTree`/`fromTree` ist verlustfrei; ein Test führt jedes Beispielformular durch den Baum und erhält denselben Entwurf und Katalog. Keine Migration, keine Änderung an Engine, Katalog und Anfrageverarbeitung.
- **Fehlende Angaben** sind rot umrandet und gezählt; das Speichern lehnt ein unvollständiges Formular mit den Gründen ab und legt nichts an.
- **Weitere Regeln** (Vorbelegungen, zusätzliche Regeln desselben Ziels) bleiben unverändert als Liste im Register „Weitere Regeln“; sie lesen den Aufbau aus dem Baumtext und werden kurz nach Änderungen mit dem Server abgeglichen.
**Alternativen.** Filament-Builder mit besseren Blocktiteln (verworfen: bleibt eine aufklappbare Endlosliste ohne sichtbare Zugehörigkeit). Neue Datenstruktur mit verschachtelten Teilbereichen im Entwurf (ausgeschlossen: kein neues Datenmodell; die Zugehörigkeit steht schon als Feldgruppe im Katalog). Eigenes Ziehen ohne Bibliothek (verworfen: Berührung, Animation und Randfälle liefert SortableJS).
**Folgen.** Keine Migration. Die Livewire-Tests des Editors wurden bewusst auf den Baumtext umgestellt (der Builder entfällt). Rückfall auf ADR-61: Der Entwurf bleibt gültig; die ältere Ansicht liest ihn wieder. Das Ziehen bietet auf Berührungsbildschirmen SortableJS-Standardverhalten, wurde dort aber nicht geprüft.
**Quelle.** Rückmeldung von Lars vom 28.11.2026 zur Bedienung des Formular-Editors; ADR-61.
## ADR-63 – Bildfassungen: Thumbnail, Web und Vollauflösung
**Status am 28.11.2026:** Umgesetzt auf `feature/bildvarianten`; Messung und Abnahme auf `luf-test` offen. Beschreibung: `docs/architektur/bildvarianten.md`.
**Kontext.** Medienauswahl, Contentmanager und Listen luden für jedes Kachelbild dieselbe Datei wie die Vorschau (bei Bildern bis 2400 px), die Website lieferte immer die volle Fassung. Jedes Bild war eine PHP-Anfrage mit Sitzung (`Set-Cookie`, Zeile in `sessions`) und `Cache-Control: no-cache, private`; der Browser behielt nichts. Gemessen auf `luf-test`: 120 bis 260 KB je Vorschaubild, ein PNG mit 1,2 MB als Website-Datei.
**Entscheidung.**
- **Drei Stufen je Bild.** Verwaltung: `klein` (360 px), `mittel` (960 px) und die volle Datei (`thumbnail_path`, unverändert). Website: Breiten 640, 1280 und 1920 px neben der vollen Datei (`website/{id}/datei-{breite}.jpg`). Fassungen entstehen nur, wenn die Quelle breiter ist; nie vergrößert.
- **Namensregel statt Spalte.** `element-12-klein.jpg` liegt neben `element-12.jpg`. Keine Migration. Fehlt eine Fassung, gilt die nächstgrößere Datei; Bestand bricht nicht.
- **Geschrieben wird nur in der Warteschlange** (`ThumbnailDeriver`, `PresentationFile::place`, `PublishWebsiteMedia`). Der Web-Prozess liest nur. Bestand ohne Fassungen füllt sich selbst: Die Auslieferung nimmt die volle Datei und legt einen Auftrag an (Website: `DeriveWebsiteVariants`, höchstens einmal je Stunde und Bild; Verwaltung und Mitgliederbereich: `DeriveImageVariants`, höchstens einmal je Tag und Bild); `media:varianten` holt alles auf einmal nach, ohne Zugriff auf den Server.
- **Zwischenspeicherung.** Adressen tragen Größe (`g`) und Version (`v`, `updated_at` des Mediums bzw. Zeitpunkt der Freigabe). Mit Version: ein Jahr, `immutable` (`private` in der Verwaltung und im Mitgliederbereich, `public` auf der Website). Ohne Version: ETag und Last-Modified, `304` ohne Inhalt. Eine neue Ableitung setzt die Version (`touch`).
- **Website ohne Sitzung.** Die Route `website.media` läuft ohne Sitzung, Cookies und CSRF: keine Sitzungszeile, kein `Set-Cookie`, zwischenspeicherbar.
- **`srcset`** in Hero, Bild mit Text, Karten und Medienkarte; Abschnittshintergründe nehmen die Breite 1920. Nur JPEG-Quellen erhalten Breiten (PNG, GIF, WebP können Transparenz tragen).
- **Rücknahme** der Website-Freigabe löscht auch die Breiten.
- **Auswahl im CMS:** Die Optionsliste fragte je Eintrag das Medium dreimal ab; geladene Medien werden jetzt weitergereicht.
**Alternativen.** WebP (verworfen für jetzt: das Docker-Image baut GD ohne WebP; eigener Schritt mit Dockerfile-Änderung). Fassungen im Aufruf berechnen und zwischenspeichern (verworfen: der Web-Prozess darf nicht schreiben). Spalten für Fassungen (verworfen: Namensregel genügt, keine Migration). Statische Auslieferung durch den Webserver (verworfen: private Medien bleiben hinter der Berechtigung).
**Folgen.** Keine Migration. Tests mit festen Adressen der Website-Bilder wurden bewusst geändert (Adresse trägt `?v=`, Bild-Tags tragen `srcset`). Rückfall: Ein Stand ohne ADR-63 kennt `g`/`v` nicht und liefert die volle Datei; die Fassungsdateien bleiben liegen und stören nicht. Offen: EXIF-Drehung (Handyfotos), WebP.
**Quelle.** Rückmeldung von Lars vom 28.11.2026 zu den Ladezeiten von Medienauswahl, Contentmanager und Website.
+42
View File
@@ -0,0 +1,42 @@
# Bildfassungen (ADR-63)
Stand 28.11.2026. Gilt für alle Bilder, die die Anwendung anzeigt: Vorschaubilder der Verwaltung (Medienauswahl, Listen, Karten, Aufbau), Bilder im CMS und auf der Website.
## Stufen
| Stufe | Wo | Breite | Verwendung |
|---|---|---|---|
| `klein` | `derived/vorschau/…-klein.jpg` | 360 px | Auswahl, Listen, Kacheln, Zeilen im Aufbau |
| `mittel` | `derived/vorschau/…-mittel.jpg` | 960 px | Detailansicht, Vorschau im Editor, Kartenbilder in Seitenvorschauen, Poster |
| voll | `derived/vorschau/element-N.jpg` (`thumbnail_path`) | Bilder bis 2400 px, sonst 640 px | Quelle für die Website-Freigabe |
| Website | `public/website/N/datei-{640,1280,1920}.jpg` | 640, 1280, 1920 | `srcset` von Hero, Bild mit Text, Karten; Hintergrund 1920 |
| Website voll | `public/website/N/datei.jpg` | bis 2400 px | Rückfall und `src` |
| Original | `originals/…`, `derived/inhalte/…` | unverändert | nur Hintergrundverarbeitung, nie ausgeliefert |
Die Fassungen heißen wie die Hauptdatei mit Suffix (`ImageVariants::path`). Es gibt keine Spalte. **Fehlt eine Fassung, gilt die nächstgrößere Datei.**
## Wer schreibt
Nur die Warteschlange (`queue`); der Web-Prozess liest:
- `ThumbnailDeriver::still()` und `frame()` (jede Ableitung eines Vorschaubildes) und `PresentationFile::place()` rufen `ImageVariants::generate`.
- `PublishWebsiteMedia` (Freigabe) ruft `ImageVariants::generatePublic`; Rücknahme und Ersatz löschen die Breiten.
- `DeriveImageVariants` und `DeriveWebsiteVariants` füllen Bestand nach. Sie werden vom Befehl `php artisan media:varianten` (`--now`, `--pretend`) oder von der Auslieferung angestoßen, wenn eine Breite fehlt (höchstens einmal je Stunde und Bild).
Eine Fassung entsteht nur, wenn die Quelle breiter ist; sonst wird eine ältere gelöscht. Fassungen sind JPEG (Qualität 80, progressiv), transparente Flächen werden weiß. Website-Breiten gibt es nur für JPEG-Quellen.
## Auslieferung
- **Verwaltung** `GET /redaktion/karte/{kind}/{subject}?g=klein|mittel&v=…` (nur angemeldete Redaktion) und **Mitgliederbereich** `member.thumbnail` mit denselben Parametern (Berechtigung unverändert).
- **Website** `GET /website-medien/{id}?w=640|1280|1920&v=…` (nur freigegebene Medien).
- `ThumbnailRef::url(route, kind, id, path, size, version)` und `EditorialCatalog::cardUrl` bauen die Adressen. Wer ein Bild neu anzeigt, wählt `klein` für alles unter etwa 180 px Anzeigebreite, sonst `mittel`, und übergibt `updated_at` als Version.
- Mit `v` in der Adresse: `Cache-Control: private|public, max-age=31536000, immutable`. Ohne `v` oder bei veralteter Website-Version: `max-age=0, must-revalidate` mit ETag und Last-Modified, `304` bei unverändertem Bild.
- Die Website-Route läuft ohne Sitzung und Cookies.
## Nachprüfen
Auf dem Server nur lesend: `ls derived/vorschau | grep -- -klein`, `ls public/website/*/`. Im Browser: Netzwerk-Reiter, `Cache-Control` und Größe der Bilder; zweiter Aufruf der Medienauswahl lädt die Bilder aus dem Browser-Cache.
## Nicht enthalten
EXIF-Drehung von Handyfotos (bisher nicht beachtet), WebP/AVIF (das Image baut GD ohne WebP), Fassungen für Film-Standbilder über 640 px.
+10
View File
@@ -136,6 +136,16 @@ ## 4. Registrierte Widget-Arten
- Das Kit lädt das Einstiegsbild immer sofort; hier nur beim ersten Widget der Seite, alle anderen verzögert.
- Kit-CSS ergänzt: Überschriften erben Farbe (globale h1–h3-Regeln), Unterstreichung als Block, Fläche `clear` übernimmt die Farben dunkler Abschnitte, Strahlen-Akzent aus `components/brand/rays.blade.php`, Fokusfarbe aus den Tokens.
### Anfrage (`inquiry`, Version 1, ADR-60, ADR-61)
Kontaktformular mit Auswahl des **Anfragegrundes**. `data.reasons` (bis zu 8): `key` (entsteht beim Speichern, stabil), `label`, `description`, `template` (Kennung eines veröffentlichten Formulars), optional `issue` und `subissue` (vorgewähltes Anliegen); dazu `question` und `open_label`. Einstellungen (`settings`): `mode` (compact, wizard), `open` (inline, modal), `picker` (cards, select), `width`, `spacing`, `columns`, `button`; Formularführung und Präsentation sind unabhängig. Das Widget kennt weder Felder noch Texte, Regeln oder Empfänger; diese werden unter „Kommunikation → Formulare & Befragungen“ gepflegt. Seiten der ersten Fassung (`refs.entry`, kein Grund) werden weiter dargestellt.
- Prüfung: nur die Existenz des Formulars (`reasons.*.template`), damit eine später zurückgezogene Vorlage eine Seite nicht unspeicherbar macht. Öffentlich erscheint ein Grund nur, solange sein Formular veröffentlicht und nicht archiviert ist; ohne verfügbaren Grund bleibt das Widget leer, die Vorschau nennt den Grund.
- Darstellung: `data-config` mit Gründen und Adressen (`/anfrage/formular/{vorlage}?anliegen=…&modus=…`); `resources/js/inquiry-widget.js` zeigt die Auswahl, lädt erst nach der Wahl das Formular des Grundes und hält je Grund eine Instanz. Dialog als natives `dialog`. Vorauswahl über `?grund=Kennung`.
- Vorschau-Iframes im Seiteneditor laden nur Stile: Die Widget-Ansicht lädt dort `resources/js/inquiry-embed.js` (eigener Vite-Einstieg); der Dialog steht dort als gerahmtes Beispiel.
- Platz: 3 oder 4 Rastereinheiten; Breite, Abstände und Feldanordnung sind Einstellungen, Umbrüche folgen der Containerbreite.
- Sprungmarke: Ein Abschnitt mit Sprungmarke lässt sich mit Links wie `/kontakt?grund=kurse_workshops#anfrage` ansteuern.
## 5. Neues Widget hinzufügen
1. Klasse unter `app/Domain/Cms/Widgets/Types/` anlegen, von `WidgetType` ableiten. Pflicht: `key()`, `label()`, `description()`, `dataRules()`, `dataFields()`. Je nach Bedarf: `variants()`, Layoutvertrag `supportedUnits()`/`preferredUnits()`/`heights()`/`stages()`/`narrowBehavior()` (Abschnitt 12), `settings()`/`settingLabels()` (Bezeichnung und Erklärung für das (i))/`settingGroups()`/`settingHiddenWhen()`/`optionIcons()`, `mediaSchema()` für den Reiter „Medien“, `refRules()`, `refFields()`, `clean()` (Links mit `SafeUrl`, Text mit `RichText::sanitize`, Bilder mit `ImageRefFields::clean`), `resolve()`, `mediaPaths()`, `summary()`, `schematic()`, `icon()`.
@@ -0,0 +1,162 @@
# Kommunikationsverwaltung: Anfragevorlagen, Anfrage-Einstiege und Posteingang
Stand: 27.11.2026. Entscheidung: ADR-60 im [Entscheidungsprotokoll](12_Entscheidungsprotokoll_ADR.md). Auftrag: Entwicklungsauftrag von Lars vom 27.11.2026 („Zentrale Kommunikationsverwaltung mit dynamischem Anfrage-Widget“).
Leitprinzip: **Eine zentrale Kommunikationsverwaltung für alle Inhalte und Prozesse. Ein schlankes CMS-Widget für die Platzierung. Ein gemeinsamer Anfrageservice für alle Anfragen.**
## 1. Bestandsanalyse (Schritt 1 des Auftrags)
Belegt im Repository vor der Umsetzung:
| Thema | Befund |
|---|---|
| Kontakt- oder Anfragemodelle | keine (kein Modell, keine Tabelle, kein Formular) |
| E-Mail und Warteschlange | Laravel-Mail; `MAIL_MAILER=log` in der Vorgabe, auf Servern über `/etc/luf/*.env`; Warteschlange `database`; ein Postausgang (`OrderConfirmed`), direkt gesendet |
| Verwaltung | Filament 5, Gruppen „Inhalte“, „Katalog“, „Verkauf“, „Stammdaten“; Listen über `ListsCatalog` und die gemeinsame Bestandsliste; Rechte über `StaffRole` |
| CMS | Widget-Registry (ADR-30, `config/cms.php`), Abschnitte mit Plätzen (ADR-38), Revisionen, Vorschau; öffentliche Seiten ohne Livewire, Skripte über Vite |
| Rechte | `User::hasStaffRole()`, mehrere Rollen je Konto; Rollen Redakteur, Katalogverwalter, Kundenbetreuung, Systemverwalter u. a. |
| Sitzung und CSRF | Web-Gruppe mit Sitzung und CSRF auch auf öffentlichen Routen (Warenkorb, Anmeldung); ADR-32 (sitzungsfreie Seiten) ist Entwurf und nicht umgesetzt |
Die im Auftrag genannten Unterlagen `docs/00_LUF_Projektkompass.md` und `docs/01_LUF_Zielbild_und_Fachkonzept_v1.1.md` gibt es unter diesen Pfaden im Repository nicht. Herangezogen wurden stattdessen `docs/architektur/01_Zielbild_und_Faehigkeiten.md`, `cms-widget-registry.md`, `designsystem.md`, `website-cms-marketing-zielarchitektur.md`, `docs/fachkonzept/*`, `docs/prinzipien/*` und `12_Entscheidungsprotokoll_ADR.md`. Inhalte der fehlenden Dokumente wurden nicht erfunden.
Abweichungen und Einordnung: Die Produkt- und Lizenzarchitektur bleibt unverändert; es entsteht kein Bezug zu Konten, Lizenzen oder Kauf. Das Startseiten-Redaktionskonzept liegt nicht vor; die Besucherführung nach §21 (Links „Über Kursangebote informieren“ und „Hier unverbindlich anfragen“) wird als Redaktionsschritt beschrieben (Abschnitt 9), nicht per Migration in bestehende Seiten geschrieben.
## 2. Bausteine
| Baustein | Ort |
|---|---|
| Modelle und Logik | `app/Domain/Communication/` |
| Verwaltung | `app/Filament/Resources/Communication/` (Anliegen, Felder, Gruppen, Vorlagen, Einstiege, Anfragen), Seite `KommunikationEinstellungen`, `app/Filament/Support/TemplateEditor.php` |
| Öffentliche Schnittstelle | `InquiryFormController` (`/anfrage/{einstieg}`, `/zustand`, `/senden`), `InquiryPreviewController` (`/redaktion/anfrage/…`) |
| Darstellung | `resources/js/inquiry-form.js`, `resources/css/components/lf-anfrage.css`, Komponente `x-inquiry.mount` |
| CMS | Widget `inquiry` (`app/Domain/Cms/Widgets/Types/InquiryWidget.php`, `resources/views/widgets/inquiry.blade.php`) |
| Benachrichtigung | `SendInquiryNotification`, `InquiryReceived`, `CommunicationTestMail` |
| Beispiele | `ExampleConfiguration` (nur auf Wunsch aus „Einstellungen“) |
Wiederverwendet: Filament-Formularkomponenten, gemeinsame Bestandsliste (`ListsCatalog`, `ShowsBestand`), Widget-Registry, Warteschlange, Mail, Rechte über `StaffRole`, Designtokens (`tokens.css`).
## 3. Datenmodell
Alle Tabellen sind neu (Migration `2026_12_03_100000_create_communication_tables`):
- `inquiry_issues`: Anliegen und Unteranliegen (`parent_id`), stabile Kennung, Bezeichnung, Reihenfolge, aktiv, archiviert.
- `inquiry_fields`: Feldkatalog (Kennung, fachliche und öffentliche Bezeichnung, Hilfetext, Typ, Auswahlwerte mit stabilen Kennungen, Grenzen, Verwendung in der Anfrageübersicht).
- `inquiry_field_groups`: geordnete Liste von Feldern mit Pflichtangabe.
- `inquiry_templates` und `inquiry_template_versions`: Entwurf (`draft`) und unveränderliche, aufgelöste Fassungen mit Quelle (`source`).
- `inquiry_entries`: Konfiguration (`config`) und veröffentlichter Stand (`published_config`).
- `inquiries`: Anfrage mit Fassungsbezug, Kontaktspalten (zur Anzeige), `answers` (Schnappschuss je Antwort: Kennung, Bezeichnung, Typ, Wert, Anzeigetext, Schritt, Gruppe), Quellseite, Status, Benachrichtigungsstand, Einmalkennung.
- `inquiry_notes`: interne Notizen. `communication_settings`: Empfänger und Aufbewahrungsdauer.
Feldtypen: Text, mehrzeiliger Text, E-Mail, Telefon, Zahl, Einfachauswahl, Mehrfachauswahl, Ja/Nein, Datum, Zeitraum. Ein neuer technischer Typ ist eine kontrollierte Softwareerweiterung (`FieldType`, `FieldValue`, `inquiry-form.js`).
## 4. Bedienung in der Verwaltung
Gruppe „Kommunikation“ (Menüreihenfolge: Anfragen, Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen, Anfrage-Einstiege, Einstellungen).
1. **Anliegen und Unteranliegen** anlegen (Dialog), bearbeiten, mit „Nach oben/unten“ sortieren, deaktivieren oder archivieren. Die Kennung entsteht einmal aus der Bezeichnung; Umbenennen ändert sie nie.
2. **Feldkatalog:** Feld mit Typ anlegen; bei Auswahlfeldern die Werte als Liste pflegen (Kennungen bleiben bei Umbenennung stabil). Grenzen (Länge, kleinster und größter Wert) und die Verwendung („E-Mail-Adresse für Rückfragen“, Name, Telefon, Organisation, Nachricht) einstellen. Jede Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“.
3. **Feldgruppen:** Felder in Reihenfolge, je Feld Pflicht ja/nein.
4. **Anfragevorlage:** Reiter *Aufbau* (Schritte; je Schritt Bausteine: Auswahl des Anliegens, Feldgruppe, Einzelfeld), *Regeln* (Wirkung, Ziel, Bedingungen, alles als Auswahl), *Texte* (Überschrift, Beschreibung, Fragen, Schaltflächen, Zusammenfassung, Bestätigung, Fehlermeldung, Datenschutzhinweis). Aktionen: **Vorschau** (gespeicherter Entwurf, wählbar als Kompaktformular oder mehrstufiger Dialog), **Konfiguration prüfen**, **Veröffentlichen** (Dialog nennt die betroffenen Einstiege; Bemerkung zur Fassung). Unter „Fassungen“: wieder in Kraft setzen oder als Entwurf laden.
5. **Anfrage-Einstieg:** Vorlage, zugelassene Anliegen und Unteranliegen, Vorauswahl (zum Beispiel Kursformat „Schul-AG“), Formularart (kompakt oder mehrstufig), Öffnung (direkt oder erst per Schaltfläche), Texte überschreiben. Aktionen: Vorschau, Veröffentlichen, Zurückziehen, Archivieren.
6. **Posteingang** „Anfragen“: Suche, Filter, Sortierung; Detail mit Antworten, Status, Notizen, erneutem Versand der Benachrichtigung und (nur Systemverwaltung) Löschen.
7. **Einstellungen:** Empfänger, Aufbewahrungsdauer, Testnachricht, Beispielkonfiguration.
## 5. Regeln und Prüfungen
Gespeichert wird immer, veröffentlicht nur eine gültige Konfiguration. Beim Veröffentlichen prüft `TemplateCompiler`: Verweise auf verfügbare Gruppen und Felder, doppelte Verwendung, Ziele und Wirkungen, Bedingungsquellen (nur Auswahl- und Ja/Nein-Felder sowie Anliegen), gültige Vergleichswerte, **Reihenfolge (Quelle vor Ziel)**, Vorbelegungen, Widersprüche (gleiche Bedingung zeigt und blendet aus), genau ein Feld je Verwendung, mindestens ein Feld „E-Mail für Rückfragen“.
Auswertung (`FormEvaluator`): ein Durchlauf in Dokumentreihenfolge; Bedingungen sehen nur sichtbare Felder davor; ein ausgeblendetes Feld, eine ausgeblendete Gruppe oder ein übersprungener Schritt liefern keine Werte.
## 6. Anfrageverarbeitung
`InquiryService::submit`: Token (verschlüsselt: Einstieg, Fassung, Zeitpunkt, Einmalkennung) → Doppelsendung erkennen → Fassung und wirksames Formular → Köderfeld und Mindestdauer → Eingaben auswerten und prüfen → Transaktion → Benachrichtigung nach dem Speichern. Fehlerantworten: 422 mit Feldmeldungen, 419 abgelaufen (der Browser holt einmal ein neues Token und sendet erneut), 429 zu schnell oder zu häufig, 410 nicht mehr verfügbar.
## 7. Berechtigungen und Sicherheit
| Funktion | Rollen |
|---|---|
| Anliegen, Felder, Gruppen, Vorlagen, Einstiege, Vorschau | Redakteur, Systemverwalter |
| Posteingang, Notizen, Status, Einstellungen | Kundenbetreuung, Systemverwalter |
| Anfrage löschen | Systemverwalter |
| Widget „Anfrage“ im CMS | wie das übrige CMS (Redakteur); sieht nur Name der veröffentlichten Einstiege |
Maßnahmen: serverseitige Prüfung aller Werte, nur bekannte Schlüssel, nur angebotene Auswahlwerte, Ausgabe stets maskiert (Blade und `textContent`), Ratenbegrenzung (5 je Minute und 20 je Stunde je Adresse für das Senden, 120 je Minute für die Zustandsabfrage), Größenbegrenzung der Eingaben, keine Kontaktdaten in der Benachrichtigung, keine öffentliche Angabe von Empfängern.
## 8. Versionierung und Veröffentlichung
Entwurf → Prüfen → Vorschau → Veröffentlichen als neue Fassung. Fassungen sind unveränderlich (das Modell verweigert Änderung und Löschen). Eine Anfrage speichert Fassung und Bezeichnungen. Ein Einstieg zeigt immer die gültige Fassung seiner Vorlage; die CMS-Seite enthält nur die Einstiegs-Kennung und wird nie umgeschrieben.
## 9. Einbindung im CMS und Besucherführung
Im Seiteneditor: Widget „Anfrage“ einfügen, einen veröffentlichten Einstieg wählen, speichern und veröffentlichen. Mehr gibt es im CMS nicht zu pflegen. Für die Sprungmarke des Abschnitts („Anfrage“ als Sprungmarke `anfrage`) funktionieren Links wie `/kurse#anfrage` mit dem Linkwähler.
Besucherführung nach §21 (Redaktionsschritte, nicht Teil der Migration): Startseite „Über Kursangebote informieren“ und Hero „Kurse & Workshops“ führen auf die künftige Kursübersichtsseite; dort steht oben „Hier unverbindlich anfragen“ mit Ziel `#anfrage` auf das eingebundene Widget; ein allgemeiner Kontaktweg gehört in Navigation oder Fußbereich (Seite mit dem Einstieg „Allgemeiner Kontakt“).
## 10. Beispielkonfiguration
„Einstellungen → Beispielkonfiguration anlegen“ (nur in leerer Verwaltung) legt an und veröffentlicht: vier Anliegen mit zwei Unteranliegen (sechs Einträge), 38 Felder, 12 Feldgruppen, vier Vorlagen und fünf Einstiege: *Allgemeiner Kontakt* (kompakt, Name, E-Mail, Nachricht), *Kurse & Workshops* (mehrstufig, Information oder konkretes Vorhaben mit Einrichtung, Träger, Durchführungsort, Kindergruppe, Planung), *Schul-AG* (mehrstufig, Format und konkretes Vorhaben vorausgewählt, Zusatzfragen zur Laufzeit), *Programme & Materialien*, *Kooperation*. Alles ist gewöhnliche Konfiguration und in der Verwaltung änderbar.
## 11. Offene fachliche und rechtliche Prüfpunkte
- Datenschutzhinweis (Wortlaut), Rechtsgrundlage und Informationspflichten mit dem Datenschutzkonzept abgleichen; keine Pflicht-Einwilligungsbox ohne Prüfung.
- Aufbewahrungsdauer festlegen; ein Zeitplaner für `communication:purge` ist nicht eingerichtet (Betrieb).
- E-Mail-Versand auf den Servern: `MAIL_*` in `/etc/luf/test.env` und `/etc/luf/prod.env`; solange `MAIL_MAILER=log` gilt, kommt keine Nachricht an (der Posteingang vermerkt dennoch „gesendet“, weil der Mailer die Nachricht annimmt). Wirksamkeit mit der Testnachricht in den Einstellungen prüfen.
- Kursformate sind Arbeitsvorschläge; das Formular darf keine Termine, Preise oder Buchung suggerieren (Texte der Beispiele sind entsprechend formuliert).
- Spam-Schutz: Köderfeld, Mindestdauer und Ratenbegrenzung. Ein externes Captcha ist nicht eingebaut (Datenschutz); bei Missbrauch nachrüsten.
- Texte des Beispiels sind Entwürfe des Betreibers zur Prüfung.
## 12. UX-Überarbeitung (ADR-61)
Stand: 27.11.2026. Menü der Gruppe „Kommunikation“: **Anfragen**, **Formulare & Befragungen**, **Einstellungen**. Die Abschnitte 4 und 9 gelten für Anliegen, Feldkatalog, Feldgruppen und Einstiege weiter, nur ohne eigenen Menüpunkt; erreichbar sind sie unter „Einstellungen → Weitere Bausteine“.
### Formular bearbeiten
1. „Formulare & Befragungen“ → „Formular anlegen“ (Name) → der Editor öffnet.
2. Reiter **Aufbau:** Bereiche (Titel, Einleitung, Bedingung), darin „Feld oder Teilbereich hinzufügen“.
- **Feld:** Frage, Art der Antwort (nach dem Speichern fest), Auswahlwerte, Hilfetext, Pflicht, Bedingung; „Vorhandenes Feld verwenden“ übernimmt ein Feld aus dem Katalog (zum Beispiel die E-Mail-Adresse). Unter „Weitere Einstellungen“ die Verwendung in der Anfrageübersicht. Jedes Formular braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“.
- **Teilbereich:** Überschrift für die folgenden Felder, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“.
- **Frage nach dem Anliegen:** die Auswahl des Anliegens (angebotene Anliegen).
- **Bedingung** (Feld, Teilbereich, Bereich): „nur anzeigen, wenn …“, „ausblenden, wenn …“, bei Feldern „Pflichtfeld, wenn …“, bei Bereichen „überspringen, wenn …“. Beispiel: Teilbereich „Angaben zur Schule“ nur anzeigen, wenn „Sind Sie eine Schule?“ = Ja.
3. Reiter **Texte:** Überschrift, Beschreibung, Schaltflächen, Bestätigung, Datenschutzhinweis. Reiter **Weitere Regeln:** nur, was sich nicht an ein Element heften lässt (zum Beispiel Vorbelegungen).
4. **Speichern**, **Konfiguration prüfen**, **Vorschau** (als langes Formular oder mehrstufig, es wird nichts gesendet), **Veröffentlichen** (neue Fassung, sofort gültig überall, wo das Formular eingebunden ist), Fassungen unten (zurückkehren möglich).
Ein Feld, das mehrere Formulare nutzen, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare. Die Änderung gilt dort mit deren nächster Veröffentlichung.
### Widget „Anfrage“ im Seiteneditor
- Reiter **Inhalt:** **Anfragegründe** (Bezeichnung, Kurzbeschreibung, Formular, optional Anliegen und Unteranliegen vorwählen), Frage der Auswahl, Beschriftung des Buttons. Die Kennung eines Grundes (für Links) entsteht beim Speichern.
- Reiter **Darstellung:** **Formularführung** (langes Formular oder mehrstufig, Schritt für Schritt) und **Präsentation** (im Abschnitt oder im Pop-up-Fenster über der Seite) getrennt; Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten ergibt sich aus der verfügbaren Breite.
- **Vorauswahl durch einen Button der Seite:** Link auf die Seite mit `?grund=Kennung` (und gegebenenfalls `#Sprungmarke`). Das Widget wählt den Grund und öffnet bei „Dialog“ den Dialog.
- Mehrere zulässige Gründe: Der Besucher sieht zuerst die Frage, danach nur das Formular seines Grundes („Anderen Grund wählen“ wechselt, Eingaben bleiben je Grund erhalten). Ein einziger Grund: kein Auswahlschritt.
- Vorschau im Dialog des Widgets, in der Seitenvorschau und in der Geräteansicht.
### Öffentliche Adressen und Grenzen
`/anfrage/formular/{vorlage}` (Beschreibung und Token), `/zustand`, `/senden`; Grund in der Adresse (`anliegen`, `unteranliegen`, `modus`). Dieselbe Ratenbegrenzung wie bei Einstiegen. Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. Nicht umgesetzt: Vorbelegung weiterer Felder (zum Beispiel Kursformat) je Anfragegrund; dafür bleibt der Anfrage-Einstieg.
## 13. Formularansicht des Aufbaus (ADR-62)
Der Aufbau eines Formulars ist eine eigene Ansicht statt einer Filament-Liste.
### Aufbau der Ansicht
- **Bereich** (im mehrstufigen Dialog ein Schritt): Karte mit Nummer, Titel und Symbolen für Einleitung, Bedingung, weitere Einstellungen und Entfernen. Darunter die Felder und Teilbereiche, am Ende „Neues Feld“, „Vorhandenes Feld einfügen“, „Teilbereich“ und (einmal im Formular) „Frage nach dem Anliegen“.
- **Teilbereich:** eingerahmte Einheit im Bereich mit Überschrift, Symbolen und eigener Feldliste („Neues Feld im Teilbereich“). Die Bedingung gilt für alle Felder darin.
- **Feld:** eine Zeile mit Griff, Frage, Art der Antwort und Pflicht. Symbole öffnen Pop-ups: Hilfetext, Auswahlwerte (nur bei Auswahlfeldern, mit Zähler), Bedingung, weitere Einstellungen. Die Art ist nach dem ersten Speichern gesperrt.
- **Bedingung:** Wirkung, „alle/mindestens eine“, Vergleiche auf Felder oberhalb des Elements und die Frage nach dem Anliegen; als Satz unter dem Element sichtbar. Verweist eine Bedingung nach einer Verschiebung auf ein Feld darunter, ist das Symbol gelb markiert.
- **Weitere Einstellungen:** Verwendung in der Anfrageübersicht, Hinweis auf gemeinsame Verwendung, „Verschieben nach …“.
- **Rückgängig** bis zum Speichern; Hinweiszeile mit Anzahl der Bereiche, Felder und Teilbereiche.
### Bedienung
- **Ziehen:** am Griff; Felder in jeden Bereich und Teilbereich, Teilbereiche zwischen Bereiche, Bereiche untereinander.
- **Tastatur:** Griff fokussieren, Pfeil hoch oder runter; am Rand eines Teilbereichs verlässt das Feld ihn. „Verschieben nach …“ setzt ein Element ans Ende eines Bereichs oder Teilbereichs.
- **Fehlende Angaben** (Titel, Frage, Auswahlwerte) sind rot umrandet; Speichern nennt die Gründe und ändert nichts.
### Technik
`TemplateEditor` liefert die Ansicht über ein `ViewField` (`editor_json`). Der Browser führt den Baum (Alpine, `form-editor-script.blade.php`) und schreibt ihn beim Speichern als Text. `FormEditor::validateTree` prüft, `fromTree` überführt ihn in die flache Ansicht, `persist` schreibt Katalog und Entwurf wie bisher; `toTree` ist die Gegenrichtung beim Öffnen. Nach dem Speichern liefert der Server den Baum mit festen Kennungen, die Ansicht übernimmt ihn (sonst legte ein zweites Speichern Felder doppelt an). Keine Migration.
### Grenzen
Ziehen auf Berührungsbildschirmen und Screenreader-Ansagen sind nicht geprüft. Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. Die Regelliste „Weitere Regeln“ ist unverändert.
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more