Compare commits

...
Author SHA1 Message Date
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
LarsandClaude Sonnet 5.5 9e2d64a4a9 Ergänze das CMS-Widget Hinweiszeile mit optional aufklappbarer Kurzdarstellung
CI Feature / test (push) Canceled after 0s
Deploy Test / test (push) Successful in 4m37s
Deploy Test / deploy (push) Successful in 32s
Neues Widget notice (ADR-59): vollständiger Text und Kurztext als formatierte Texte, drei Modi (Volltext, responsiv mit Zeilengrenze, immer mit Kurzdarstellung), Symbol, Schriftgrößen XS bis L, Fläche, Rahmen und Akzentlinie. Der Server liefert immer den vollständigen Text; notice.js klappt ein und steht beim ersten Hinweis inline, damit nichts nach dem Laden springt (CLS 0,000).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 13:32:54 +01:00
LarsandClaude Sonnet 5.5 a12818b752 Verteile die redaktionellen Karten ausgewogen auf Zeilen mit Mindestbreite
Deploy Test / test (push) Successful in 5m48s
Deploy Test / deploy (push) Successful in 42s
Raster und hervorgehobene Variante umbrechen jetzt wie Text (Flex) statt im
Grid: Jede Karte ist mindestens 15 rem breit (mit Symbol neben dem Text
18 rem) und wandert bei Unterschreitung in die nächste Zeile. Die Zeilen
sind ausgewogen und unterscheiden sich um höchstens eine Karte (fünf Karten
3 + 2, zehn Karten 4 + 3 + 3) bei 1 bis 12 Karten.

Die Zahl je Zeile steht als erzeugte Tabelle in
lf-karten-verteilung.css (Generator scripts/cards-balance-css.py); das
Stylesheet liest die Zahl der Karten per :has(> .card:nth-child(n)), das
Markup bleibt unverändert. "Abstände gleichen aus" nutzt space-evenly,
mit Trennstrich bleiben die Spalten gleich breit.

Tests: Tabelle für 2 bis 12 Karten und alle Breiten, Mindestbreite, Flex.
Gemessen im Browser für 1 bis 12 Karten, vier Anordnungen, sechs Breiten.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 09:47:31 +01:00
LarsandClaude Sonnet 5.5 2393000468 Biete in den redaktionellen Karten einen sichtbaren Link unter dem Text an
Deploy Test / test (push) Successful in 5m43s
Deploy Test / deploy (push) Successful in 43s
Einstellung link_style (Textlink oder Pille) und je Karte ein Linktext
(leer: "Mehr erfahren", nur mit Linkziel gespeichert). Der Link trägt den
gestreckten Link über die ganze Karte, der Titel ist dann kein eigener
Link; ohne Einstellung bleibt alles wie zuvor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 09:11:01 +01:00
Lars 333e2975d5 Merge branch 'feature/symbol-zivilcourage-helfen' into feature/redaktionelle-karten 2026-11-27 09:04:11 +01:00
LarsandClaude Sonnet 5.5 ef876465f0 Baue die redaktionellen Karten aus: formatierte Beschreibung, Dachzeile, Verteilung, Symbollage und Gestaltung
Widget cards, Version 2:
- Beschreibung im Editor des Fließtexts (Webprofil). Version 1 (Klartext)
  wird beim Lesen angehoben: Leerzeile = Absatz, Zeilenumbruch = <br>.
- Dachzeile über dem Titel (nur gespeichert, wenn ausgefüllt).
- Verteilung: Karten vergrößern sich (Vorgabe, auto-fit statt auto-fill) oder
  Abstände gleichen aus (feste Kartenbreite, gleich breite Spalten).
- Symbol über, links oder rechts neben dem Text, senkrecht oben/Mitte/unten.
- Pinselstrich unter dem Titel, Trennstrich (flache Karten), Hervorhebung
  unter der Maus und bei Fokus (ohne Bewegung bei reduzierter Bewegung).
- Hervorgehobene Variante umbricht per Flex, damit die übrigen Karten die
  Zeile teilen. Links in der Beschreibung liegen über dem gestreckten
  Titellink; Textfarben in hellen Karten gelten wie auf hellen Flächen.
- Symbolfeld: Duplizieren einer Karte mit Symbol warf einen Skriptfehler
  (Vorlage noch nicht als Referenz da); behoben.

Test angepasst: CmsHeadingIntroTest prüft den Selektor mit .widget-cards
(Prosa-Regeln gelten jetzt auch in Karten).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 09:04:11 +01:00
LarsandClaude Sonnet 5.5 510ae7944c Biete das neue Motiv Zivilcourage zusätzlich als zivilcourage-helfen an
Das Motiv aus ergaenzung/zivilcourage.svg unterscheidet sich vom vorhandenen
(eine Person hilft einer anderen). Der Schlüssel zivilcourage bleibt
unverändert, weil er in gespeicherten Seiten steht; das neue Motiv erhält
einen eigenen Schlüssel in der Gruppe "Schutz und Grenzen".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 08:26:13 +01:00
Lars c8d44caa75 Merge remote-tracking branch 'origin/develop' into feature/abschnitte-sprungmarken
Deploy Test / test (push) Successful in 4m39s
Deploy Test / deploy (push) Successful in 32s
2026-11-27 08:19:27 +01:00
LarsandClaude Sonnet 5.5 cbc6b30a6d Nimm 24 weitere Symbole in die Bibliothek auf
Deploy Test / test (push) Successful in 4m42s
Deploy Test / deploy (push) Successful in 31s
Quelle: docs/Brand-UI-Kit/17_Symbolbibliothek/ergaenzung. Neue Gruppe
"Zielgruppen und Einrichtungen" (Eltern, Gruppen, Kita, Öffentliche
Einrichtungen, Schulen, Verein); die übrigen Symbole stehen in den
bestehenden Gruppen. Versionssuffixe (_v05, _v06) entfallen aus dem
Schlüssel; relevant_v06 hat Vorrang vor relevant.

zivilcourage ist ein anderes Motiv als das vorhandene und wird nicht
überschrieben (Schlüssel stehen in gespeicherten Seiten).

Der Import bereinigt jetzt Dateien aus Zeichenprogrammen (XML-Vorspann,
baseProfile, leere defs, fehlender title); elf der neuen Dateien hatten
einen XML-Vorspann, den der Loader inline in die Seite geschrieben hätte.
Tests: jede Datei beginnt mit dem svg-Tag, Zielgruppen-Gruppe vollständig.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 08:15:06 +01:00
LarsandClaude Sonnet 5.5 bd6b62b4e3 Löse den Prüflauf ein zweites Mal aus: Lauf 5225 wurde abgebrochen
CI Feature / test (push) Successful in 4m48s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 08:14:14 +01:00
LarsandClaude Sonnet 5.5 010b4fedd4 Löse den Prüflauf erneut aus: Lauf 5224 schlug ohne lokal reproduzierbaren Grund fehl (1162 Tests und Pint lokal grün)
CI Feature / test (push) Canceled after 0s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 08:08:32 +01:00
LarsandClaude Sonnet 5.5 c5d93737ec Beschrifte die Bestätigung im Werkzeug für interne Links mit Link setzen
CI Feature / test (push) Failing after 6m22s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:54:42 +01:00
LarsandClaude Sonnet 5.5 e29014a8a1 Benenne die Schaltfläche der Sprungmarke und lass Esc im Linkdialog nur den Dialog schließen
CI Feature / test (push) Successful in 5m48s
Deploy Test / test (push) Successful in 6m13s
Deploy Test / deploy (push) Successful in 42s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:38:07 +01:00
LarsandClaude Sonnet 5.5 c33e47fadd Dokumentiere Abschnittsnamen, Sprungmarken, Ausblenden und die Linkauswahl
CI Feature / test (push) Successful in 6m38s
Deploy Test / test (push) Successful in 5m52s
Deploy Test / deploy (push) Successful in 42s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:12:36 +01:00
LarsandClaude Sonnet 5.5 04a9a4f83f Lass Menüeinträge auf eine Sprungmarke der Zielseite zeigen
Zweiter Schritt in „Ziel ändern“, neue Spalte navigation_items.anchor (nullable, abwärtskompatibel).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:05:22 +01:00
LarsandClaude Sonnet 5.5 6b43fbb7d1 Verlinke interne Seiten und Sprungmarken auch im formatierten Text der Website
Neues Werkzeug neben dem freien Link in Fließtext, Überschrift-Einleitung und Bild-Text.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:03:17 +01:00
LarsandClaude Sonnet 5.5 6172364bf8 Biete in allen Widget-Linkfeldern einen Dialog für interne Seiten und Sprungmarken an
Zweistufig (Seite, dann Sprungmarke) mit Veröffentlichungszustand und den noch
ungespeicherten Marken der bearbeiteten Seite. Schreibt nur die Adresse ins Feld.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:00:57 +01:00
LarsandClaude Sonnet 5.5 ed53bb1669 Zeige Name, Sprungmarke und Ausgeblendet im Seitenaufbau und biete die Felder am Abschnitt an
Kopierte Abschnitte geben ihre Sprungmarke ab, damit die Seite weiter speicherbar bleibt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 06:57:38 +01:00
LarsandClaude Sonnet 5.5 3a37e8a7a1 Speichere Name, Sprungmarke und Ausblenden je Abschnitt und gib sie auf der Website aus
Name nur zur Orientierung, Sprungmarke als Element-Kennung (je Seite eindeutig,
reservierte Kennungen gesperrt), ausgeblendete Abschnitte erscheinen nie öffentlich
und zählen weder für die Hauptüberschrift noch für Trenner. SafeUrl nimmt #marke an.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 06:57:38 +01:00
LarsandClaude Sonnet 5.5 00b7ce9b3f Schreibe die Einleitung der Überschrift im Editor des Fließtexts
CI Feature / test (push) Canceled after 0s
Deploy Test / test (push) Successful in 6m21s
Deploy Test / deploy (push) Successful in 41s
Das Widget Überschrift und Einleitung (jetzt Version 2) nimmt die Einleitung als formatierten Text: Absätze, Zeilenumbrüche, Auszeichnungen, Schriftgröße, -farbe und Ausrichtung wie im Fließtext. Die Regeln für .prose gelten auch für die Überschrift. Klartext der Version 1 wird beim Lesen zu Absätzen mit Zeilenumbrüchen angehoben. Drei Tests erwarteten das alte Markup der Einleitung und wurden bewusst angepasst.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 17:01:56 +01:00
LarsandClaude Sonnet 5.5 bd91104970 Setze die Abspiel-Schaltfläche groß und mittig auf das Vorschaubild
Deploy Test / test (push) Successful in 6m38s
CI Feature / test (push) Successful in 6m4s
Deploy Test / deploy (push) Successful in 43s
Einstieg (Teaser) und Premium-Karten (Medien-, Programm-, Modul-, Bild-und-Text-Karte) gestalten sie gleich: großer Kreis, halbtransparent, mittig auf dem Bild; läuft der Clip, wird sie zur kleinen Anhalten-Schaltfläche in der Ecke. Skripte, Beschriftungen und Tastaturbedienung bleiben unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 16:48:23 +01:00
LarsandClaude Sonnet 5.5 57f3a18b82 Biete im Fließtext Schriftgröße, Schriftfarbe und Ausrichtung an
Deploy Test / test (push) Successful in 6m28s
CI Feature / test (push) Successful in 6m8s
Deploy Test / deploy (push) Successful in 41s
Das Webprofil von FormattedText kennt zusätzlich Ausrichtung (zentriert,
rechtsbündig), Schriftgröße (klein, groß, sehr groß) und Schriftfarbe
(Marine, Grün, Rot, Grau) aus festen Werten. Verwaltung, Dokumente und PDF
lassen sie weg. Der Editor des Fließtexts bekommt die Werkzeuge dafür
(eigene Erweiterung für die Größe); auf der Seite werden Klassen und
Tokens statt Inline-Stilen ausgegeben, Farben passen sich dunklen und
grünen Flächen an.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 14:41:41 +01:00
LarsandClaude Sonnet 5.5 28bd5590bc Lass auf dem Tablet eine ganz leere Rasterzeile entfallen
CI Feature / test (push) Canceled after 0s
Deploy Test / test (push) Successful in 6m33s
Deploy Test / deploy (push) Successful in 42s
Bei vier gleich breiten Plätzen steht das Raster auf dem Tablet als 2 x 2. War die erste Zeile komplett leer, blieb ihr Zeilenabstand als Lücke über dem Inhalt stehen. Eine Zeile, in der alle Plätze leer sind, wird dort jetzt ausgeblendet; die Plätze danach rücken genau eine Zeile nach oben und bleiben in ihrer Spalte. Gefunden durch einen Vergleich aller Raster, Abschnittsbreiten, Abstände und Fensterbreiten (2400 Prüfungen).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 12:00:35 +01:00
LarsandClaude Sonnet 5.5 40f8a4afc2 Lass leere Plätze eines Abschnitts ihre Stelle behalten
Deploy Test / test (push) Successful in 6m9s
CI Feature / test (push) Canceled after 5m5s
Deploy Test / deploy (push) Successful in 47s
Bisher entfielen leere Plätze öffentlich und die übrigen Widgets teilten sich die Spalten: Bei 1 + 3 mit leerem ersten Platz stand das Widget in der schmalen linken Spalte. Jetzt rendert SectionRenderer für jeden Platz des Rasters eine Zelle und berechnet die Spalten aus allen Einheiten. Gestapelt (Smartphone, schmaler Abschnitt, Tablet bei ungleichen Rastern) ist der leere Platz ausgeblendet und lässt keine Lücke; ein Abschnitt ohne darstellbares Widget entfällt weiterhin.

Der Test zu den leeren Plätzen erwartet bewusst die neue Regel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 11:45:39 +01:00
LarsandClaude Sonnet 5.5 79b58903ac Gib dem Fließtext den Editor der Dokumente und lass Überschrift und Fließtext die volle Breite nutzen
CI Feature / test (push) Canceled after 0s
Deploy Test / test (push) Successful in 6m13s
Deploy Test / deploy (push) Successful in 41s
Fließtext Version 2: formatierter Text (bereinigtes HTML) im gemeinsamen Editor mit Zwischenüberschriften, fett, kursiv, Links, Listen, Zitat und Tabellen. Links auf eigene Seiten (/seite, #anker) bleiben im CMS erhalten (FormattedText mit internalLinks), in Verwaltung und PDF weiterhin nicht. Version 1 (Klartext) wird beim Lesen zu Absätzen. Tabellen stehen in einem scrollbaren, tastaturerreichbaren Rahmen. Das Maß für gespeichertes HTML steigt von 20000 auf 100000 Zeichen.

Neue Einstellung "Breite des Texts" für Überschrift und Fließtext: Vorgabe volle Breite des Platzes, wahlweise Lesebreite wie bisher (Überschrift 22 Zeichen, Text 70 Zeichen). Bestehende Seiten nutzen dadurch ohne Eingriff die ganze Breite.

Der Test zu "Altes Eingabeformat" erwartet bewusst das gespeicherte HTML der Version 2.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 11:35:25 +01:00
LarsandClaude Sonnet 5.5 5233b96c42 Biete in Bild und Text einen Bildanteil, Bild ohne Text und ein Video auf dem Bild an
Deploy Test / test (push) Successful in 5m44s
CI Feature / test (push) Successful in 6m17s
Deploy Test / deploy (push) Successful in 41s
Neue Einstellung "Bildanteil" (Bild zu Text von 1:2 bis 2:1, nur im zweispaltigen Stand ab 900 px; ohne Wert bleibt die bisherige Verteilung). Der Text ist nur noch Pflicht, solange kein Bild gewählt ist; ein Bild darf allein über die ganze Breite stehen. Optional ein Video (refs.video, ein Film aus dem Medienmanager, gewählt über den gemeinsamen Picker): Der für die Website freigegebene Clip spielt auf dem Bild beim Überfahren stumm und per Klick mit Ton wie auf der Medienkarte (CardClip, card-clip.js). Ohne Versionssprung; gespeicherte Seiten bleiben unverändert.

Die Pflichtregel für den Text wird bewusst gelockert: "Bitte einen Text eingeben" gilt nur noch ohne Bild.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 11:02:18 +01:00
LarsandClaude Sonnet 5.5 3cf3e822b8 Belege Shop im CMS, Regeln fuer freie Artikel und die Shopliste im Abnahmeprotokoll
CI Feature / test (push) Successful in 5m9s
Deploy Test / test (push) Successful in 5m46s
Deploy Test / deploy (push) Successful in 40s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 09:39:25 +01:00
LarsandClaude Sonnet 5.5 6160e95d57 Merge remote-tracking branch 'origin/develop' into feature/shop-aufraeumen
CI Feature / test (push) Successful in 5m21s
Deploy Test / test (push) Successful in 5m17s
Deploy Test / deploy (push) Successful in 44s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 09:25:08 +01:00
LarsandClaude Sonnet 5.5 f0ffb47210 Biete in der Shopliste Auswahl, Reihenfolge, Listenansicht und Seiten
CI Feature / test (push) Successful in 6m4s
- ShopCatalog::listing mit Auswahl nach Thema, Materialart, Eignung und Nutzerkreis, Reihenfolge, Ansicht und Seiten
- Listenansicht shop/zeile, gemeinsame Liste fuer Shopseite und Widget (Variante Liste, Einstellung Auswahl fuer Besucher)
- Werte aus dem Abfragetext werden gegen vorhandene Werte geprueft, Felder als Liste und Zahlen ausserhalb des Bereichs sind harmlos
- Suchfeld heisst nach dem Umbau Zurücksetzen statt Suche zuruecksetzen (Test bewusst angepasst)
- ADR-57

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 08:35:33 +01:00
324 changed files with 16756 additions and 273 deletions

No files matched your search

+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;
}
}
+110 -21
View File
@@ -34,7 +34,17 @@ final class FormattedText
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
public const FIELDS = ['summary', 'description'];
private static ?HtmlSanitizer $sanitizer = null;
/** Schriftgrößen der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Werte stehen in `widgets.css`. */
public const SITE_SIZES = ['small' => 'Klein', 'large' => 'Groß', 'xlarge' => 'Sehr groß'];
/** Schriftfarben der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Farbwerte stehen in `widgets.css`. */
public const SITE_COLORS = ['marine' => 'Marine', 'gruen' => 'Grün', 'rot' => 'Rot', 'grau' => 'Grau'];
/** Ausrichtungen der Website außer der Vorgabe „linksbündig“ (so schreibt der Editor sie: `end` heißt rechtsbündig). */
private const SITE_ALIGNMENTS = ['center', 'end'];
/** @var array<string, HtmlSanitizer> je Profil eine Bereinigung (siehe sanitizer()) */
private static array $sanitizers = [];
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
public const TOOLBAR = [
@@ -53,8 +63,14 @@ public static function isHtml(?string $value): bool
/**
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
*
* `$site` ist das Profil der Website (CMS): Links auf Seiten der eigenen Website (`/materialien`, `#anker`) bleiben
* erhalten, dazu Ausrichtung (zentriert, rechtsbündig), Schriftgröße und Schriftfarbe aus festen Werten
* ({@see self::SITE_SIZES}, {@see self::SITE_COLORS}). Verwaltung und PDF kennen nur ausdrückliche Adressen
* (http, https, mailto) und keine dieser Auszeichnungen; sie fallen dort beim Speichern weg. Das Profil gehört zum Text:
* Wer mit `true` speichert, liest auch mit `true`.
*/
public static function canonical(?string $value): string
public static function canonical(?string $value, bool $site = false): string
{
$value = trim((string) $value);
@@ -62,18 +78,18 @@ public static function canonical(?string $value): string
return '';
}
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value), $site);
}
/**
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
* einem Blockelement beginnt.
*/
public static function canonicalHtml(?string $html): string
public static function canonicalHtml(?string $html, bool $site = false): string
{
$html = trim((string) $html);
return $html === '' ? '' : self::normalize($html);
return $html === '' ? '' : self::normalize($html, $site);
}
/**
@@ -85,9 +101,9 @@ public static function canonicalHtml(?string $html): string
*
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
*/
public static function html(?string $value, ?callable $images = null): string
public static function html(?string $value, ?callable $images = null, bool $site = false): string
{
return self::renderImages(self::canonical($value), $images);
return self::renderImages(self::canonical($value, $site), $images);
}
/**
@@ -454,10 +470,10 @@ public static function legacyToHtml(?string $text): string
return $html;
}
private static function normalize(string $html): string
private static function normalize(string $html, bool $site = false): string
{
$html = self::mapLegacyTags($html);
$html = trim(self::sanitizer()->sanitize($html));
$html = trim(self::sanitizer($site)->sanitize($html));
if ($html === '') {
return '';
@@ -466,6 +482,10 @@ private static function normalize(string $html): string
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
$body = $document->body;
if ($site) {
self::siteMarks($document);
}
// Ein Bild steht zwischen den Absätzen, in einem Absatz (so setzt der Editor es) oder in einer Tabellenzelle und braucht
// seine Bildfassung. Anderswo (Liste, Zitat, Überschrift) entfällt es.
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
@@ -528,7 +548,7 @@ private static function block(Node $node): string
$inner = self::inner($child);
if (! str_contains($inner, '<p>')) {
if (preg_match('/<p[\s>]/', $inner) !== 1) {
$inner = '<p>'.$inner.'</p>';
}
@@ -542,11 +562,67 @@ private static function block(Node $node): string
$inner = self::inner($node);
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
if ($name === 'blockquote' && preg_match('/<p[\s>]/', $inner) !== 1) {
$inner = '<p>'.$inner.'</p>';
}
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
// Die Ausrichtung ist im Webprofil schon auf `text-align: center|end` zurückgeführt (siehe siteMarks()).
$align = $name !== 'blockquote' && preg_match('/^text-align: (?:'.implode('|', self::SITE_ALIGNMENTS).')$/', (string) $node->getAttribute('style')) === 1
? ' style="'.$node->getAttribute('style').'"'
: '';
return self::hasContent($inner) ? '<'.$name.$align.'>'.$inner.'</'.$name.'>' : '';
}
/**
* Webprofil: Ausrichtung, Größe und Farbe auf feste Werte zurückführen. Stil und Klassen aus dem Editor oder von Hand
* sind nie maßgeblich: Ein Span trägt nur noch `class="color" data-color` (bekannter Schlüssel) und/oder `data-size`
* (bekannter Schlüssel), sonst entfällt er; Absatz und Zwischenüberschrift nur `style="text-align: center|end"`. So
* liest der Editor den Wert beim Öffnen wieder, und ein beliebiger Stil kommt nie auf die Seite.
*/
private static function siteMarks(HTMLDocument $document): void
{
foreach (iterator_to_array($document->querySelectorAll('span')) as $span) {
$color = (string) $span->getAttribute('data-color');
$size = (string) $span->getAttribute('data-size');
$color = array_key_exists($color, self::SITE_COLORS) ? $color : '';
$size = array_key_exists($size, self::SITE_SIZES) ? $size : '';
if ($color === '' && $size === '') {
while ($span->firstChild !== null) {
$span->parentNode->insertBefore($span->firstChild, $span);
}
$span->remove();
continue;
}
foreach (iterator_to_array($span->attributes) as $attribute) {
$span->removeAttribute($attribute->name);
}
if ($color !== '') {
$span->setAttribute('class', 'color');
$span->setAttribute('data-color', $color);
}
if ($size !== '') {
$span->setAttribute('data-size', $size);
}
}
foreach ($document->querySelectorAll('p, h3, h4, h5, h6') as $block) {
$align = preg_match('/(?:^|;)\s*text-align\s*:\s*(center|end|right)\s*(?:;|$)/i', (string) $block->getAttribute('style'), $match) === 1
? (strtolower($match[1]) === 'center' ? 'center' : 'end')
: null;
$block->removeAttribute('style');
if ($align !== null) {
$block->setAttribute('style', 'text-align: '.$align);
}
}
}
/**
@@ -694,16 +770,29 @@ private static function runsText(array $runs): string
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
}
private static function sanitizer(): HtmlSanitizer
private static function sanitizer(bool $site = false): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p')
if (isset(self::$sanitizers[$site ? 'site' : 'catalog'])) {
return self::$sanitizers[$site ? 'site' : 'catalog'];
}
// Das Webprofil lässt zusätzlich Spans (Größe, Farbe) und den Stil an Absätzen und Überschriften zu; siteMarks()
// führt beides danach auf feste Werte zurück. Verwaltung und PDF kennen weder Spans noch Stile.
$text = $site ? ['style'] : [];
$config = (new HtmlSanitizerConfig)
->allowElement('p', $text)
->allowElement('h3', $text)
->allowElement('h4', $text)
->allowElement('h5', $text)
->allowElement('h6', $text);
if ($site) {
$config = $config->allowElement('span', ['class', 'data-color', 'data-size']);
}
return self::$sanitizers[$site ? 'site' : 'catalog'] = new HtmlSanitizer(
$config
->allowElement('br')
->allowElement('h3')
->allowElement('h4')
->allowElement('h5')
->allowElement('h6')
->allowElement('strong')
->allowElement('em')
->allowElement('ul')
@@ -720,7 +809,7 @@ private static function sanitizer(): HtmlSanitizer
->allowElement('img', ['data-id', 'alt'])
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks(false)
->allowRelativeLinks($site)
->forceAttribute('a', 'rel', 'noopener noreferrer')
->withMaxInputLength(100000),
);
+131
View File
@@ -0,0 +1,131 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Cms\Sections\PageSections;
/**
* Interne Linkziele für die Auswahl im CMS: Seiten mit ihrem Veröffentlichungszustand und die Sprungmarken ihrer
* Abschnitte. Rein lesend; das Ergebnis ist eine Adresse, die in ein Linkfeld oder einen Menüeintrag geschrieben wird.
*
* Adressformen: „/pfad“, „/pfad#marke“ (andere Seite) und „#marke“ (dieselbe Seite). Sie bestehen SafeUrl.
*/
class LinkTargets
{
public function __construct(private readonly PageSections $sections) {}
/**
* Seiten für die Auswahl, nach Adresse sortiert. Suche in Titel und Adresse.
*
* @return list<array{id: int, titel: string, pfad: string, zustand: array{label: string, ton: string}, marken: int}>
*/
public function pages(string $search = '', ?int $exceptId = null): array
{
$needle = mb_strtolower(trim($search));
return Page::query()->with(['latestRevision', 'publishedRevision'])->orderBy('path')->get()
->reject(fn (Page $page): bool => $page->getKey() === $exceptId)
->map(fn (Page $page): array => [
'id' => (int) $page->getKey(),
'titel' => $page->latestRevision?->contentTitle() ?: $page->path,
'pfad' => $page->path,
'zustand' => $this->state($page),
'marken' => count($this->anchorsOf($page->latestRevision?->sections() ?? [])),
])
->filter(fn (array $page): bool => $needle === '' || str_contains(mb_strtolower($page['titel'].' '.$page['pfad']), $needle))
->values()
->all();
}
/**
* @return array{label: string, ton: string}
*/
public function state(Page $page): array
{
if ($page->published_revision_id === null) {
return ['label' => 'Nur Entwurf, öffentlich nicht erreichbar', 'ton' => 'offen'];
}
return $page->latestRevision !== null && $page->latestRevision->id !== $page->published_revision_id
? ['label' => 'Veröffentlicht · Entwurf neuer', 'ton' => 'gut']
: ['label' => 'Veröffentlicht', 'ton' => 'gut'];
}
/**
* Sprungmarken einer gespeicherten Seite: die des neuesten Entwurfs, je mit dem Hinweis, ob sie schon
* veröffentlicht sind und ob der Abschnitt ausgeblendet ist.
*
* @return list<array{anchor: string, label: string, hidden: bool, published: bool}>
*/
public function anchorsForPage(Page $page): array
{
$published = collect($this->anchorsOf($page->publishedRevision?->sections() ?? []))
->filter(fn (array $anchor): bool => ! $anchor['hidden'])
->pluck('anchor')
->all();
return array_map(
fn (array $anchor): array => $anchor + ['published' => in_array($anchor['anchor'], $published, true)],
$this->anchorsOf($page->latestRevision?->sections() ?? $page->publishedRevision?->sections() ?? []),
);
}
/**
* Sprungmarken der Abschnitte im Editor, auch ungespeicherte. Für „diese Seite“.
*
* @param list<array<string, mixed>> $sections Abschnitte im Modell (nach SectionEditor::fromEditorState)
* @return list<array{anchor: string, label: string, hidden: bool, published: bool}>
*/
public function anchorsInEditor(array $sections): array
{
return array_map(fn (array $anchor): array => $anchor + ['published' => false], $this->anchorsOf($sections));
}
/**
* @param list<array<string, mixed>> $sections
* @return list<array{anchor: string, label: string, hidden: bool}>
*/
public function anchorsOf(array $sections): array
{
$anchors = [];
foreach (array_values($sections) as $position => $section) {
$anchor = PageSections::cleanAnchor($section['anchor'] ?? null);
if ($anchor === null) {
continue;
}
$name = PageSections::cleanName($section['name'] ?? null);
$anchors[] = [
'anchor' => $anchor,
'label' => $name ?? 'Abschnitt '.($position + 1),
'hidden' => PageSections::isHidden($section['hidden'] ?? false),
];
}
return $anchors;
}
/**
* Adresse für ein Linkfeld: „/pfad“, „/pfad#marke“ oder (dieselbe Seite) „#marke“.
*/
public function href(?string $path, ?string $anchor): ?string
{
$anchor = $anchor !== null && $anchor !== '' ? PageSections::cleanAnchor($anchor) : null;
if ($path === null) {
return $anchor !== null ? '#'.$anchor : null;
}
return $path.($anchor !== null ? '#'.$anchor : '');
}
/**
* Vollständige öffentliche Adresse mit Sprungmarke, für Verweise von außen.
*/
public function publicUrl(Page $page, ?string $anchor = null): string
{
return $page->publicUrl().($anchor !== null && $anchor !== '' ? '#'.$anchor : '');
}
}
+5 -1
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Cms;
use App\Domain\Cms\Sections\PageSections;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Commerce\Shop;
use Illuminate\Database\Eloquent\Builder;
@@ -32,6 +33,7 @@ class NavigationItem extends Model
'label',
'page_id',
'url',
'anchor',
'placement',
'sort_order',
'is_visible',
@@ -86,7 +88,9 @@ public function href(): ?string
}
if ($this->page !== null) {
return $this->page->path === '/' ? url('/') : url($this->page->path);
$anchor = PageSections::cleanAnchor($this->anchor);
return ($this->page->path === '/' ? url('/') : url($this->page->path)).($anchor !== null ? '#'.$anchor : '');
}
if ($this->url === null || $this->url === '' || ! SafeUrl::isSafe($this->url)) {
+113 -8
View File
@@ -18,6 +18,13 @@
* Version 2 (Abstände): oben, unten und Widget-Abstand sind drei unabhängige Werte. Hüllen der Version 1 werden beim
* Lesen übersetzt (SectionStyle::migrateSpacing), ohne die Darstellung zu ändern; gespeicherte Revisionen bleiben.
*
* Optionale Felder des Abschnitts (abwärtskompatibel, fehlen in älteren Revisionen):
* - name: interner Name zur Orientierung im Seitenaufbau (nie öffentlich), höchstens 80 Zeichen;
* - anchor: Sprungmarke, wird als Element-Kennung des Abschnitts ausgegeben (Link „#marke“ oder „/pfad#marke“),
* je Seite eindeutig, nur Kleinbuchstaben, Ziffern und Bindestriche;
* - hidden: true blendet den Abschnitt auf der Website aus; er bleibt im Entwurf und in den Revisionen erhalten.
* Ältere Programmstände kennen „hidden“ nicht und würden einen ausgeblendeten Abschnitt zeigen (siehe Release-Vorbereitung).
*
* Jeder Slot enthält höchstens ein Widget aus dem zentralen Widget-Register. Abschnitte sind nicht verschachtelbar.
* Revisionen ohne Abschnitte (Bestand vor dieser Fassung) werden beim Lesen als einspaltige Abschnitte gelesen.
*/
@@ -29,6 +36,20 @@ class PageSections
public const MAX_WIDGETS = 60;
public const MAX_NAME = 80;
public const MAX_ANCHOR = 60;
/**
* Kennungen, die im Seitengerüst schon vergeben sind (Hauptbereich, Navigation, Fuß) oder als Vorgabe dienen.
* Eine Sprungmarke darf sie nicht wiederholen.
*
* @var list<string>
*/
public const RESERVED_ANCHORS = ['inhalt', 'main', 'top', 'site-nav', 'fuss-themen', 'mb-account-menu'];
public const ANCHOR_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
public function __construct(private readonly WidgetRegistry $widgets) {}
/**
@@ -36,7 +57,7 @@ public function __construct(private readonly WidgetRegistry $widgets) {}
*
* @param array<int|string, mixed>|null $sections gespeicherte Abschnitte (Spalte sections)
* @param array<int|string, mixed>|null $blocks flache Bausteinliste (Spalte blocks), nur ohne Abschnitte verwendet
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
public function read(?array $sections, ?array $blocks = null): array
{
@@ -59,7 +80,7 @@ public function read(?array $sections, ?array $blocks = null): array
* „sections.N.layout“, „sections.N.style.image“, „sections.N.slots“, „sections.N.slots.M.data.feld“.
*
* @param array<int|string, mixed> $content
* @return list<array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
* @return list<array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
public function normalize(array $content): array
{
@@ -75,6 +96,7 @@ public function normalize(array $content): array
$sections = [];
$seenSectionIds = [];
$seenWidgetIds = [];
$seenAnchors = [];
$widgetCount = 0;
// Eingaben mit Abständen der Version 1 (zum Beispiel ältere Aufrufer) werden wie beim Lesen übersetzt.
@@ -96,7 +118,7 @@ public function normalize(array $content): array
$item['style'] = $migrated[$index]['style'] ?? ($item['style'] ?? []);
}
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount);
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount, $seenAnchors);
}
if ($widgetCount > self::MAX_WIDGETS) {
@@ -164,12 +186,14 @@ public function mediaPaths(array $sections): array
*/
public function pageTitle(array $sections): ?string
{
return $this->widgets->pageTitle($this->flatten($sections));
// Ein ausgeblendeter Abschnitt liefert keinen Seitentitel; seine Medien bleiben dagegen erfasst (mediaPaths),
// damit ihre Bilder nicht als ungenutzt gelten.
return $this->widgets->pageTitle($this->flatten(array_values(array_filter($sections, fn (array $section): bool => ! ($section['hidden'] ?? false)))));
}
/**
* @param array<int|string, mixed> $blocks
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
private function wrapWidgets(array $blocks): array
{
@@ -179,6 +203,9 @@ private function wrapWidgets(array $blocks): array
$sections[] = [
'id' => null,
'v' => self::VERSION,
'name' => null,
'anchor' => null,
'hidden' => false,
'layout' => SectionLayouts::DEFAULT,
// Bestand vor dem Raster stand in einem durchgehenden Blatt: kompakte Abstände, zwischen den Widgets
// nur einmal (oben kein Abstand ab dem zweiten), wie bisher.
@@ -192,7 +219,7 @@ private function wrapWidgets(array $blocks): array
/**
* @param array<string, mixed> $section
* @return array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
* @return array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
*/
private function upcastSection(array $section): array
{
@@ -210,6 +237,9 @@ private function upcastSection(array $section): array
return [
'id' => is_string($section['id'] ?? null) ? $section['id'] : null,
'v' => self::VERSION,
'name' => self::cleanName($section['name'] ?? null),
'anchor' => self::cleanAnchor($section['anchor'] ?? null),
'hidden' => self::isHidden($section['hidden'] ?? false),
'layout' => $layout,
'style' => SectionStyle::fromStored($section['style'] ?? []),
'slots' => $slots,
@@ -221,9 +251,9 @@ private function upcastSection(array $section): array
* @param array<string, list<string>> $errors
* @param array<string, true> $seenSectionIds
* @param array<string, true> $seenWidgetIds
* @return array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
* @return array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
*/
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount): array
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount, array &$seenAnchors): array
{
$prefix = "sections.$index";
@@ -294,15 +324,90 @@ private function normalizeSection(array $section, int $index, array &$errors, ar
}
$seenSectionIds[$id] = true;
[$name, $anchor] = $this->normalizeLabels($section, $prefix, $errors, $seenAnchors);
return [
'id' => $id,
'v' => self::VERSION,
'name' => $name,
'anchor' => $anchor,
'hidden' => self::isHidden($section['hidden'] ?? false),
'layout' => $layout,
'style' => $style,
'slots' => $slots,
];
}
/**
* Name und Sprungmarke eines Abschnitts. Fehler: „sections.N.name“ und „sections.N.anchor“.
*
* @param array<string, mixed> $section
* @param array<string, list<string>> $errors
* @param array<string, true> $seenAnchors
* @return array{0: ?string, 1: ?string}
*/
private function normalizeLabels(array $section, string $prefix, array &$errors, array &$seenAnchors): array
{
$name = null;
$rawName = $section['name'] ?? null;
if (is_string($rawName) && trim($rawName) !== '') {
$name = self::cleanName($rawName);
if ($name === null) {
$errors["$prefix.name"] = ['Der Name darf höchstens '.self::MAX_NAME.' Zeichen lang sein.'];
}
}
$anchor = null;
$rawAnchor = $section['anchor'] ?? null;
if (is_string($rawAnchor) && trim($rawAnchor) !== '') {
$candidate = mb_strtolower(trim($rawAnchor));
if (strlen($candidate) > self::MAX_ANCHOR || preg_match(self::ANCHOR_PATTERN, $candidate) !== 1) {
$errors["$prefix.anchor"] = ['Eine Sprungmarke besteht aus Kleinbuchstaben, Ziffern und einzelnen Bindestrichen (höchstens '.self::MAX_ANCHOR.' Zeichen), zum Beispiel „anmeldung“.'];
} elseif (in_array($candidate, self::RESERVED_ANCHORS, true) || str_starts_with($candidate, 'bereich-')) {
$errors["$prefix.anchor"] = ['Diese Sprungmarke ist im Seitengerüst schon vergeben. Bitte eine andere wählen.'];
} elseif (isset($seenAnchors[$candidate])) {
$errors["$prefix.anchor"] = ['Diese Sprungmarke gibt es auf der Seite schon. Jede Sprungmarke darf nur einmal vorkommen.'];
} else {
$seenAnchors[$candidate] = true;
$anchor = $candidate;
}
} elseif ($rawAnchor !== null && ! is_string($rawAnchor)) {
$errors["$prefix.anchor"] = ['Die Sprungmarke ist ungültig.'];
}
return [$name, $anchor];
}
/** Interner Name: Leerraum vereinheitlicht, ohne Steuerzeichen; leer oder über 80 Zeichen ergibt null. */
public static function cleanName(mixed $value): ?string
{
if (! is_string($value)) {
return null;
}
$name = trim((string) preg_replace('/\s+/u', ' ', (string) preg_replace('/[\x00-\x1F\x7F]/u', ' ', $value)));
return $name === '' || mb_strlen($name) > self::MAX_NAME ? null : $name;
}
/** Lesepfad: eine gespeicherte Sprungmarke nur, wenn sie der Form entspricht. */
public static function cleanAnchor(mixed $value): ?string
{
return is_string($value) && strlen($value) <= self::MAX_ANCHOR && preg_match(self::ANCHOR_PATTERN, $value) === 1
&& ! in_array($value, self::RESERVED_ANCHORS, true) && ! str_starts_with($value, 'bereich-')
? $value
: null;
}
public static function isHidden(mixed $value): bool
{
return $value === true || $value === 1 || $value === '1' || $value === 'true';
}
/**
* @param array<string, mixed> $style
* @param array<string, list<string>> $errors
+3 -3
View File
@@ -7,8 +7,8 @@
* Die Kennungen sind gespeichert und ändern sich nie; neue Raster werden ergänzt, nicht umbenannt.
*
* Die Einheiten werden nicht als eigenes CSS-Grundraster umgesetzt, sondern als Spaltenverhältnis (fr)
* des Abschnittsrasters. Leere Slots entfallen auf der veröffentlichten Seite; die übrigen Slots teilen
* sich die Breite im Verhältnis ihrer Einheiten.
* des Abschnittsrasters. Jeder Platz behält seine Stelle und Breite, auch wenn er leer bleibt; die Widgets
* daneben rücken nicht nach.
*/
final class SectionLayouts
{
@@ -81,7 +81,7 @@ public static function options(): array
}
/**
* Spaltenvorlagen für die Slots, die tatsächlich etwas darstellen.
* Spaltenvorlagen für alle Plätze des Rasters (auch leere, damit die übrigen an ihrer Stelle bleiben).
*
* - Desktop (Abschnitt ab 60rem): Verhältnis der Einheiten.
* - Tablet (ab 40rem): gleich breite Slots bleiben nebeneinander (zwei oder drei Spalten, vier Slots als 2 × 2);
+75 -17
View File
@@ -11,10 +11,15 @@
* Einziger Darstellungsweg für Abschnitte: öffentliche Seite und Seitenvorschau rufen denselben Renderer auf.
*
* Regeln:
* - Leere Slots erzeugen keine Leerfläche; die übrigen Slots teilen sich die Breite im Verhältnis ihrer Einheiten.
* - Jeder Platz des Rasters behält seine Stelle und seine Breite: Ein leerer Platz bleibt als leere Spalte stehen, die
* Widgets daneben rücken nicht in ihn hinein. Gestapelt (Smartphone, schmaler Abschnitt) erzeugt ein leerer Platz keine
* Lücke.
* - Ein Abschnitt ohne darstellbares Widget entfällt samt Hintergrund und Trenner.
* - Das erste dargestellte Widget der Seite ist der Seiteneinstieg (Überschrift erster Ordnung).
* - Trenner stehen zwischen Abschnitten, nie nach dem letzten.
* - Ein ausgeblendeter Abschnitt („hidden“) erscheint nie auf der Website und zählt weder für das erste Widget noch für
* Trenner. Nur die Vorschau zeigt an seiner Stelle einen schmalen Hinweis (ohne Inhalt).
* - Eine Sprungmarke („anchor“) ist die Element-Kennung des Abschnitts; ohne Sprungmarke gilt „bereich-<Kennung>“.
*/
class SectionRenderer
{
@@ -29,37 +34,59 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
$first = true;
foreach ($sections as $section) {
if ($section['hidden'] ?? false) {
if ($context->preview) {
$rendered[] = ['note' => $this->hiddenNote($section)];
}
continue;
}
$cells = [];
$shown = false;
$units = SectionLayouts::units($section['layout']);
foreach ($units as $position => $slotUnits) {
$widget = $section['slots'][$position] ?? null;
if (! is_array($widget)) {
continue;
}
$html = $this->widgets->renderWidget($widget, $context, $first);
$html = is_array($widget) ? $this->widgets->renderWidget($widget, $context, $first) : '';
if ($html !== '') {
$first = false;
$cells[] = ['units' => $slotUnits, 'html' => $html];
$shown = true;
}
// Auch ein leerer Platz (oder ein Widget, das nichts darstellt) bleibt eine Zelle, damit die Plätze daneben stehen bleiben.
$cells[] = ['units' => $slotUnits, 'html' => $html];
}
if ($cells !== []) {
if ($shown) {
$rendered[] = ['section' => $section, 'cells' => $cells];
}
}
$html = '';
$last = count($rendered) - 1;
$last = -1;
foreach ($rendered as $position => $item) {
if (isset($item['section'])) {
$last = $position;
}
}
$index = 0;
foreach ($rendered as $position => $item) {
if (! isset($item['section'])) {
$html .= $item['note'];
continue;
}
foreach ($rendered as $index => $item) {
$html .= $this->renderSection($item['section'], $item['cells'], $index, $context);
$index++;
$divider = $item['section']['style']['divider'] ?? 'none';
if ($index < $last && in_array($divider, ['line', 'accent'], true)) {
if ($position < $last && in_array($divider, ['line', 'accent'], true)) {
$html .= '<div class="section-divider section-divider-'.$divider.'" aria-hidden="true"><span></span></div>';
}
}
@@ -68,8 +95,20 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
}
/**
* Hinweis der Vorschau an der Stelle eines ausgeblendeten Abschnitts.
*
* @param array<string, mixed> $section
* @param list<array{units: int, html: string}> $cells
*/
private function hiddenNote(array $section): string
{
$name = is_string($section['name'] ?? null) && $section['name'] !== '' ? '„'.$section['name'].'“ ' : '';
return '<div class="section-hidden-note" role="note">Abschnitt '.e($name).'ist für die Website ausgeblendet und erscheint hier nur als Hinweis.</div>';
}
/**
* @param array<string, mixed> $section
* @param list<array{units: int, html: string}> $cells alle Plätze des Rasters in ihrer Reihenfolge; html '' = leer
*/
private function renderSection(array $section, array $cells, int $index, RenderContext $context): string
{
@@ -105,7 +144,11 @@ private function renderSection(array $section, array $cells, int $index, RenderC
$classes[] = $scope;
}
$id = is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '';
// Die Sprungmarke ist die Kennung, die ein Link „#marke“ anspringt; ohne sie bleibt die bisherige Kennung.
$anchor = PageSections::cleanAnchor($section['anchor'] ?? null);
$id = $anchor !== null
? ' id="'.e($anchor).'"'
: (is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '');
$html = '<div class="'.e(implode(' ', $classes)).'"'.$id.'>';
if ($hasImage) {
@@ -115,11 +158,26 @@ private function renderSection(array $section, array $cells, int $index, RenderC
.' style="object-position: '.e(SectionStyle::FOCUS_POSITIONS[$style['focus']]).'">';
}
$html .= '<div class="page-section-inner"><div class="section-grid" data-slots="'.count($cells).'"'
// Auf dem Tablet stehen gleich breite Plätze nebeneinander (zwei oder drei je Zeile); nur dort behalten leere Plätze
// ihre Stelle. Eine Zeile, in der alle Plätze leer sind, entfällt auf dem Tablet ganz (sonst bliebe ihr Abstand stehen).
$perRow = preg_match('/^repeat\((\d+),/', $columns['md'], $match) === 1 ? (int) $match[1] : 1;
$tabletColumns = $perRow > 1 ? ' section-grid-tablet-columns' : '';
$emptyRows = [];
if ($perRow > 1) {
foreach (array_chunk(array_keys($cells), $perRow) as $row) {
if (array_filter($row, fn (int $position): bool => $cells[$position]['html'] !== '') === []) {
$emptyRows = array_merge($emptyRows, $row);
}
}
}
$html .= '<div class="page-section-inner"><div class="section-grid'.$tabletColumns.'" data-slots="'.count($cells).'"'
.' style="--section-cols-lg: '.e($columns['lg']).'; --section-cols-md: '.e($columns['md']).'">';
foreach ($cells as $cell) {
$html .= '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
foreach ($cells as $position => $cell) {
$html .= $cell['html'] === ''
? '<div class="section-slot section-slot-empty'.(in_array($position, $emptyRows, true) ? ' section-slot-empty-row' : '').'" data-units="'.$cell['units'].'" aria-hidden="true"></div>'
: '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
}
return $html.'</div></div></div>';
@@ -62,6 +62,26 @@ public static function symbols(): array
*/
public const TEXT_ALIGN = ['left' => 'Linksbündig', 'center' => 'Zentriert', 'right' => 'Rechtsbündig'];
/**
* Breite des Texts in Überschrift und Fließtext: Vorgabe ist die volle Breite des Platzes (so viel, wie die Abschnitts-
* einstellung dem Widget gibt); die Lesebreite begrenzt Zeilen auf etwa 70 Zeichen (Überschrift 22 Zeichen).
*
* @var array<string, string>
*/
public const TEXT_WIDTH = ['full' => 'Volle Breite des Platzes', 'reading' => 'Lesebreite (etwa 70 Zeichen je Zeile)'];
public const TEXT_WIDTH_LABEL = ['Breite des Texts', 'Volle Breite nutzt den ganzen Platz, den der Abschnitt dem Widget gibt (bei vier von vier Einheiten die ganze Zeile). Lesebreite begrenzt die Zeilen auf etwa 70 Zeichen, das liest sich bei langen Texten leichter. Vorgabe: volle Breite.'];
/**
* „reading“ nur bei ausdrücklicher, gültiger Wahl; alles andere ist die volle Breite.
*
* @param array<string, mixed> $settings
*/
public static function textWidth(array $settings): string
{
return ($settings['text_width'] ?? null) === 'reading' ? 'reading' : 'full';
}
/** @var array<string, string> */
public const LINK_STYLE = ['text' => 'Kleiner Textlink', 'pill' => 'Pille (Schaltfläche)'];
@@ -120,6 +120,12 @@ public function resolve(mixed $id, bool $preview): array
];
}
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist (auch für den Medienwähler). */
public function isSelectable(ContentElement $element): bool
{
return $this->allowed($element);
}
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist. */
private function allowed(ContentElement $element): bool
{
@@ -0,0 +1,30 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Js;
/**
* Linkfeld für alle Widgets: Die Adresse lässt sich frei eintippen (Seitenpfad, #Sprungmarke oder http(s)-Adresse) oder
* über den Dialog „Interne Seite oder Sprungmarke wählen“ aus den Seiten der Website übernehmen
* (ChoosesLinkTargets). Der Knopf ruft den Dialog direkt auf; ein Aktionsdialog im Bausteindialog entsteht nicht. Wo die
* Seite den Dialog nicht kennt, fehlt der Knopf und das Feld bleibt ein Textfeld.
*/
final class LinkField
{
public static function make(string $name, string $label = 'Linkziel'): TextInput
{
return TextInput::make($name)
->label($label)
->maxLength(500)
->rule(SafeUrl::rule())
->suffixAction(Action::make('linkWaehlen')
->label('Interne Seite oder Sprungmarke wählen')
->tooltip('Interne Seite oder Sprungmarke wählen')
->icon('heroicon-o-link')
->visible(fn ($livewire): bool => is_object($livewire) && method_exists($livewire, 'openLinkPicker'))
->actionJs(fn ($component): string => '$wire.openLinkPicker('.Js::from($component->getStatePath()).')'));
}
}
@@ -53,10 +53,7 @@ public static function eyebrowField(): TextInput
public static function ctaFields(): Grid
{
$url = fn (string $name, string $label, string $pair) => TextInput::make($name)
->label($label)
->maxLength(500)
->rule(SafeUrl::rule())
$url = fn (string $name, string $label, string $pair) => LinkField::make($name, $label)
->requiredWith($pair)
->live(onBlur: true)
->placeholder('/programme');
+1 -1
View File
@@ -12,7 +12,7 @@
final class RichText
{
/** Werkzeugleiste des Editors; muss zur Erlaubnisliste unten passen. */
public const TOOLBAR = [['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']];
public const TOOLBAR = [['bold', 'italic', 'link', 'interneSeite'], ['bulletList', 'orderedList'], ['undo', 'redo']];
private static ?HtmlSanitizer $sanitizer = null;
+7 -2
View File
@@ -6,7 +6,8 @@
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...") oder http(s)-Adressen.
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...", auch mit "#marke"), Sprungmarken auf der
* eigenen Seite ("#marke") oder http(s)-Adressen. Eine Sprungmarke besteht aus Buchstaben, Ziffern, Bindestrich und Unterstrich.
*/
final class SafeUrl implements ValidationRule
{
@@ -16,6 +17,10 @@ public static function isSafe(mixed $url): bool
return false;
}
if (str_starts_with($url, '#')) {
return preg_match('/^#[A-Za-z0-9_-]{1,80}$/', $url) === 1;
}
$isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//') && ! str_starts_with($url, '/\\');
$isAbsolute = preg_match('#^https?://[^/\s]+#i', $url) === 1;
@@ -24,7 +29,7 @@ public static function isSafe(mixed $url): bool
public static function message(): string
{
return 'Erlaubt sind Seitenpfade (beginnend mit /) oder http(s)-Adressen.';
return 'Erlaubt sind Seitenpfade (beginnend mit /), Sprungmarken (#marke) oder http(s)-Adressen.';
}
/**
@@ -3,6 +3,7 @@
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\Support\LinkField;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
@@ -82,12 +83,9 @@ public function dataFields(): array
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('text')->label('Text')->rows(3)->maxLength(1000),
TextInput::make('label')->label('Beschriftung der Schaltfläche')->required()->maxLength(80),
TextInput::make('url')
->label('Linkziel')
LinkField::make('url')
->required()
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /angebote oder eine vollständige http(s)-Adresse.'),
->helperText('Seitenpfad wie /angebote, Sprungmarke wie #kurse oder eine vollständige http(s)-Adresse; oder über das Linksymbol eine Seite oder Sprungmarke wählen.'),
];
}
+138 -21
View File
@@ -2,28 +2,79 @@
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Catalog\FormattedText;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\LinkField;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\RichField;
use App\Filament\Support\SymbolField;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Illuminate\Validation\Rule;
/**
* Redaktionelle Karten. Die Einträge sind freie redaktionelle Verweise, keine Produkte oder Lizenzartikel.
*
* Version 1 umfasst den Bestand (Titel, Text, Adresse). Das optionale Bild je Karte ist eine
* abwärtskompatible Ergänzung derselben Version: ältere Karten haben schlicht kein Bild.
* Version 1 (Bestand): Titel, Klartext, Adresse; Bild und Symbol je Karte sind abwärtskompatible Ergänzungen derselben
* Version. Version 2: Die Beschreibung ist formatierter Text (HTML, Webprofil von FormattedText wie im Fließtext). Neu je
* Karte ist die optionale Dachzeile über dem Titel (sie wird nur gespeichert, wenn sie ausgefüllt ist).
*/
class CardsWidget extends WidgetType
{
/** Größtes zulässiges Maß des gespeicherten HTML einer Beschreibung. */
public const TEXT_MAX_LENGTH = 5000;
/**
* Verteilung der Karten auf die Breite: die Karten wachsen und füllen jede Zeile (Vorgabe) oder behalten ihre Breite,
* und die Abstände wachsen. In beiden Fällen sind alle Spalten gleich breit.
*
* @var array<string, string>
*/
public const DISTRIBUTION = ['grow' => 'Karten vergrößern sich', 'space' => 'Abstände gleichen aus'];
/** @var array<string, string> */
public const DIVIDER = ['line' => 'Feiner Strich zwischen den Karten'];
private const DEFAULT_LINK_LABEL = 'Mehr erfahren';
/** @var array<string, string> */
public const HOVER = ['lift' => 'Karte unter der Maus hervorheben'];
/**
* Gültige Layout-Einstellungen mit Vorgaben; alles andere fällt auf die Vorgabe zurück (Karten wachsen, Symbol über
* dem Text, oben, ohne Strich, ohne Pinselstrich, ohne Hervorhebung).
*
* @param array<string, mixed> $settings
* @return array{align: string, size: string, position: string, valign: string, distribution: string, divider: bool, brush: bool, hover: bool, link: ?string}
*/
public static function layout(array $settings): array
{
$position = $settings['symbol_position'] ?? null;
$distribution = $settings['distribution'] ?? null;
return HeadingAccent::block($settings) + [
'position' => is_string($position) && array_key_exists($position, FeaturesWidget::SYMBOL_POSITION) ? $position : 'top',
'valign' => HeadingAccent::align($settings),
'distribution' => is_string($distribution) && array_key_exists($distribution, self::DISTRIBUTION) ? $distribution : 'grow',
'divider' => ($settings['divider'] ?? null) === 'line',
'brush' => HeadingAccent::hasBrush($settings),
'hover' => ($settings['hover'] ?? null) === 'lift',
// Sichtbarer Link unter dem Text (Textlink oder Pille); ohne Einstellung ist der Titel der Link der Karte.
'link' => in_array($settings['link_style'] ?? null, array_keys(HeadingAccent::LINK_STYLE), true) ? $settings['link_style'] : null,
];
}
public function version(): int
{
return 2;
}
public function key(): string
{
return 'cards';
@@ -36,7 +87,7 @@ public function label(): string
public function description(): string
{
return 'Mehrere Karten mit Titel, Text, Linkziel und optionalem Bild. Als Raster, kompakte Liste oder mit hervorgehobener erster Karte.';
return 'Mehrere Karten mit Dachzeile, Titel, formatiertem Text, Symbol, Linkziel und optionalem Bild. Als Raster, kompakte Liste oder mit hervorgehobener erster Karte.';
}
public function supportedUnits(): array
@@ -46,7 +97,7 @@ public function supportedUnits(): array
public function narrowBehavior(): string
{
return 'Karten stehen untereinander, sobald keine zwei 15 rem breiten Karten nebeneinander passen; die hervorgehobene Karte stapelt Bild und Text.';
return 'Die Karten sind mindestens 15 rem breit (mit Symbol neben dem Text 18 rem) und verteilen sich ausgewogen auf Zeilen (zehn Karten als 4, 3 und 3); passen keine zwei Karten nebeneinander, stehen sie untereinander. Bei „Abstände gleichen aus“ behalten sie ihre Breite (höchstens 20 rem). Die hervorgehobene Karte stapelt Bild und Text.';
}
public function preferredUnits(): int
@@ -58,7 +109,7 @@ public function stages(): array
{
return [
'narrow' => 'eine Karte je Zeile',
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 15rem Kartenbreite passen; hervorgehobene Karte ab 44rem mit Bild neben dem Text',
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 15rem Kartenbreite passen, ausgewogen auf die Zeilen verteilt; hervorgehobene Karte ab 44rem mit Bild neben dem Text',
];
}
@@ -85,9 +136,11 @@ public function dataRules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:12'],
'items.*.eyebrow' => ['nullable', 'string', 'max:80'],
'items.*.title' => ['required', 'string', 'max:120'],
'items.*.text' => ['nullable', 'string', 'max:500'],
'items.*.text' => ['nullable', 'string', 'max:'.self::TEXT_MAX_LENGTH],
'items.*.url' => ['nullable', 'string', 'max:500'],
'items.*.link_label' => ['nullable', 'string', 'max:60'],
'items.*.symbol' => ['nullable', 'string', Rule::in(array_keys(HeadingAccent::symbols()))],
'items.*.image' => ['nullable'],
'items.*._upload' => ['nullable'],
@@ -97,21 +150,40 @@ public function dataRules(): array
public function settings(): array
{
return [
'symbol_size' => HeadingAccent::STEPS,
'distribution' => self::DISTRIBUTION,
'align' => HeadingAccent::TEXT_ALIGN,
'symbol_size' => HeadingAccent::STEPS,
'symbol_position' => FeaturesWidget::SYMBOL_POSITION,
'symbol_align' => HeadingAccent::ALIGN,
'accent' => HeadingAccent::BRUSH,
'divider' => self::DIVIDER,
'hover' => self::HOVER,
'link_style' => HeadingAccent::LINK_STYLE,
];
}
public function settingGroups(): array
{
return ['Aussehen' => ['symbol_size', 'align']];
return [
'Verteilung' => ['distribution', 'align'],
'Symbol' => ['symbol_size', 'symbol_position', 'symbol_align'],
'Gestaltung' => ['accent', 'divider', 'hover'],
'Link' => ['link_style'],
];
}
public function settingLabels(): array
{
return [
'distribution' => ['Verteilung der Karten', 'Wie die Karten den verfügbaren Platz füllen. Die Zeilen sind in beiden Fällen ausgewogen (fünf Karten stehen als drei und zwei, zehn als vier, drei und drei) und jede Karte ist mindestens 15 rem breit (mit Symbol neben dem Text 18 rem); wird das unterschritten, wandert eine Karte in die nächste Zeile. „Karten vergrößern sich“ (Vorgabe): Jede Zeile wird ganz ausgefüllt. „Abstände gleichen aus“: Die Karten behalten eine feste Breite (höchstens 20 rem), und der übrige Platz verteilt sich gleichmäßig zwischen und neben den Karten. Möglich sind eine bis zwölf Karten.'],
'align' => ['Ausrichtung', 'Richtet Symbol, Dachzeile, Titel, Pinselstrich und Text jeder Karte aus. Vorgabe: linksbündig.'],
'symbol_size' => ['Größe der Symbole', 'Kantenlänge der Symbole auf den Karten, die eins haben: Klein 2,5 rem, Mittel 3,5 rem, Groß 5 rem, Sehr groß 7 rem. Vorgabe: Mittel.'],
'align' => ['Ausrichtung', 'Richtet Symbol, Titel und Text jeder Karte aus. Vorgabe: linksbündig.'],
'symbol_position' => ['Lage des Symbols', 'Über dem Text (Vorgabe) oder links bzw. rechts neben Dachzeile, Titel und Text jeder Karte. Neben dem Text braucht jede Karte mindestens 18 rem Breite, sonst stehen die Karten untereinander. Vorgabe: über dem Text.'],
'symbol_align' => ['Senkrechte Lage des Symbols', 'Wo das Symbol neben dem Text sitzt: oben (Vorgabe), mittig oder unten. Wirkt nur, wenn das Symbol links oder rechts neben dem Text steht.'],
'accent' => ['Pinselstrich', 'Gelbe Unterstreichung unter dem Titel jeder Karte (freigegebenes Motiv aus dem Brand-Kit). Vorgabe: ohne.'],
'divider' => ['Trennstrich', 'Ein feiner Strich zwischen den Karten: senkrecht zwischen Spalten, waagerecht zwischen Zeilen. Die Karten verlieren dabei ihre Fläche und stehen flach auf dem Abschnitt, wie in der Merkmalszeile. In der kompakten Liste wirkt die Einstellung nicht, sie hat schon Linien. Vorgabe: ohne.'],
'link_style' => ['Link unter dem Text', 'Zeigt unter dem Text jeder Karte mit Linkziel einen sichtbaren Link: als kleiner Textlink oder als Pille (Schaltfläche). Die ganze Karte bleibt anklickbar, der Titel ist dann kein eigener Link. Der Linktext steht je Karte (leer: „'.self::DEFAULT_LINK_LABEL.'“). Vorgabe: kein sichtbarer Link, die Karte öffnet sich über den Titel.'],
'hover' => ['Hervorhebung unter der Maus', 'Die Karte, über der die Maus steht (oder die per Tastatur erreicht wird), hebt sich leicht ab. Ohne Bewegung, wenn das Betriebssystem reduzierte Bewegung wünscht. Vorgabe: ohne.'],
];
}
@@ -123,15 +195,22 @@ public function dataFields(): array
Repeater::make('items')
->label('Karten')
->schema([
TextInput::make('eyebrow')
->label('Dachzeile (optional)')
->maxLength(80)
->helperText('Kurzer Hinweis über dem Titel, zum Beispiel ein Themenbereich. Kein Pflichtfeld.'),
TextInput::make('title')->label('Titel')->required()->maxLength(120),
SymbolField::make('symbol', 'Symbol (optional)')
->helperText('Kleine Grafik aus dem Brand-Kit über dem Titel. Größe und Ausrichtung im Reiter „Darstellung“.'),
Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500),
TextInput::make('url')
->label('Linkziel')
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'),
->helperText('Kleine Grafik aus dem Brand-Kit. Größe, Lage und senkrechte Ausrichtung im Reiter „Darstellung“.'),
RichField::make('text', 'Beschreibung', website: true)
->helperText('Wie beim Fließtext: Absätze und Zeilenumbrüche (Umschalt + Eingabe), fett, kursiv, Links, Listen, Schriftgröße, Schriftfarbe und Ausrichtung. Die Karten bleiben auch auf dunklen und grünen Abschnitten hell; die Farben entsprechen dort denen auf hellen Flächen.'),
LinkField::make('url')
->helperText('Seitenpfad wie /praevention, Sprungmarke wie #kurse oder eine http(s)-Adresse; oder über das Linksymbol wählen. Leer lassen für eine Karte ohne Link.'),
TextInput::make('link_label')
->label('Linktext (optional)')
->maxLength(60)
->placeholder(self::DEFAULT_LINK_LABEL)
->helperText('Nur sichtbar, wenn im Reiter „Darstellung“ ein Link unter dem Text gewählt ist, und nur mit Linkziel. Leer: „'.self::DEFAULT_LINK_LABEL.'“.'),
$image,
$upload,
$status,
@@ -146,6 +225,36 @@ public function dataFields(): array
];
}
public function upgrade(array $widget, int $from): array
{
if ($from === 1) {
foreach ($widget['data']['items'] ?? [] as $index => $item) {
if (is_array($item) && filled($item['text'] ?? null)) {
$widget['data']['items'][$index]['text'] = self::plainToHtml((string) $item['text']);
}
}
return $widget;
}
return parent::upgrade($widget, $from);
}
/**
* Klartext der Version 1 als formatierter Text: Leerzeilen trennen Absätze, ein einfacher Zeilenumbruch bleibt ein
* Zeilenumbruch (so wie in der Überschrift mit Einleitung).
*/
public static function plainToHtml(string $text): string
{
$paragraphs = preg_split('/\R\s*\R/u', trim($text)) ?: [];
$html = implode('', array_map(
fn (string $paragraph): string => trim($paragraph) === '' ? '' : '<p>'.preg_replace('/\R/u', '<br>', e(trim($paragraph))).'</p>',
$paragraphs,
));
return FormattedText::canonicalHtml($html, true);
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
foreach ($data['items'] as $index => $item) {
@@ -155,11 +264,17 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
$itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image");
// Der Schlüssel symbol wird nur gespeichert, wenn ein Symbol gewählt ist: Karten ohne Symbol bleiben byteweise wie zuvor.
$text = FormattedText::canonical(is_string($item['text'] ?? null) ? $item['text'] : '', true);
// Die Schlüssel eyebrow und symbol werden nur gespeichert, wenn sie ausgefüllt sind: Karten ohne sie bleiben
// byteweise wie zuvor.
$data['items'][$index] = [
...(filled($item['eyebrow'] ?? null) ? ['eyebrow' => trim((string) $item['eyebrow'])] : []),
'title' => $item['title'],
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
'text' => $text !== '' ? $text : null,
'url' => filled($item['url'] ?? null) ? $item['url'] : null,
// Ein Linktext ohne Linkziel wird verworfen; ohne Linktext bleibt der Schlüssel weg (Karten bleiben wie zuvor).
...(filled($item['url'] ?? null) && filled($item['link_label'] ?? null) ? ['link_label' => trim((string) $item['link_label'])] : []),
...(filled($item['symbol'] ?? null) ? ['symbol' => $item['symbol']] : []),
'image' => $itemRefs['image'],
];
@@ -180,9 +295,11 @@ public function resolve(array $widget, RenderContext $context): array
}
$items[] = [
'eyebrow' => filled($item['eyebrow'] ?? null) ? $item['eyebrow'] : null,
'title' => $item['title'],
'text' => $item['text'] ?? null,
'textHtml' => filled($item['text'] ?? null) ? ProseWidget::render($item['text']) : '',
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
'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),
];
@@ -194,7 +311,7 @@ public function resolve(array $widget, RenderContext $context): array
return [
'items' => $items,
'layout' => HeadingAccent::block($widget['settings'] ?? []),
'layout' => self::layout($widget['settings'] ?? []),
'imageNotice' => $notices === [] ? null : implode(' ', $notices),
];
}
@@ -4,6 +4,7 @@
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\Support\LinkField;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
@@ -157,11 +158,8 @@ public function dataFields(): array
SymbolField::make('symbol', 'Symbol', required: true),
TextInput::make('title')->label('Kurztitel')->required()->maxLength(60),
Textarea::make('text')->label('Satz')->rows(2)->maxLength(200),
TextInput::make('url')
->label('Linkziel (optional)')
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /materialien oder eine http(s)-Adresse. Leer lassen für ein Merkmal ohne Link.'),
LinkField::make('url', 'Linkziel (optional)')
->helperText('Seitenpfad wie /materialien, Sprungmarke wie #kurse oder eine http(s)-Adresse; oder über das Linksymbol wählen. Leer lassen für ein Merkmal ohne Link.'),
TextInput::make('link_label')
->label('Linktext')
->maxLength(60)
+65 -4
View File
@@ -2,13 +2,31 @@
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Catalog\FormattedText;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use App\Filament\Support\RichField;
use Filament\Forms\Components\TextInput;
/**
* Überschrift mit Einleitung. Die Einleitung wird im Editor des Fließtexts geschrieben (Absätze, Zeilenumbrüche, fett,
* kursiv, Links, Listen, Schriftgröße, -farbe, Ausrichtung; Webprofil von FormattedText) und so dargestellt wie dort.
*
* Version 1 (Bestand): Einleitung als Klartext; eine Leerzeile beginnt einen Absatz, ein einfacher Zeilenumbruch bleibt
* ein Zeilenumbruch. Version 2: formatierter Text (HTML).
*/
class HeadingWidget extends WidgetType
{
/** Größtes zulässiges Maß des gespeicherten HTML der Einleitung. */
public const INTRO_MAX_LENGTH = 20000;
public function version(): int
{
return 2;
}
public function key(): string
{
return 'heading';
@@ -60,15 +78,56 @@ public function dataRules(): array
{
return [
'heading' => ['required', 'string', 'max:200'],
'intro' => ['nullable', 'string', 'max:1000'],
'intro' => ['nullable', 'string', 'max:'.self::INTRO_MAX_LENGTH],
];
}
public function upgrade(array $widget, int $from): array
{
if ($from === 1) {
$intro = $widget['data']['intro'] ?? '';
$paragraphs = preg_split("/
\s*
/", trim(is_string($intro) ? $intro : '')) ?: [];
$html = implode('', array_map(
fn (string $paragraph): string => trim($paragraph) === '' ? '' : '<p>'.preg_replace('/\R/u', '<br>', e(trim($paragraph))).'</p>',
$paragraphs,
));
$widget['data']['intro'] = FormattedText::canonicalHtml($html, true);
return $widget;
}
return parent::upgrade($widget, $from);
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$intro = FormattedText::canonical(is_string($data['intro'] ?? null) ? $data['intro'] : '', true);
if ($intro === '') {
unset($data['intro']);
} else {
$data['intro'] = $intro;
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$intro = $widget['data']['intro'] ?? null;
return ['introHtml' => is_string($intro) && trim($intro) !== '' ? ProseWidget::render($intro) : ''];
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('intro')->label('Einleitung')->rows(3)->maxLength(1000),
RichField::make('intro', 'Einleitung', website: true)
->helperText('Wie beim Fließtext: Absätze und Zeilenumbrüche (Umschalt + Eingabe), fett, kursiv, Links, Listen, Zitate und Tabellen, dazu Schriftgröße, Schriftfarbe (Marine, Grün, Rot, Grau) und Ausrichtung. Auf dunklen und grünen Flächen werden die Farben aufgehellt, damit die Schrift lesbar bleibt.'),
];
}
@@ -79,12 +138,13 @@ public function settings(): array
'symbol_size' => HeadingAccent::SIZE,
'symbol_align' => HeadingAccent::ALIGN,
'accent' => HeadingAccent::BRUSH,
'text_width' => HeadingAccent::TEXT_WIDTH,
];
}
public function settingGroups(): array
{
return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align', 'accent']];
return ['Aussehen' => ['text_width', 'symbol', 'symbol_size', 'symbol_align', 'accent']];
}
public function settingLabels(): array
@@ -94,6 +154,7 @@ public function settingLabels(): array
'symbol_size' => HeadingAccent::SIZE_LABEL,
'symbol_align' => HeadingAccent::ALIGN_LABEL,
'accent' => HeadingAccent::BRUSH_LABEL,
'text_width' => HeadingAccent::TEXT_WIDTH_LABEL,
];
}
+102 -10
View File
@@ -4,6 +4,7 @@
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\Support\HeroVideo;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PremiumFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
@@ -11,8 +12,10 @@
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\InternalLinkPlugin;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\ViewField;
use Filament\Schemas\Components\Group;
/**
@@ -20,6 +23,11 @@
*
* Version 1 (Bestand): data {image, alt, body} mit Klartext.
* Version 2: data {title, body (formatierter Text), alt}, refs {image}, Varianten Bild links/rechts.
* Ohne Versionssprung ergänzt (ältere Revisionen bleiben unverändert darstellbar): Bildanteil (settings.image_share),
* Bild ohne Text (Text ist nicht mehr Pflicht, wenn ein Bild gewählt ist) und ein Video (refs.video, ein Film aus dem
* Medienmanager): Das freigegebene Video (Trailer, Vorschauclip oder Website-Datei, Regel CardClip) spielt auf dem Bild
* beim Überfahren mit der Maus stumm und per Klick oder Schaltfläche mit Ton, wie auf der Medienkarte.
*
* Version 3: zusätzlich Label, zwei Schaltflächen, Bildfokus in Prozent; Einstellungen Oberfläche, Höhe und
* Überschriftenebene. Die Bildseite bleibt die Variante (keine doppelte Einstellung). Die Einstellung
* format der Designiteration 1 entfällt; die Bildproportion folgt jetzt der Höhe.
@@ -110,10 +118,25 @@ public function optionIcons(): array
];
}
/**
* Bildanteil an der Breite im zweispaltigen Stand (ab 900 px Containerbreite): Bild- und Textspalte als Verhältnis.
* Ohne Wert gilt die bisherige Verteilung (Text 1,1 : Bild 0,9, je nach Bildseite).
*
* @var array<string, string>
*/
public const IMAGE_SHARE = [
'third' => 'Schmales Bild (ein Drittel Bild, zwei Drittel Text)',
'two_fifths' => 'Eher schmales Bild (40 % Bild, 60 % Text)',
'half' => 'Gleich breit (je die Hälfte)',
'three_fifths' => 'Eher breites Bild (60 % Bild, 40 % Text)',
'two_thirds' => 'Breites Bild (zwei Drittel Bild, ein Drittel Text)',
];
public function settings(): array
{
return [
'surface' => ['cream' => 'Creme (Markenfläche)', 'clear' => 'Ohne eigene Fläche', 'navy' => 'Navy (dunkel)'],
'image_share' => self::IMAGE_SHARE,
'heading_level' => PremiumFields::HEADING_LEVELS,
'symbol' => HeadingAccent::symbols(),
'symbol_size' => HeadingAccent::SIZE,
@@ -124,7 +147,7 @@ public function settings(): array
public function settingGroups(): array
{
return [
'Aussehen' => ['surface', 'symbol', 'symbol_size', 'symbol_align'],
'Aussehen' => ['surface', 'image_share', 'symbol', 'symbol_size', 'symbol_align'],
'Seitenstruktur' => ['heading_level'],
];
}
@@ -133,6 +156,7 @@ public function settingLabels(): array
{
return [
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
'image_share' => ['Bildanteil', 'Verhältnis von Bild und Text nebeneinander. Gilt erst ab 900 px Breite des Widgets; schmaler steht das Bild über dem Text. Ohne Auswahl bleibt es bei der bisherigen Verteilung (Text etwas breiter als das Bild). Ohne Text füllt das Bild die ganze Breite.'],
'symbol' => HeadingAccent::SYMBOL_LABEL,
'symbol_size' => HeadingAccent::SIZE_LABEL,
'symbol_align' => HeadingAccent::ALIGN_LABEL,
@@ -180,13 +204,14 @@ public function dataRules(): array
{
return [
'title' => ['nullable', 'string', 'max:160'],
'body' => ['required', 'string', 'max:40000'],
// Der Text ist nur Pflicht, solange kein Bild gewählt ist (clean); ein Bild darf allein stehen.
'body' => ['nullable', 'string', 'max:40000'],
] + PremiumFields::rules();
}
public function refRules(): array
{
return ImageRefFields::rules();
return ImageRefFields::rules() + ['video' => ['nullable']];
}
public function dataFields(): array
@@ -196,8 +221,9 @@ public function dataFields(): array
TextInput::make('title')->label('Überschrift')->maxLength(160)->live(onBlur: true),
RichEditor::make('body')
->label('Text')
->required()
->helperText('Leer lassen, wenn nur das Bild gezeigt werden soll. Ohne Text, Überschrift, Label und Schaltflächen füllt das Bild die ganze Breite.')
->live(onBlur: true)
->plugins([new InternalLinkPlugin])
->toolbarButtons(RichText::TOOLBAR),
PremiumFields::ctaFields(),
PremiumFields::altField(),
@@ -207,7 +233,16 @@ public function dataFields(): array
public function refFields(): array
{
return ImageRefFields::fields(live: true);
return [...ImageRefFields::fields(live: true), $this->videoField()];
}
private function videoField(): ViewField
{
return ViewField::make('video')
->live()
->label('Video (optional)')
->view('filament.cms.video-feld')
->helperText('Ein Film aus dem Medienmanager, über denselben Wähler wie das Bild. Das Bild bleibt stehen; das Video spielt darauf beim Überfahren stumm und per Klick oder Schaltfläche mit Ton, nur wenn ein Trailer, Vorschauclip oder die Website-Datei des Films für die Website freigegeben ist. Die Auswahl gibt nichts frei.');
}
public function editorSchema(): array
@@ -234,13 +269,47 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
$data['title'] = filled($data['title'] ?? null) ? trim((string) $data['title']) : null;
$data = PremiumFields::clean($data, $errors, $refs['image'] !== null);
if (RichText::isBlank($data['body'])) {
$errors->add('data.body', 'Bitte einen Text eingeben.');
$video = app(HeroVideo::class)->clean($refs['video'] ?? null, $errors);
$video === null ? $refs = array_diff_key($refs, ['video' => true]) : $refs['video'] = $video;
if ($video !== null && $refs['image'] === null) {
$errors->add('refs.image', 'Bitte auch ein Bild wählen: Es steht, bis das Video startet.');
}
if ($refs['image'] === null && ! self::hasCopy($data)) {
$errors->add('data.body', 'Bitte einen Text eingeben oder ein Bild wählen.');
}
return [$data, $refs];
}
/**
* Ob neben dem Bild etwas zu lesen ist: Text, Überschrift, Label oder Schaltfläche. Ohne bleibt das Bild allein.
*
* @param array<string, mixed> $data
*/
public static function hasCopy(array $data): bool
{
$body = is_string($data['body'] ?? null) ? RichText::sanitize($data['body']) : '';
return ! RichText::isBlank($body)
|| filled($data['title'] ?? null)
|| filled($data['eyebrow'] ?? null)
|| PremiumFields::actions($data) !== [];
}
/**
* Gültiger Bildanteil oder null (bisherige Verteilung).
*
* @param array<string, mixed> $settings
*/
public static function imageShare(array $settings): ?string
{
$share = $settings['image_share'] ?? null;
return is_string($share) && array_key_exists($share, self::IMAGE_SHARE) ? $share : null;
}
public function resolve(array $widget, RenderContext $context): array
{
$surface = $widget['settings']['surface'] ?? 'cream';
@@ -248,10 +317,23 @@ public function resolve(array $widget, RenderContext $context): array
$images = app(WebsiteImage::class);
$image = $widget['refs']['image'] ?? null;
$imageUrl = $images->url($image, $context->preview);
$imageAlt = $images->alt($image, $widget['data']['alt'] ?? null);
$hasCopy = self::hasCopy($widget['data'] ?? []);
$video = app(HeroVideo::class)->resolve($widget['refs']['video'] ?? null, $context->preview);
// Ohne Bild gibt es nichts, worauf das Video stehen könnte; die Redaktion erfährt es in der Vorschau.
if ($imageUrl === null && $video['url'] !== null) {
$video = ['url' => null, 'title' => $video['title'], 'notice' => $context->preview ? 'Das Video braucht ein Bild: Es steht, bis das Video startet. Bitte ein Bild wählen.' : null];
}
return [
'imageUrl' => $images->url($image, $context->preview),
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
'imageUrl' => $imageUrl,
'imageAlt' => $imageAlt,
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'video' => $video,
'hasCopy' => $hasCopy,
'imageShare' => self::imageShare($widget['settings'] ?? []),
'body' => RichText::sanitize(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : ''),
'actions' => PremiumFields::actions($widget['data']),
'focus' => PremiumFields::focus($widget['data'], 64, 43),
@@ -270,6 +352,16 @@ public function summary(array $widget): string
{
$title = $widget['data']['title'] ?? null;
return filled($title) ? (string) $title : RichText::excerpt($widget['data']['body'] ?? '');
if (filled($title)) {
return (string) $title;
}
$excerpt = RichText::excerpt($widget['data']['body'] ?? '');
if ($excerpt !== '') {
return $excerpt;
}
return filled($widget['data']['alt'] ?? null) ? 'Bild: '.$widget['data']['alt'] : 'Bild';
}
}
@@ -0,0 +1,116 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetType;
use App\Domain\Communication\InquiryEntry;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Text;
use Illuminate\Validation\Rule;
/**
* Kontakt-Widget: bindet einen veröffentlichten Anfrage-Einstieg der Kommunikationsverwaltung ein (ADR-60). Das Widget
* speichert ausschließlich die Kennung des Einstiegs. Felder, Auswahlwerte, Bedingungen, Schritte, Texte und
* Empfänger gibt es im CMS nicht; sie werden in der Kommunikationsverwaltung gepflegt.
*/
class InquiryWidget extends WidgetType
{
public function key(): string
{
return 'inquiry';
}
public function label(): string
{
return 'Anfrage';
}
public function description(): string
{
return 'Bindet einen Anfrage-Einstieg aus der Kommunikationsverwaltung ein: Kontaktformular oder mehrstufiger Anfragedialog.';
}
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, der mehrstufige Dialog bleibt einspaltig.';
}
public function stages(): array
{
return ['fluid' => 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art stehen auf breiten Plätzen nebeneinander'];
}
public function schematic(): array
{
return [[6, 4, 24, 3, 'ink'], [6, 10, 48, 5, 'line'], [6, 18, 48, 5, 'line'], [6, 26, 18, 5, 'accent']];
}
public function dataRules(): array
{
return [];
}
public function dataFields(): array
{
return [];
}
public function refRules(): array
{
return [
// Nur die Existenz: Ein später zurückgezogener Einstieg darf eine Seite nicht unspeicherbar machen (Seiten bleiben
// konsistent). Auswahl im Editor sind nur veröffentlichte Einstiege; öffentlich erscheint nichts, solange er es nicht ist.
'entry' => ['required', 'integer', Rule::exists('inquiry_entries', 'id')],
];
}
public function refFields(): array
{
return [
Select::make('entry')
->label('Anfrage-Einstieg')
->required()
->searchable()
->options(fn (): array => InquiryEntry::query()->live()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Nur veröffentlichte Einstiege stehen zur Auswahl. Anliegen, Felder, Bedingungen, Texte und Empfänger pflegst du in der Kommunikationsverwaltung („Kommunikation → Anfrage-Einstiege“), nicht hier. Eine Änderung dort gilt sofort auf allen Seiten, die diesen Einstieg verwenden.'),
Text::make('Ein Einstieg ist die konkrete Nutzungsvariante einer Anfragevorlage. Mehrere Seiten können denselben Einstieg einbinden.'),
];
}
public function editorSchema(): array
{
return parent::editorSchema();
}
public function resolve(array $widget, RenderContext $context): array
{
$id = $widget['refs']['entry'] ?? null;
$entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null;
return ['entry' => $entry, 'entryLive' => $entry?->isLive() ?? false];
}
public function summary(array $widget): string
{
$id = $widget['refs']['entry'] ?? null;
$name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null;
return $name !== null ? 'Anfrage: '.$name : 'Kein Anfrage-Einstieg gewählt';
}
}
@@ -0,0 +1,291 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Catalog\FormattedText;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\RichField;
/**
* Hinweiszeile: ein kompakter Hinweis (zum Beispiel „Dieses Bild wurde mit KI erzeugt“) mit formatiertem Text und
* optionalem Symbol, wahlweise mit aufklappbarer Kurzdarstellung.
*
* Drei Darstellungsmodi (Einstellung `mode`), der Text steht immer in beiden Fassungen gespeichert, ein Wechsel des Modus
* verliert also nichts:
* - full (Vorgabe): der vollständige Hinweis, immer sichtbar, ohne Aufklappen.
* - responsive: breit der volle Text; unter einer Widgetbreite (Einstellung `narrow`) die Kurzdarstellung, auf Wunsch erst
* dann, wenn der Volltext mehr Zeilen braucht als die Zeilengrenze (`line_limit`). Beim Laden eingeklappt.
* - collapsed: immer zuerst die Kurzdarstellung, auf jeder Breite; ein Klick zeigt den vollständigen Text. Breite und
* Zeilengrenze bleiben unberücksichtigt.
* Ohne Kurztext gibt es nichts einzuklappen: Der Hinweis erscheint dann wie im Modus „Volltext“.
*/
class NoticeWidget extends WidgetType
{
/** Größtes zulässiges Maß des gespeicherten HTML je Text. */
public const TEXT_MAX_LENGTH = 10000;
public const SHORT_MAX_LENGTH = 2000;
/** @var array<string, string> */
public const MODE = [
'full' => 'Volltext: immer vollständig sichtbar',
'responsive' => 'Responsiv: auf schmalen Bildschirmen die Kurzdarstellung',
'collapsed' => 'Immer mit Kurzdarstellung starten',
];
/**
* Auslösegrenze: Der Volltext braucht mehr Zeilen als die Grenze. Die Schlüssel sind keine Zahlen, damit sie als
* Zeichenketten erhalten bleiben (ADR-30: nur feste Werte).
*
* @var array<string, string>
*/
public const LINE_LIMIT = [
'l1' => 'Mehr als 1 Zeile',
'l2' => 'Mehr als 2 Zeilen',
'l3' => 'Mehr als 3 Zeilen',
'l4' => 'Mehr als 4 Zeilen',
'l5' => 'Mehr als 5 Zeilen',
'l6' => 'Mehr als 6 Zeilen',
];
/**
* Breite des Widgets (nicht des Fensters), unter der „schmal“ gilt, in rem.
*
* @var array<string, float>
*/
public const NARROW_REM = ['narrow' => 30.0, 'medium' => 40.0, 'wide' => 56.0];
/** @var array<string, string> */
public const NARROW = [
'narrow' => 'Nur bei sehr wenig Platz (Widgetbreite unter 30 rem, etwa 480 px)',
'medium' => 'Bei wenig Platz (unter 40 rem, etwa 640 px)',
'wide' => 'Auch bei mittlerem Platz (unter 56 rem, etwa 900 px)',
];
/** Schriftgrößen: S, M und L sind die Stufen „klein“, „Text“ und „Einleitung“ des Designsystems, XS ist kleiner als diese. */
public const SIZE = ['xs' => 'XS (klein, 13 px)', 's' => 'S (Hinweistext des Designsystems)', 'm' => 'M (Fließtext)', 'l' => 'L (Einleitungstext)'];
/** @var array<string, string> */
public const SYMBOL_SIZE = ['xs' => 'Sehr klein (1 rem)', 's' => 'Klein (1,25 rem)', 'm' => 'Mittel (1,75 rem)', 'l' => 'Groß (2,5 rem)', 'xl' => 'Sehr groß (3,5 rem)'];
/** @var array<string, string> */
public const SURFACE = ['green' => 'Dezentes Grün', 'yellow' => 'Hinweisgelb', 'cream' => 'Creme'];
/** @var array<string, string> */
public const BORDER = ['line' => 'Feiner Rahmen'];
/** @var array<string, string> */
public const BAR = ['left' => 'Akzentlinie links', 'top' => 'Akzentlinie oben'];
/**
* Gültige Darstellungswerte; alles andere fällt auf die Vorgabe zurück (Volltext, ohne Grenze, mittlere Schwelle, S,
* linksbündig, Symbol klein und oben, ohne Fläche, Rahmen und Linie). Ohne Kurztext ist der Modus immer „full“.
*
* @param array<string, mixed> $settings
* @return array{mode: string, limit: ?int, narrow: float, size: string, align: string, symbol: ?string, symbolSize: string, symbolAlign: string, surface: ?string, border: bool, bar: ?string}
*/
public static function layout(array $settings, bool $hasShort = true): array
{
$pick = fn (string $key, array $allowed, ?string $default): ?string => is_string($settings[$key] ?? null) && array_key_exists($settings[$key], $allowed) ? $settings[$key] : $default;
$mode = $pick('mode', self::MODE, 'full');
$limit = $pick('line_limit', self::LINE_LIMIT, null);
return [
'mode' => $hasShort ? $mode : 'full',
'limit' => $limit === null ? null : (int) substr($limit, 1),
'narrow' => self::NARROW_REM[$pick('narrow', self::NARROW, 'medium')],
'size' => $pick('size', self::SIZE, 's'),
'align' => $pick('align', HeadingAccent::TEXT_ALIGN, 'left'),
'symbol' => HeadingAccent::symbol($settings),
'symbolSize' => $pick('symbol_size', self::SYMBOL_SIZE, 's'),
'symbolAlign' => $pick('symbol_align', HeadingAccent::ALIGN, 'top'),
'surface' => $pick('surface', self::SURFACE, null),
'border' => ($settings['border'] ?? null) === 'line',
'bar' => $pick('bar', self::BAR, null),
];
}
/**
* Das Skript der Hinweiszeile (resources/js/notice.js) ohne Kommentare, zum Einbetten in die Seite. Es steht beim ersten
* Hinweis einer Seite inline im Quelltext und entscheidet dort über die Darstellung, bevor der Browser die folgenden
* Inhalte malt; sonst spränge ein Hinweis nach dem Laden vom vollen Text zur Kurzdarstellung. Dieselbe Datei läuft auch
* als Modul (app.js) für dynamisch eingefügte Hinweise.
*/
public static function bootScript(): string
{
$file = resource_path('js/notice.js');
// Fehlt die Datei im Abbild, bleibt die Seite lesbar: Das Modul (app.js) übernimmt, nur ein Sprung beim Laden ist möglich.
if (! is_readable($file)) {
return '';
}
$source = (string) file_get_contents($file);
$source = (string) preg_replace('#/\*.*?\*/#s', '', $source);
$source = (string) preg_replace('#^\s*//.*$#m', '', $source);
return trim((string) preg_replace('/\n\s*\n+/', "\n", $source));
}
public function key(): string
{
return 'notice';
}
public function label(): string
{
return 'Hinweiszeile';
}
public function description(): string
{
return 'Kompakter Hinweis mit formatiertem Text und Symbol, wahlweise mit aufklappbarer Kurzdarstellung.';
}
public function supportedUnits(): array
{
return [1, 2, 3, 4];
}
public function preferredUnits(): int
{
return 4;
}
public function narrowBehavior(): string
{
return 'Der Text bricht um, nichts wird abgeschnitten. Je nach Modus wechselt der Hinweis bei geringer Widgetbreite zur aufklappbaren Kurzdarstellung; die Breite des Widgets entscheidet, nicht die des Fensters.';
}
public function stages(): array
{
return [
'narrow' => 'Modus „Responsiv“: Kurzdarstellung (bei Zeilengrenze nur, wenn der Volltext mehr Zeilen braucht)',
'wide' => 'vollständiger Text; im Modus „Immer mit Kurzdarstellung starten“ auch hier zuerst die Kurzdarstellung',
];
}
public function icon(): string
{
return 'heroicon-o-information-circle';
}
public function schematic(): array
{
return [[2, 11, 56, 14, 'line'], [2, 11, 2, 14, 'accent'], [8, 15, 30, 3, 'ink'], [8, 20, 44, 2, 'line']];
}
public function dataRules(): array
{
return [
'text' => ['required', 'string', 'max:'.self::TEXT_MAX_LENGTH],
'short' => ['nullable', 'string', 'max:'.self::SHORT_MAX_LENGTH],
];
}
public function dataFields(): array
{
return [
RichField::make('text', 'Vollständiger Text', website: true)
->required()
->helperText('Der ganze Hinweis. Wie beim Fließtext: fett, kursiv, Farbmarkierungen (Marine, Grün, Rot, Grau), Links, Listen und Ausrichtung. Im Modus „Volltext“ ist das der einzige Text, der angezeigt wird.'),
RichField::make('short', 'Kurztext (optional)', website: true)
->helperText('Die Kurzdarstellung für die Modi „Responsiv“ und „Immer mit Kurzdarstellung starten“, am besten ein Satz. Er wird gespeichert, auch wenn der Modus „Volltext“ gewählt ist, und geht beim Wechsel des Modus nicht verloren. Ohne Kurztext erscheint immer der vollständige Text.'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$text = FormattedText::canonical(is_string($data['text'] ?? null) ? $data['text'] : '', true);
$short = FormattedText::canonical(is_string($data['short'] ?? null) ? $data['short'] : '', true);
if ($text === '') {
$errors->add('data.text', 'Bitte den vollständigen Text eingeben.');
}
// Die Schlüssel stehen nur, wenn sie ausgefüllt sind; ein leerer Kurztext bleibt byteweise ohne Spur.
$data['text'] = $text;
if ($short === '') {
unset($data['short']);
} else {
$data['short'] = $short;
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$text = $widget['data']['text'] ?? null;
$short = $widget['data']['short'] ?? null;
$shortHtml = is_string($short) && trim($short) !== '' ? ProseWidget::render($short) : '';
$layout = self::layout($widget['settings'] ?? [], $shortHtml !== '');
return [
'textHtml' => is_string($text) && trim($text) !== '' ? ProseWidget::render($text) : '',
'shortHtml' => $shortHtml,
'layout' => $layout,
// Nur die Vorschau weist darauf hin, dass ein gewählter Modus ohne Kurztext nichts einklappen kann.
'notice' => $context->preview && $shortHtml === '' && self::layout($widget['settings'] ?? [])['mode'] !== 'full'
? 'Der gewählte Modus braucht einen Kurztext. Ohne ihn erscheint der vollständige Text immer.'
: null,
];
}
public function settings(): array
{
return [
'mode' => self::MODE,
'line_limit' => self::LINE_LIMIT,
'narrow' => self::NARROW,
'size' => self::SIZE,
'align' => HeadingAccent::TEXT_ALIGN,
'symbol' => HeadingAccent::symbols(),
'symbol_size' => self::SYMBOL_SIZE,
'symbol_align' => HeadingAccent::ALIGN,
'surface' => self::SURFACE,
'border' => self::BORDER,
'bar' => self::BAR,
];
}
public function settingGroups(): array
{
return [
'Darstellungsmodus' => ['mode', 'narrow', 'line_limit'],
'Text' => ['size', 'align'],
'Symbol' => ['symbol', 'symbol_size', 'symbol_align'],
'Fläche' => ['surface', 'border', 'bar'],
];
}
public function settingLabels(): array
{
return [
'mode' => ['Darstellungsmodus', 'Volltext (Vorgabe): Der ganze Hinweis ist immer sichtbar. Responsiv: Breit der ganze Text, bei wenig Platz die Kurzdarstellung mit Pfeil zum Aufklappen. Immer mit Kurzdarstellung starten: Auf jeder Breite zuerst der Kurztext, ein Klick zeigt den ganzen Text, ein weiterer Klick klappt wieder zu. Die Kurzdarstellung ist beim Laden immer eingeklappt. Beide Fassungen bleiben beim Wechsel erhalten; ohne Kurztext erscheint immer der vollständige Text.'],
'narrow' => ['Wann gilt „wenig Platz“?', 'Gemessen wird die Breite des Widgets, nicht die des Fensters: Ein Hinweis in einer schmalen Spalte klappt früher ein als derselbe Hinweis über die ganze Seite. Wirkt nur im Modus „Responsiv“. Vorgabe: unter 40 rem (etwa 640 px).'],
'line_limit' => ['Zeilengrenze', 'Nur bei wenig Platz und nur im Modus „Responsiv“: Die Kurzdarstellung erscheint, wenn der vollständige Text bei der tatsächlichen Breite mehr Zeilen braucht als gewählt (gezählt werden umgebrochene Textzeilen). Es werden nie Zeilen abgeschnitten. Ohne Grenze (Vorgabe) steht bei wenig Platz immer die Kurzdarstellung. Im Modus „Immer mit Kurzdarstellung starten“ wird die Grenze nicht berücksichtigt.'],
'size' => ['Schriftgröße', 'XS, S (Vorgabe), M und L. S, M und L sind die Stufen „klein“, „Text“ und „Einleitung“ des Designsystems; XS ist etwas kleiner (13 px) und nur für Randbemerkungen gedacht.'],
'align' => ['Ausrichtung', 'Richtet den Text aus. Vorgabe: linksbündig.'],
'symbol' => ['Symbol', 'Kleine Grafik aus dem Brand-Kit vor dem Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'],
'symbol_size' => ['Größe des Symbols', 'Unabhängig von der Schriftgröße: von sehr klein (1 rem) bis sehr groß (3,5 rem). Vorgabe: Klein. Wirkt nur, wenn ein Symbol gewählt ist.'],
'symbol_align' => ['Senkrechte Lage des Symbols', 'Oben (Vorgabe, auf Höhe der ersten Zeile), Mitte oder Unten. Wirkt nur, wenn ein Symbol gewählt ist.'],
'surface' => ['Hintergrundfläche', 'Eine dezente Fläche hinter dem Hinweis (Farben des Designsystems). Auf der Fläche ist die Schrift immer dunkel, auch auf dunklen Abschnitten. Vorgabe: ohne Fläche, der Hinweis steht auf dem Abschnitt.'],
'border' => ['Rahmen', 'Ein feiner Rahmen um den Hinweis. Vorgabe: ohne.'],
'bar' => ['Akzentlinie', 'Eine farbige Linie links oder oben am Hinweis. Vorgabe: ohne.'],
];
}
public function summary(array $widget): string
{
$html = FormattedText::canonical(is_string($widget['data']['text'] ?? null) ? $widget['data']['text'] : '', true);
$text = trim((string) preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags((string) preg_replace('#</(?:p|li|blockquote)>#', ' $0', $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
return mb_strlen($text) > 120 ? rtrim(mb_substr($text, 0, 119)).'…' : $text;
}
}
+79 -12
View File
@@ -2,13 +2,32 @@
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Catalog\FormattedText;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\HeadingAccent;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use App\Filament\Support\RichField;
/**
* Fließtext mit dem Editor der Dokumente (ADR-50, ADR-51): Zwischenüberschriften, fett, kursiv, Links, Listen, Zitate und
* Tabellen, dazu Schriftgröße, Schriftfarbe und Ausrichtung aus festen Werten (Webprofil von FormattedText). Gespeichert wird bereinigtes HTML (FormattedText, Regel „Links auf eigene Seiten erlaubt“); Skripte, Stile und
* Ereignisattribute entfallen. Bilder gibt es im Text nicht: Die Bilder der Website stehen als eigene Bausteine (zum
* Beispiel Bild und Text), nicht als Bildfassungen eines Dokuments.
*
* Version 1 (Bestand): Klartext, eine Leerzeile beginnt einen Absatz. Version 2: formatierter Text (HTML).
*/
class ProseWidget extends WidgetType
{
/** Größtes zulässiges Maß des gespeicherten HTML (entspricht der Bereinigung des Textbausteins). */
public const MAX_LENGTH = 100000;
public function version(): int
{
return 2;
}
public function key(): string
{
return 'prose';
@@ -21,7 +40,7 @@ public function label(): string
public function description(): string
{
return 'Längerer Text in Absätzen. Eine Leerzeile beginnt einen neuen Absatz.';
return 'Längerer Text mit Zwischenüberschriften, Hervorhebungen, Listen, Zitaten, Tabellen und Links, geschrieben im Editor wie bei den Dokumenten.';
}
public function supportedUnits(): array
@@ -31,12 +50,12 @@ public function supportedUnits(): array
public function narrowBehavior(): string
{
return 'Fließtext bricht um; Zeilen höchstens etwa 70 Zeichen.';
return 'Fließtext bricht um; Zeilen höchstens etwa 70 Zeichen. Eine Tabelle scrollt bei wenig Platz waagerecht.';
}
public function preferredUnits(): int
{
return 2;
return 4;
}
public function stages(): array
@@ -51,37 +70,80 @@ public function icon(): string
return 'heroicon-o-bars-3-bottom-left';
}
public function upgrade(array $widget, int $from): array
{
if ($from === 1) {
// Klartext wird zu Absätzen an den Leerzeilen (wie bisher dargestellt), nicht zu Listen oder Überschriften.
$body = $widget['data']['body'] ?? '';
$widget['data']['body'] = FormattedText::canonicalHtml(RichText::fromPlainText(is_string($body) ? $body : ''), true);
return $widget;
}
return parent::upgrade($widget, $from);
}
public function dataRules(): array
{
return [
'body' => ['required', 'string', 'max:20000'],
'body' => ['required', 'string', 'max:'.self::MAX_LENGTH],
];
}
public function dataFields(): array
{
return [
Textarea::make('body')
->label('Text')
->rows(10)
RichField::make('body', 'Text', website: true)
->required()
->maxLength(20000)
->helperText('Eine Leerzeile beginnt einen neuen Absatz.'),
->helperText('Zwischenüberschriften (H3 bis H6), fett, kursiv, Links, Listen, Zitate und Tabellen. Dazu Schriftgröße, Schriftfarbe (Marine, Grün, Rot, Grau) und Ausrichtung (linksbündig, zentriert, rechtsbündig) des Absatzes. Auf dunklen und grünen Flächen werden die Farben aufgehellt, damit die Schrift lesbar bleibt. Links auf eigene Seiten wie /materialien oder #anker sind möglich. Eine Tabelle legen Sie über das Tabellensymbol an; die erste Zeile lässt sich als Kopfzeile kennzeichnen.'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$data['body'] = FormattedText::canonical(is_string($data['body'] ?? null) ? $data['body'] : '', true);
if ($data['body'] === '') {
$errors->add('data.body', 'Bitte einen Text eingeben.');
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
return ['html' => self::render($widget['data']['body'] ?? null)];
}
/**
* Sicheres HTML zur Ausgabe. Jede Tabelle steht in einem Rahmen, der bei wenig Platz waagerecht scrollt und mit der
* Tastatur erreichbar ist.
*/
public static function render(mixed $body): string
{
$html = FormattedText::html(is_string($body) ? $body : '', null, true);
// Die Ausrichtung steht gespeichert als Stil (so liest der Editor sie); auf der Seite wird sie eine Klasse.
return str_replace(
['<table>', '</table>', ' style="text-align: center"', ' style="text-align: end"'],
['<div class="prose-table" role="region" tabindex="0" aria-label="Tabelle"><table>', '</table></div>', ' class="ta-center"', ' class="ta-end"'],
$html,
);
}
public function settings(): array
{
return [
'symbol' => HeadingAccent::symbols(),
'symbol_size' => HeadingAccent::SIZE,
'symbol_align' => HeadingAccent::ALIGN,
'text_width' => HeadingAccent::TEXT_WIDTH,
];
}
public function settingGroups(): array
{
return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align']];
return ['Aussehen' => ['text_width', 'symbol', 'symbol_size', 'symbol_align']];
}
public function settingLabels(): array
@@ -90,11 +152,16 @@ public function settingLabels(): array
'symbol' => ['Symbol neben dem Text', 'Kleine Grafik aus dem Brand-Kit links neben dem ganzen Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'],
'symbol_size' => ['Größe des Symbols', 'Vorgabe: Mittel. Bei wenig Platz steht das Symbol über dem Text. Wirkt nur, wenn ein Symbol gewählt ist.'],
'symbol_align' => HeadingAccent::ALIGN_LABEL,
'text_width' => HeadingAccent::TEXT_WIDTH_LABEL,
];
}
public function summary(array $widget): string
{
return RichText::excerpt(e((string) ($widget['data']['body'] ?? '')));
// Gelesen wird im Webprofil: Das Profil der Verwaltung kennt Spans (Größe, Farbe) nicht und ließe ihren Text weg.
$html = FormattedText::canonical(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : '', true);
$text = trim((string) preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags((string) preg_replace('#</(?:p|h[3-6]|li|td|th|blockquote)>#', ' $0', $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
return mb_strlen($text) > 120 ? rtrim(mb_substr($text, 0, 119)).'…' : $text;
}
}
@@ -79,6 +79,7 @@ public function variants(): array
{
return [
'kacheln' => 'Kacheln mit Bild',
'liste' => 'Liste mit kleinem Bild',
];
}
@@ -88,6 +89,7 @@ public function settings(): array
'sort' => ['name' => 'Alphabetisch', 'neu' => 'Neueste zuerst', 'preis' => 'Preis aufsteigend'],
'limit' => ['alle' => 'Alle Produkte', 'n3' => '3 Produkte', 'n6' => '6 Produkte', 'n9' => '9 Produkte', 'n12' => '12 Produkte', 'n24' => '24 Produkte'],
'search' => ['aus' => 'Ohne Suchfeld', 'an' => 'Mit Suchfeld'],
'filter' => ['aus' => 'Ohne Auswahl', 'an' => 'Mit Suche, Auswahl, Ansicht und Seiten'],
];
}
@@ -96,13 +98,14 @@ public function settingLabels(): array
return [
'sort' => ['Reihenfolge', 'Ohne Wahl gilt die Reihenfolge der Shopseite: Altbestand, Artikel, Pakete.'],
'limit' => ['Anzahl', 'Wie viele Produkte höchstens erscheinen. Ohne Wahl erscheinen alle.'],
'search' => ['Suchfeld', 'Ein Suchfeld über den Kacheln. Es wirkt auf der Shopseite; auf anderen Seiten führt die Suche in den Shop.'],
'search' => ['Suchfeld', 'Ein einfaches Suchfeld über den Kacheln. Es sendet an die Seite, auf der das Widget steht.'],
'filter' => ['Auswahl für Besucher', 'Suche, Auswahl nach Thema, Materialart, Eignung und Nutzerkreis, Reihenfolge, Umschalter Kacheln und Liste und Seiten. Sinnvoll auf der Shopseite mit vielen Produkten. Ersetzt das einfache Suchfeld und die Einstellung „Anzahl“.'],
];
}
public function settingGroups(): array
{
return ['Auswahl' => ['sort', 'limit', 'search']];
return ['Auswahl' => ['sort', 'limit', 'search', 'filter']];
}
public function dataRules(): array
@@ -165,21 +168,28 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
public function resolve(array $widget, RenderContext $context): array
{
if (! Shop::visible()) {
return ['cards' => [], 'term' => '', 'shopVisible' => false];
return ['listing' => null, 'cards' => [], 'term' => '', 'shopVisible' => false];
}
$settings = is_array($widget['settings'] ?? null) ? $widget['settings'] : [];
$filters = ($settings['filter'] ?? 'aus') === 'an';
$search = ($settings['search'] ?? 'aus') === 'an';
$term = $search && ! $context->preview ? trim((string) request()->query('suche', '')) : '';
$limit = preg_match('/^n(\d+)$/', (string) ($settings['limit'] ?? ''), $match) === 1 ? (int) $match[1] : null;
$limit = preg_match('/^n(\\d+)$/', (string) ($settings['limit'] ?? ''), $match) === 1 ? (int) $match[1] : null;
$query = $context->preview ? [] : request()->query();
$term = ($search || $filters) && isset($query['suche']) && is_string($query['suche']) ? mb_substr(trim($query['suche']), 0, 100) : '';
$fixed = [
'pillar' => $widget['data']['pillar'] ?? null,
'kind' => $widget['data']['kind'] ?? null,
'sort' => $settings['sort'] ?? null,
'limit' => $filters ? null : $limit,
'view' => ($widget['variant'] ?? 'kacheln') === 'liste' ? 'liste' : 'kacheln',
'filters' => $filters,
];
$listing = app(ShopCatalog::class)->listing($filters ? $query : ['suche' => $term], $fixed);
return [
'cards' => app(ShopCatalog::class)->cards($term, [
'pillar' => $widget['data']['pillar'] ?? null,
'kind' => $widget['data']['kind'] ?? null,
'sort' => $settings['sort'] ?? null,
'limit' => $limit,
]),
'listing' => $listing,
'cards' => $listing['cards'],
'term' => $term,
'shopVisible' => true,
];
+6 -4
View File
@@ -210,7 +210,7 @@ private function optionsFor(string $key): array
/**
* Günstigster Preis und Zahl der Optionen je Seite einer Art ('a', 'b' oder 'c'): Kennung => Zusammenfassung.
*
* @return array<int, array{from_cents: int, count: int}>
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
*/
private function summariesOf(string $kind): array
{
@@ -224,6 +224,8 @@ private function summariesOf(string $kind): array
$summary[(int) substr($key, 2)] = [
'from_cents' => min(array_map(fn (array $row): int => (int) $row['version']->price_cents, $rows)),
'count' => count($rows),
'holders' => array_values(array_unique(array_map(fn (array $row): string => (string) $row['version']->holder_kind, $rows))),
'scopes' => array_values(array_unique(array_filter(array_map(fn (array $row): ?string => $row['version']->licence_scope, $rows)))),
];
}
@@ -233,7 +235,7 @@ private function summariesOf(string $kind): array
/**
* Artikel mit kaufbarer Option: Artikelkennung => günstigster Preis und Zahl der Optionen.
*
* @return array<int, array{from_cents: int, count: int}>
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
*/
public function articleSummaries(): array
{
@@ -243,7 +245,7 @@ public function articleSummaries(): array
/**
* Pakete mit kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
*
* @return array<int, array{from_cents: int, count: int}>
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
*/
public function bundleSummaries(): array
{
@@ -253,7 +255,7 @@ public function bundleSummaries(): array
/**
* Altbestand: Programmseiten mit kaufbaren Optionen (Angebote mit mehreren Positionen).
*
* @return array<int, array{from_cents: int, count: int}>
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
*/
public function summaries(): array
{
+140 -11
View File
@@ -6,6 +6,7 @@
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Pillar;
use App\Domain\Catalog\PresentationMedia;
@@ -37,11 +38,21 @@ public function __construct(
public const SORTS = ['name' => 'Alphabetisch', 'neu' => 'Neueste zuerst', 'preis' => 'Preis aufsteigend'];
/**
* @param array{pillar?: int|null, kind?: int|null, sort?: string|null, limit?: int|null} $options Filter nach Säule
* und Materialart, Sortierung (name, neu, preis) und Höchstzahl
* @param array{pillar?: int|null, kind?: int|null, holder?: string|null, scope?: string|null, sort?: string|null, limit?: int|null} $options Filter
* nach Säule, Materialart, Eignung und Nutzerkreis, Sortierung (name, neu, preis) und Höchstzahl
* @return list<array<string, mixed>>
*/
public function cards(string $term = '', array $options = []): array
{
return $this->arrange($this->all($term), $options);
}
/**
* Alle Kacheln zu einem Suchbegriff, ungefiltert und in der Reihenfolge der Quellen.
*
* @return list<array<string, mixed>>
*/
public function all(string $term = ''): array
{
$term = mb_strtolower(mb_substr(trim($term), 0, 100));
$cards = [];
@@ -56,10 +67,13 @@ public function cards(string $term = '', array $options = []): array
$title = (string) ($composition->display_title ?: $composition->designation);
$teaser = (string) ($composition->teaser ?: FormattedText::plain($composition->summary));
$pillars = $this->pillarNames($composition->pillars);
$pillarMap = $this->publishedPillars($composition->pillars);
$pillars = array_values($pillarMap);
$card = $this->card('c:'.$composition->id, 'programm', route('public.program', $composition), $title, $teaser, $summaries[$composition->id], 'Programm', null, $pillars, [], $this->image($composition));
$card['pillar_ids'] = $composition->pillars->pluck('id')->map(fn ($id): int => (int) $id)->all();
$card['pillar_ids'] = array_keys($pillarMap);
$card['kind_id'] = $composition->editorial_content_kind_id !== null ? (int) $composition->editorial_content_kind_id : null;
$card['holders'] = $summaries[$composition->id]['holders'] ?? [];
$card['scopes'] = $summaries[$composition->id]['scopes'] ?? [];
if ($this->matches($term, $title.' '.$teaser.' '.FormattedText::plain($composition->summary).' '.$composition->search_terms.' '.implode(' ', $pillars))) {
$cards[] = $card;
@@ -74,15 +88,18 @@ public function cards(string $term = '', array $options = []): array
$title = $this->products->articleTitle($article);
$teaser = (string) ($profile->value('teaser') ?: $profile->value('summary'));
$kind = $article->editorialContentKind;
$pillars = $this->pillarNames($article->pillars);
$pillarMap = $this->publishedPillars($article->pillars);
$pillars = array_values($pillarMap);
$offerIds = array_map(fn ($offer): int => (int) $offer->id, $this->products->offersOfArticle($article));
$card = $this->card(
'a:'.$article->id, 'artikel', route('shop.article', $article), $title, $teaser, $articleSummaries[$article->id],
(string) ($kind?->label ?? ''), $this->symbol($kind?->symbol), $pillars, $this->markers->visible($article, $offerIds), $this->image($article),
);
$card['pillar_ids'] = $article->pillars->pluck('id')->map(fn ($id): int => (int) $id)->all();
$card['pillar_ids'] = array_keys($pillarMap);
$card['kind_id'] = $kind !== null ? (int) $kind->id : null;
$card['since'] = $this->markers->firstOffered($offerIds)?->getTimestamp() ?? 0;
$card['holders'] = $articleSummaries[$article->id]['holders'] ?? [];
$card['scopes'] = $articleSummaries[$article->id]['scopes'] ?? [];
if ($this->matches($term, $title.' '.$teaser.' '.$profile->value('summary').' '.$profile->searchTerms.' '.($kind?->label ?? '').' '.implode(' ', $pillars))) {
$cards[] = $card;
@@ -97,13 +114,15 @@ public function cards(string $term = '', array $options = []): array
$names = implode(', ', array_column($contents, 'title'));
$teaser = 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : '');
$card = $this->card('b:'.$bundle->id, 'paket', route('public.package', $bundle), (string) $bundle->name, $teaser, $bundleSummaries[$bundle->id], 'Paket', null, [], [], $this->image($bundle));
$card['holders'] = $bundleSummaries[$bundle->id]['holders'] ?? [];
$card['scopes'] = $bundleSummaries[$bundle->id]['scopes'] ?? [];
if ($this->matches($term, $bundle->name.' '.$names)) {
$cards[] = $card;
}
}
return $this->arrange($cards, $options);
return $cards;
}
/**
@@ -114,7 +133,7 @@ public function cards(string $term = '', array $options = []): array
* @param array<string, mixed> $options
* @return list<array<string, mixed>>
*/
private function arrange(array $cards, array $options): array
public function arrange(array $cards, array $options): array
{
$pillar = isset($options['pillar']) ? (int) $options['pillar'] : 0;
$kind = isset($options['kind']) ? (int) $options['kind'] : 0;
@@ -127,6 +146,17 @@ private function arrange(array $cards, array $options): array
$cards = array_filter($cards, fn (array $card): bool => ($card['kind_id'] ?? null) === $kind);
}
$holder = (string) ($options['holder'] ?? '');
$scope = (string) ($options['scope'] ?? '');
if ($holder !== '') {
$cards = array_filter($cards, fn (array $card): bool => in_array($holder, $card['holders'] ?? [], true));
}
if ($scope !== '') {
$cards = array_filter($cards, fn (array $card): bool => in_array($scope, $card['scopes'] ?? [], true));
}
$cards = array_values($cards);
match ($options['sort'] ?? null) {
@@ -141,6 +171,103 @@ private function arrange(array $cards, array $options): array
return $limit > 0 ? array_slice($cards, 0, $limit) : $cards;
}
public const HOLDERS = ['person' => 'Privatpersonen', 'organisation' => 'Organisationen und Vereine'];
public const SCOPES = [LicenceScope::SINGLE => 'Einzellizenz', LicenceScope::MULTI => 'Mehrfachlizenz'];
/**
* Die Auswahl, die ein Besucher bei diesen Kacheln hat: nur Werte, die es gibt, und nur Auswahlfelder mit mindestens
* zwei Werten (sonst filtert nichts).
*
* @param list<array<string, mixed>> $cards
* @return array{pillar: array<int, string>, kind: array<int, string>, holder: array<string, string>, scope: array<string, string>}
*/
public function facets(array $cards): array
{
$pillars = [];
$kinds = [];
$holders = [];
$scopes = [];
foreach ($cards as $card) {
foreach (array_values($card['pillar_ids'] ?? []) as $index => $id) {
$pillars[(int) $id] = (string) ($card['pillars'][$index] ?? '');
}
if (($card['kind_id'] ?? null) !== null && ($card['kind_label'] ?? '') !== '') {
$kinds[(int) $card['kind_id']] = (string) $card['kind_label'];
}
foreach ($card['holders'] ?? [] as $holder) {
if (isset(self::HOLDERS[$holder])) {
$holders[$holder] = self::HOLDERS[$holder];
}
}
foreach ($card['scopes'] ?? [] as $scope) {
if (isset(self::SCOPES[$scope])) {
$scopes[$scope] = self::SCOPES[$scope];
}
}
}
asort($pillars);
asort($kinds);
$facets = ['pillar' => $pillars, 'kind' => $kinds, 'holder' => $holders, 'scope' => $scopes];
return array_map(fn (array $values): array => count($values) >= 2 ? $values : [], $facets);
}
/**
* Die Produktliste für Shopseite und Widget: Suche, Auswahl des Besuchers (Säule, Materialart, Eignung,
* Nutzerkreis), Reihenfolge, Ansicht und Seiten. Alles kommt aus dem Abfragetext und wird gegen feste Werte
* geprüft; unbekannte Werte entfallen.
*
* @param array<string, mixed> $query Abfrage des Besuchers (suche, saeule, art, eignung, kreis, sort, ansicht, seite)
* @param array<string, mixed> $fixed Vorgaben der Seite (pillar, kind, sort, limit, view, filters)
* @return array<string, mixed>
*/
public function listing(array $query, array $fixed = []): array
{
$text = fn (string $key): string => isset($query[$key]) && (is_string($query[$key]) || is_int($query[$key])) ? trim((string) $query[$key]) : '';
$filters = (bool) ($fixed['filters'] ?? true);
$term = mb_substr($text('suche'), 0, 100);
$base = $this->arrange($this->all($term), array_intersect_key($fixed, ['pillar' => 1, 'kind' => 1]));
$facets = $filters ? $this->facets($base) : ['pillar' => [], 'kind' => [], 'holder' => [], 'scope' => []];
$pick = function (string $key, string $facet) use ($text, $facets, $filters): int|string|null {
$value = $text($key);
return $filters && $value !== '' && array_key_exists($value, $facets[$facet]) ? (ctype_digit($value) ? (int) $value : $value) : null;
};
$chosen = [
'pillar' => $pick('saeule', 'pillar'),
'kind' => $pick('art', 'kind'),
'holder' => $pick('eignung', 'holder'),
'scope' => $pick('kreis', 'scope'),
];
$sort = $filters && isset(self::SORTS[$text('sort')]) ? $text('sort') : ($fixed['sort'] ?? null);
$view = $filters && in_array($text('ansicht'), ['kacheln', 'liste'], true) ? $text('ansicht') : (string) ($fixed['view'] ?? 'kacheln');
$cards = $this->arrange($base, $chosen + ['sort' => $sort, 'limit' => $fixed['limit'] ?? null]);
$perPage = max(1, (int) config('shop.per_page', 12));
$pages = max(1, (int) ceil(count($cards) / $perPage));
$page = $filters ? min($pages, max(1, (int) $text('seite'))) : 1;
$shown = $filters ? array_slice($cards, ($page - 1) * $perPage, $perPage) : $cards;
return [
'cards' => $shown,
'total' => count($cards),
'page' => $page,
'pages' => $filters ? $pages : 1,
'facets' => $facets,
'chosen' => $chosen,
'sort' => $sort,
'view' => $view,
'term' => $term,
'filters' => $filters,
];
}
/**
* @param array{from_cents: int, count: int} $summary
* @param list<string> $pillars
@@ -167,6 +294,8 @@ private function card(string $key, string $kind, string $url, string $title, str
'pillar_ids' => [],
'kind_id' => null,
'since' => 0,
'holders' => [],
'scopes' => [],
];
}
@@ -179,11 +308,11 @@ private function matches(string $term, string $haystack): bool
* Nur veröffentlichte Säulen sind öffentlich (Säulenverwaltung).
*
* @param Collection<int, Pillar> $pillars
* @return list<string>
* @return array<int, string> Kennung => Name
*/
private function pillarNames(Collection $pillars): array
private function publishedPillars(Collection $pillars): array
{
return $pillars->filter(fn (Pillar $pillar): bool => $pillar->published_at !== null)->map(fn (Pillar $pillar): string => (string) $pillar->name)->values()->all();
return $pillars->filter(fn (Pillar $pillar): bool => $pillar->published_at !== null)->mapWithKeys(fn (Pillar $pillar): array => [(int) $pillar->id => (string) $pillar->name])->all();
}
/** Ein Symbol zeigt nur, was die Symbolbibliothek kennt (die Auswahl wird an der Materialart geprüft, hier noch einmal). */
@@ -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'), ',');
}
}
+210
View File
@@ -0,0 +1,210 @@
<?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) {
$stepVisible = ! $this->any($byTarget['step:'.$step['key']] ?? [], 'skip', $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'],
];
}
}
+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;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?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
{
public static function issue(int $entryId, int $versionId): string
{
return Crypt::encryptString(json_encode([
'e' => $entryId,
'v' => $versionId,
't' => now()->getTimestamp(),
'n' => Str::random(32),
], JSON_THROW_ON_ERROR));
}
/**
* @return array{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 ['e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']];
}
}
+51
View File
@@ -0,0 +1,51 @@
<?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])));
}
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');
}
}
+292
View File
@@ -0,0 +1,292 @@
<?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
{
$token = FormToken::read($payload['token'] ?? null);
if ($token === null || $token['e'] !== $entry->id) {
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 = $this->deliver($entry, $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' => $entry->id,
'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, ['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,
];
}
}
@@ -0,0 +1,176 @@
<?php
namespace App\Filament\Pages;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\ExampleConfiguration;
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 = 7;
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('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 !== '')));
}
}
+67 -4
View File
@@ -2,9 +2,11 @@
namespace App\Filament\Pages;
use App\Domain\Cms\LinkTargets;
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page as CmsPage;
use App\Domain\Cms\PageService;
use App\Domain\Cms\Sections\PageSections;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\Bestand;
@@ -74,7 +76,7 @@ class Webpraesenz extends Page
/** Ausgewählter Eintrag (Schlüssel „e{id}“ oder „n{zähler}“ für neue Einträge). */
public ?string $auswahl = null;
/** @var array<string, array{id: ?int, label: string, page_id: ?int, url: string, placement: string, parent: ?string, is_visible: bool}> */
/** @var array<string, array{id: ?int, label: string, page_id: ?int, url: string, anchor: string, placement: string, parent: ?string, is_visible: bool}> */
public array $eintraege = [];
/** Globale Reihenfolge der Schlüssel; entspricht sort_order. @var list<string> */
@@ -103,6 +105,9 @@ class Webpraesenz extends Page
/** Eintrag, dessen Ziel gerade gewählt wird. */
public ?string $zielwahl = null;
/** Zweiter Schritt der Zielwahl: gewählte Seite, deren Sprungmarke noch zu wählen ist. */
public ?int $zielSeite = null;
public string $zielSuche = '';
public static function canAccess(): bool
@@ -327,6 +332,7 @@ public function ladeMenues(): void
'label' => (string) $item->label,
'page_id' => $item->page_id,
'url' => (string) ($item->url ?? ''),
'anchor' => (string) ($item->anchor ?? ''),
'placement' => (string) $item->placement,
'parent' => $item->parent_id !== null ? 'e'.$item->parent_id : null,
'is_visible' => (bool) $item->is_visible,
@@ -364,6 +370,7 @@ private function bereichsStaende(): array
trim($e['label']),
$e['page_id'] !== null ? (int) $e['page_id'] : null,
trim($e['url']),
trim($e['anchor'] ?? ''),
(bool) $e['is_visible'],
$this->elternVon($k),
];
@@ -562,6 +569,7 @@ public function eintragHinzufuegen(): void
'label' => '',
'page_id' => null,
'url' => '',
'anchor' => '',
'placement' => $this->menue,
'parent' => null,
'is_visible' => true,
@@ -595,7 +603,7 @@ public function updatedEintraege(mixed $value, string $pfad): void
match ($feld) {
'placement' => $this->bereichGeaendert($k),
'parent' => $this->elternGeaendert($k),
'page_id' => $this->eintraege[$k]['page_id'] = blank($value) ? null : (int) $value,
'page_id' => $this->seiteGeaendert($k, $value),
'is_visible' => $this->eintraege[$k]['is_visible'] = (bool) $value,
default => null,
};
@@ -673,10 +681,18 @@ private function ansEnde(string $k): void
$this->folge = [...array_values(array_filter($this->folge, fn (string $x): bool => $x !== $k)), $k];
}
/** Eine andere Zielseite hat eigene Sprungmarken: Die bisherige Marke entfällt. */
private function seiteGeaendert(string $k, mixed $value): void
{
$this->eintraege[$k]['page_id'] = blank($value) ? null : (int) $value;
$this->eintraege[$k]['anchor'] = '';
}
public function zielAdresseNutzen(string $k): void
{
if (isset($this->eintraege[$k])) {
$this->eintraege[$k]['page_id'] = null;
$this->eintraege[$k]['anchor'] = '';
$this->js("requestAnimationFrame(() => document.getElementById('menue-adresse')?.focus())");
}
}
@@ -692,6 +708,7 @@ public function oeffneZielwahl(string $k): void
public function schliesseZielwahl(): void
{
$this->zielwahl = null;
$this->zielSeite = null;
}
public function waehleZiel(int $seiteId): void
@@ -702,8 +719,48 @@ public function waehleZiel(int $seiteId): void
$this->eintraege[$this->zielwahl]['page_id'] = $seiteId;
$this->eintraege[$this->zielwahl]['url'] = '';
$this->eintraege[$this->zielwahl]['anchor'] = '';
$this->resetErrorBag("eintraege.{$this->zielwahl}.url");
$this->zielwahl = null;
// Hat die Seite Sprungmarken, folgt als zweiter Schritt die Wahl der Marke; sonst ist die Auswahl fertig.
if ($this->zielMarken($seiteId) !== []) {
$this->zielSeite = $seiteId;
return;
}
$this->schliesseZielwahl();
}
/**
* Zweiter Schritt von „Ziel ändern“: Sprungmarke der gewählten Seite übernehmen (leer = Seitenanfang).
*/
public function waehleMarke(?string $marke = null): void
{
if ($this->zielwahl === null || $this->zielSeite === null || ! isset($this->eintraege[$this->zielwahl])) {
return;
}
$marke = filled($marke) ? $marke : null;
if ($marke !== null && ! in_array($marke, array_column($this->zielMarken($this->zielSeite), 'anchor'), true)) {
return;
}
$this->eintraege[$this->zielwahl]['anchor'] = $marke ?? '';
$this->schliesseZielwahl();
}
/**
* Sprungmarken einer Seite für den zweiten Schritt.
*
* @return list<array{anchor: string, label: string, hidden: bool, published: bool}>
*/
public function zielMarken(int $seiteId): array
{
$seite = $this->seitenCache()->get($seiteId);
return $seite === null ? [] : app(LinkTargets::class)->anchorsForPage($seite);
}
/**
@@ -755,7 +812,7 @@ public function zielVon(string $k): array
return $seite === null
? ['art' => 'fehlt', 'titel' => null, 'pfad' => null, 'zustand' => ['label' => 'Zielseite nicht mehr vorhanden', 'ton' => 'achtung'], 'seite' => null]
: ['art' => 'seite', 'titel' => $seite->latestRevision?->contentTitle() ?: $seite->path, 'pfad' => $seite->path, 'zustand' => $this->seitenZustand($seite), 'seite' => $seite];
: ['art' => 'seite', 'titel' => $seite->latestRevision?->contentTitle() ?: $seite->path, 'pfad' => $seite->path.(trim($e['anchor'] ?? '') !== '' ? '#'.trim($e['anchor']) : ''), 'zustand' => $this->seitenZustand($seite), 'seite' => $seite];
}
if (trim($e['url']) !== '') {
@@ -919,6 +976,7 @@ private function pruefen(): array
|| $alt->label !== $e['label']
|| $alt->page_id !== ($e['page_id'] !== null ? (int) $e['page_id'] : null)
|| (string) ($alt->url ?? '') !== $e['url']
|| (string) ($alt->anchor ?? '') !== trim($e['anchor'] ?? '')
|| $alt->placement !== $e['placement']
|| ($alt->parent_id !== null ? 'e'.$alt->parent_id : null) !== $this->elternVon($k)
|| (bool) $alt->is_visible !== (bool) $e['is_visible']
@@ -936,16 +994,19 @@ private function pruefen(): array
'placement' => $e['placement'],
'page_id' => $e['page_id'],
'url' => trim($e['url']) === '' ? null : trim($e['url']),
'anchor' => trim($e['anchor'] ?? '') === '' ? null : trim($e['anchor']),
], [
'label' => ['required', 'string', 'max:80'],
'placement' => ['required', 'in:'.implode(',', array_keys(self::BEREICHE))],
'page_id' => ['nullable', 'integer', 'exists:pages,id'],
'url' => ['nullable', 'string', 'max:500', SafeUrl::rule()],
'anchor' => ['nullable', 'string', 'max:'.PageSections::MAX_ANCHOR, 'regex:'.PageSections::ANCHOR_PATTERN],
], [
'label.required' => 'Bitte einen Menütext eingeben.',
'label.max' => 'Der Menütext hat höchstens 80 Zeichen.',
'url.max' => 'Die Adresse hat höchstens 500 Zeichen.',
'page_id.exists' => 'Diese Seite gibt es nicht mehr.',
'anchor.regex' => 'Die Sprungmarke ist ungültig. Bitte über „Ziel ändern“ eine vorhandene wählen.',
]);
$meldungen = $validator->errors()->toArray();
@@ -1044,6 +1105,8 @@ private function schreiben(array $geaendert): array
'label' => trim($e['label']),
'page_id' => $e['page_id'] !== null ? (int) $e['page_id'] : null,
'url' => trim($e['url']) === '' ? null : trim($e['url']),
// Eine Sprungmarke gehört zur Zielseite; ohne Seite (freie Adresse) entfällt sie.
'anchor' => $e['page_id'] !== null && trim($e['anchor'] ?? '') !== '' ? trim($e['anchor']) : null,
'placement' => $e['placement'],
'parent_id' => $eltern !== null ? ($ids[$eltern] ?? $this->eintraege[$eltern]['id']) : null,
'is_visible' => (bool) $e['is_visible'],
@@ -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,143 @@
<?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;
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,120 @@
<?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;
/**
* @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,80 @@
<?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;
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('entry.name')->label('Anfrage-Einstieg')->placeholder('Gelöscht'),
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');
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->entry->name ?? 'Einstieg gelöscht'),
'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,66 @@
<?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;
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;
/**
* Anfragevorlagen: ein vollständiger fachlicher Anfrageprozess. 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 = 'Anfragevorlagen';
protected static ?string $modelLabel = 'Anfragevorlage';
protected static ?string $pluralModelLabel = 'Anfragevorlagen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/vorlagen';
protected static ?int $navigationSort = 5;
public static function form(Schema $schema): Schema
{
return $schema->components(TemplateEditor::schema());
}
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,151 @@
<?php
namespace App\Filament\Resources\Communication\Templates\Pages;
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 diese Vorlage 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('Neue Fassung 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('Die Vorlage 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. Noch kein Anfrage-Einstieg verwendet diese Vorlage.';
}
$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. Sofort betroffen sind diese Anfrage-Einstiege und damit alle Seiten, die sie einbinden: '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
protected function archiveNote(): string
{
return 'Die Vorlage wird archiviert. Anfrage-Einstiege, die sie verwenden, liefern dann kein Formular 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 dieser Vorlage. Bitte zuerst zurückziehen oder auf eine andere Vorlage umstellen." : null;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$data['draft'] = TemplateDraft::clean((array) ($data['draft'] ?? []));
return $data;
}
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 'Eine Anfragevorlage beschreibt einen vollständigen Anfrageprozess: Schritte, Feldgruppen, Bedingungen und Texte. Änderungen entstehen zunächst als Entwurf und gelten erst nach „Veröffentlichen“. Die Anfrage-Einstiege, die eine Vorlage verwenden, übernehmen jede neu veröffentlichte Fassung.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Vorlage anlegen')
->modalHeading('Neue Anfragevorlage')
->modalDescription('Der Aufbau entsteht danach auf der Seite der Vorlage.')
->modalSubmitActionLabel('Vorlage anlegen')
->schema([
TextInput::make('name')->label('Bezeichnung')->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('Die Vorlage 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' => 'Anfragevorlage · '.$steps.' '.($steps === 1 ? 'Schritt' : 'Schritte').' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege'),
'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 ['Anfragevorlage', 'Anfragevorlagen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfragevorlagen', 'text' => 'Mit „Vorlage anlegen“ oben entsteht die erste Vorlage. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
@@ -0,0 +1,78 @@
<?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
->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);
}
}
@@ -6,6 +6,7 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\ChoosesLinkTargets;
use App\Filament\Support\ChoosesWebsiteImages;
use App\Filament\Support\ReportsSectionErrors;
use App\Filament\Support\SectionEditor;
@@ -18,6 +19,7 @@
class CreatePage extends CreateRecord
{
use ChoosesLinkTargets;
use ChoosesWebsiteImages;
use ReportsSectionErrors;
@@ -6,6 +6,7 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\ChoosesLinkTargets;
use App\Filament\Support\ChoosesWebsiteImages;
use App\Filament\Support\ReportsSectionErrors;
use App\Filament\Support\SectionEditor;
@@ -22,6 +23,7 @@
class EditPage extends EditRecord
{
use ChoosesLinkTargets;
use ChoosesWebsiteImages;
use ReportsSectionErrors;
@@ -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());
}),
];
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace App\Filament\Support;
use App\Domain\Cms\LinkTargets;
use App\Domain\Cms\Page;
use App\Domain\Cms\Widgets\Support\SafeUrl;
/**
* Auswahl interner Linkziele im CMS über einen Dialog (filament.cms.link-picker): erst die Seite, dann auf Wunsch eine
* Sprungmarke. Ein Linkfeld (Widgets\Support\LinkField) öffnet den Dialog mit seinem Formularpfad; „übernehmen“ schreibt die Adresse in
* genau dieses Feld, auch im geöffneten Bausteindialog. Gespeichert wird weiterhin nur mit dem Seitenentwurf. Die
* Auswahl ändert keine Seite und veröffentlicht nichts.
*
* Die Sprungmarken der Seite, die gerade bearbeitet wird, stammen aus dem Formular und enthalten damit auch
* ungespeicherte Marken.
*/
trait ChoosesLinkTargets
{
/** Formularpfad des Linkfelds, in das die Adresse übernommen wird; null = Dialog geschlossen. */
public ?string $linkZiel = null;
public string $linkSuche = '';
/** Gewählte Seite im zweiten Schritt: „diese“ (Seite im Editor) oder die Kennung einer Seite. */
public ?string $linkSeite = null;
public function openLinkPicker(string $pfad): void
{
if (preg_match('/^(data|mountedActions\.\d+\.data)(\.[A-Za-z0-9_-]+)+$/', $pfad) !== 1) {
return;
}
$this->linkZiel = $pfad;
$this->linkSuche = '';
$this->linkSeite = null;
$this->forceRenderForLinkPicker();
}
public function closeLinkPicker(): void
{
$this->linkZiel = null;
$this->linkSeite = null;
$this->linkSuche = '';
$this->forceRenderForLinkPicker();
}
public function chooseLinkPage(string $key): void
{
if ($this->linkZiel === null) {
return;
}
if ($key === 'diese' ? ! $this->linkHasOwnPage() : ! Page::query()->whereKey((int) $key)->exists()) {
return;
}
$this->linkSeite = $key;
}
public function backToLinkPages(): void
{
$this->linkSeite = null;
}
/**
* @param ?string $anchor Sprungmarke; leer = Seitenanfang (nur für andere Seiten)
*/
public function applyLink(?string $anchor = null): void
{
if ($this->linkZiel === null || $this->linkSeite === null) {
return;
}
$targets = app(LinkTargets::class);
$anchor = filled($anchor) ? $anchor : null;
if ($this->linkSeite === 'diese') {
$known = array_column($targets->anchorsInEditor($this->linkEditorSections()), 'anchor');
if ($anchor === null || ! in_array($anchor, $known, true)) {
return;
}
$href = $targets->href(null, $anchor);
} else {
$page = Page::query()->with(['latestRevision', 'publishedRevision'])->find((int) $this->linkSeite);
if (! $page instanceof Page) {
return;
}
if ($anchor !== null && ! in_array($anchor, array_column($targets->anchorsForPage($page), 'anchor'), true)) {
return;
}
$href = $targets->href($page->path, $anchor);
}
if (! SafeUrl::isSafe($href)) {
return;
}
data_set($this, $this->linkZiel, $href);
$this->closeLinkPicker();
}
/**
* Seiten im ersten Schritt (ohne die bearbeitete Seite, die als „Diese Seite“ oben steht).
*
* @return list<array<string, mixed>>
*/
public function linkPages(): array
{
return app(LinkTargets::class)->pages($this->linkSuche, $this->linkOwnPageId());
}
/**
* Daten des zweiten Schritts: gewählte Seite, ihre Sprungmarken und die vollständige Adresse.
*
* @return array{titel: string, pfad: ?string, diese: bool, marken: list<array<string, mixed>>, offen: bool, adresse: ?string}|null
*/
public function linkChosen(): ?array
{
if ($this->linkSeite === null) {
return null;
}
$targets = app(LinkTargets::class);
if ($this->linkSeite === 'diese') {
$record = $this->linkOwnPage();
return [
'titel' => 'Diese Seite',
'pfad' => $record?->path,
'diese' => true,
'marken' => $targets->anchorsInEditor($this->linkEditorSections()),
'offen' => $record === null,
'adresse' => $record?->published_revision_id !== null ? $targets->publicUrl($record) : null,
];
}
$page = Page::query()->with(['latestRevision', 'publishedRevision'])->find((int) $this->linkSeite);
if (! $page instanceof Page) {
return null;
}
return [
'titel' => $page->latestRevision?->contentTitle() ?: $page->path,
'pfad' => $page->path,
'diese' => false,
'marken' => $targets->anchorsForPage($page),
'offen' => false,
'adresse' => $page->published_revision_id !== null ? $targets->publicUrl($page) : null,
];
}
/** Hat die Seite im Editor schon Sprungmarken oder eine Adresse? Neue Seiten dürfen auf ihre eigenen Marken zeigen. */
public function linkHasOwnPage(): bool
{
return property_exists($this, 'data');
}
public function linkOwnPage(): ?Page
{
$record = property_exists($this, 'record') ? ($this->record ?? null) : null;
return $record instanceof Page ? $record : null;
}
/**
* Sprungmarken der Seite im Editor (auch ungespeicherte).
*
* @return list<array<string, mixed>>
*/
public function linkOwnAnchors(): array
{
return $this->linkHasOwnPage() ? app(LinkTargets::class)->anchorsInEditor($this->linkEditorSections()) : [];
}
private function linkOwnPageId(): ?int
{
return $this->linkOwnPage()?->getKey();
}
/**
* @return list<array<string, mixed>>
*/
private function linkEditorSections(): array
{
$state = is_array($this->data['sections'] ?? null) ? $this->data['sections'] : [];
return SectionEditor::fromEditorState($state);
}
/**
* Filament rendert bei offenen Aktionsdialogen nur den Dialogteil neu; der Auswahldialog liegt darüber und braucht
* die ganze Seite.
*/
public function hydrateChoosesLinkTargets(): void
{
if ($this->linkZiel !== null) {
$this->forceRenderForLinkPicker();
}
}
private function forceRenderForLinkPicker(): void
{
if (method_exists($this, 'forceRender')) {
$this->forceRender();
}
}
}
+13
View File
@@ -7,6 +7,7 @@
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\Pillar;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Cms\Widgets\Support\HeroVideo;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Http\Controllers\ContentPreviewController;
@@ -127,6 +128,18 @@ public function pickerResult(): array
$result = app(EditorialCatalog::class)->presentationBrowse($this->pickerQuery, $this->pickerKind);
$result = $this->filterByMaterialart($result);
// CMS: nur Filme, die als Video wählbar sind (nicht archiviert, nicht gesperrt, keine Traineranleitung).
if ($this->pickerPurpose === 'website-video') {
$ids = array_values(array_filter(array_map(fn (array $item): int => (int) ($item['element_id'] ?? 0), $result['items'])));
$elements = ContentElement::query()->with('editorialContentKind')->whereKey($ids)->get()->keyBy('id');
$videos = app(HeroVideo::class);
$result['items'] = array_values(array_filter($result['items'], function (array $item) use ($elements, $videos): bool {
$element = $elements->get((int) ($item['element_id'] ?? 0));
return $element !== null && $videos->isSelectable($element);
}));
}
// CMS: nur Bilder, die als Website-Bild wählbar sind (keine vertraulichen Arten, nicht archiviert).
if ($this->pickerPurpose === 'website-bild') {
$ids = array_values(array_filter(array_map(fn (array $item): int => (int) ($item['element_id'] ?? 0), $result['items'])));
+24 -5
View File
@@ -5,6 +5,7 @@
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Cms\Widgets\Support\HeroVideo;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Media\CompositionStill;
use App\Domain\Media\FilmStill;
@@ -37,6 +38,22 @@ public function openWebsiteImagePicker(string $pfad): void
$this->forceRenderForPicker();
}
/**
* Bild und Text: ein Film aus dem Medienmanager als Video wählen. Gleicher Wähler wie beim Bild, nur mit Filmen; das
* Ziel ist ausschließlich ein Videofeld (…video). Die Auswahl gibt nichts frei.
*/
public function openWebsiteVideoPicker(string $pfad): void
{
if (preg_match('/^(data|mountedActions\.\d+\.data)(\.[A-Za-z0-9_-]+)+\.video$/', $pfad) !== 1) {
return;
}
$this->resetPicker('website-video');
$this->pickerKind = 'film';
$this->bildZiel = $pfad;
$this->forceRenderForPicker();
}
/**
* Medien- und Materialkarte: das Vorschaubild des Films als Bild für die Website übernehmen. Es entsteht ein Bild
* im Medienmanager (einmal gespeichert), das im Bildfeld ausgewählt wird. Die Datei des Films bleibt geschützt.
@@ -197,8 +214,10 @@ public function confirmPicker(): void
$row = app(EditorialCatalog::class)->rowForTarget((string) $target, 0, allowDraft: true);
$element = isset($row['element_id']) ? ContentElement::query()->find((int) $row['element_id']) : null;
if (! $element instanceof ContentElement || ! WebsiteImage::isSelectable($element)) {
Notification::make()->danger()->title('Dieses Medium kann nicht als Website-Bild gewählt werden.')->send();
$video = $this->pickerPurpose === 'website-video';
if ($video ? ! ($element instanceof ContentElement && app(HeroVideo::class)->isSelectable($element)) : ! ($element instanceof ContentElement && WebsiteImage::isSelectable($element))) {
Notification::make()->danger()->title($video ? 'Dieser Film kann nicht als Video gewählt werden.' : 'Dieses Medium kann nicht als Website-Bild gewählt werden.')->send();
return;
}
@@ -212,17 +231,17 @@ public function confirmPicker(): void
*/
public function pickerKinds(): array
{
return ['bild' => 'Bilder'];
return $this->pickerPurpose === 'website-video' ? ['film' => 'Filme'] : ['bild' => 'Bilder'];
}
public function pickerTitle(): string
{
return 'Bild aus dem Medienmanager';
return $this->pickerPurpose === 'website-video' ? 'Video aus dem Medienmanager' : 'Bild aus dem Medienmanager';
}
public function pickerConfirmLabel(): string
{
return 'Bild übernehmen';
return $this->pickerPurpose === 'website-video' ? 'Video übernehmen' : 'Bild übernehmen';
}
/**
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\FormattedText;
use App\Filament\Support\TipTap\FontSizeExtension;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\RichContentPlugin;
use Filament\Forms\Components\RichEditor\RichEditorTool;
use Filament\Forms\Components\Select;
use Filament\Support\Enums\Width;
/**
* Schriftgröße für die Texte der Website: ein Werkzeug „Schriftgröße“ mit festen Stufen (kein freies Maß), dazu das
* PHP-Modell und die JS-Erweiterung der Auszeichnung. Nur über {@see RichField::make()} mit `website: true`.
*/
final class FontSizePlugin implements RichContentPlugin
{
private const SCRIPT = 'js/rich-font-size.js';
public function getTipTapPhpExtensions(): array
{
return [new FontSizeExtension];
}
public function getTipTapJsExtensions(): array
{
$file = public_path(self::SCRIPT);
// Die Prüfsumme in der Adresse lässt den Browser eine geänderte Fassung sofort laden.
return [asset(self::SCRIPT).(is_file($file) ? '?v='.substr((string) md5_file($file), 0, 10) : '')];
}
public function getEditorTools(): array
{
return [
RichEditorTool::make('fontSize')
->label('Schriftgröße')
->action(arguments: '{ size: $getEditor().getAttributes(\'fontSize\')[\'data-size\'] ?? null }')
->toggle()
->icon('fi-o-lead'),
];
}
public function getEditorActions(): array
{
return [
Action::make('fontSize')
->label('Schriftgröße')
->modalHeading('Schriftgröße')
->modalWidth(Width::Large)
->fillForm(fn (array $arguments): array => ['size' => array_key_exists((string) ($arguments['size'] ?? ''), FormattedText::SITE_SIZES) ? $arguments['size'] : 'normal'])
->schema([
Select::make('size')
->label('Größe')
->options(['normal' => 'Normal', ...FormattedText::SITE_SIZES])
->native(false)
->required()
->helperText('Gilt für den markierten Text. „Normal“ nimmt die Auszeichnung zurück.'),
])
->action(function (array $arguments, array $data, RichEditor $component): void {
$collapsed = ($arguments['editorSelection']['head'] ?? null) === ($arguments['editorSelection']['anchor'] ?? null);
$size = (string) ($data['size'] ?? 'normal');
$extend = $collapsed ? [EditorCommand::make('extendMarkRange', arguments: ['fontSize'])] : [];
$component->runCommands(
array_key_exists($size, FormattedText::SITE_SIZES)
? [...$extend, EditorCommand::make('setFontSize', arguments: [['size' => $size]])]
: [...$extend, EditorCommand::make('unsetFontSize')],
editorSelection: $arguments['editorSelection'],
);
}),
];
}
}
+159
View File
@@ -0,0 +1,159 @@
<?php
namespace App\Filament\Support;
use App\Domain\Cms\LinkTargets;
use App\Domain\Cms\Page;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\RichContentPlugin;
use Filament\Forms\Components\RichEditor\RichEditorTool;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
/**
* Werkzeug „Interne Seite oder Sprungmarke verlinken“ für die Texte der Website: wählt eine Seite der Website und auf
* Wunsch eine Sprungmarke und setzt daraus den Link am markierten Text. Es ergänzt das Werkzeug „Link“ (freie Adresse),
* ersetzt es nicht. Gleiche Ziele wie der Linkdialog der Felder ({@see ChoosesLinkTargets}); gespeichert wird nur mit dem
* Seitenentwurf, veröffentlicht wird nichts.
*/
final class InternalLinkPlugin implements RichContentPlugin
{
public function getTipTapPhpExtensions(): array
{
return [];
}
public function getTipTapJsExtensions(): array
{
return [];
}
public function getEditorTools(): array
{
return [
RichEditorTool::make('interneSeite')
->label('Interne Seite oder Sprungmarke verlinken')
->icon(Heroicon::DocumentText)
->action(),
];
}
public function getEditorActions(): array
{
return [
Action::make('interneSeite')
->label('Interne Seite oder Sprungmarke verlinken')
->modalHeading('Interne Seite oder Sprungmarke verlinken')
->modalDescription('Der markierte Text wird zum Link auf eine Seite dieser Website oder auf eine Sprungmarke. Eine freie Adresse setzt das Werkzeug „Link“.')
->modalWidth(Width::Large)
->modalSubmitActionLabel('Link setzen')
->schema([
Select::make('seite')
->label('Seite')
->options(fn ($livewire): array => self::pageOptions($livewire))
->searchable()
->required()
->live()
->afterStateUpdated(fn (callable $set) => $set('marke', null)),
Select::make('marke')
->label('Sprungmarke')
->placeholder('Seitenanfang (ohne Sprungmarke)')
->options(fn (Get $get, $livewire): array => self::anchorOptions($get('seite'), $livewire))
->required(fn (Get $get): bool => $get('seite') === 'diese')
->visible(fn (Get $get): bool => filled($get('seite')))
->helperText('Ausgeblendete Abschnitte sind gekennzeichnet; ein Link auf sie führt ins Leere.'),
])
->action(function (array $arguments, array $data, RichEditor $component): void {
$href = self::href((string) ($data['seite'] ?? ''), $data['marke'] ?? null, $component->getLivewire());
if ($href === null) {
return;
}
$collapsed = ($arguments['editorSelection']['head'] ?? null) === ($arguments['editorSelection']['anchor'] ?? null);
$component->runCommands([
...($collapsed ? [EditorCommand::make('extendMarkRange', arguments: ['link'])] : []),
EditorCommand::make('setLink', arguments: [['href' => $href, 'target' => null]]),
], editorSelection: $arguments['editorSelection']);
}),
];
}
/**
* @return array<string, string>
*/
private static function pageOptions(mixed $livewire): array
{
$options = [];
if (self::editsPage($livewire)) {
$options['diese'] = 'Diese Seite';
}
$own = is_object($livewire) && method_exists($livewire, 'linkOwnPage') ? $livewire->linkOwnPage() : null;
foreach (app(LinkTargets::class)->pages('', $own?->getKey()) as $page) {
$options[(string) $page['id']] = $page['titel'].' ('.$page['pfad'].')';
}
return $options;
}
/**
* @return array<string, string>
*/
private static function anchorOptions(mixed $seite, mixed $livewire): array
{
$anchors = self::anchorsOf((string) $seite, $livewire);
return collect($anchors)->mapWithKeys(fn (array $anchor): array => [
$anchor['anchor'] => $anchor['label'].' (#'.$anchor['anchor'].')'.($anchor['hidden'] ? ' – ausgeblendet' : ''),
])->all();
}
/**
* @return list<array{anchor: string, label: string, hidden: bool}>
*/
private static function anchorsOf(string $seite, mixed $livewire): array
{
$targets = app(LinkTargets::class);
if ($seite === 'diese') {
return self::editsPage($livewire) ? $targets->anchorsInEditor(SectionEditor::fromEditorState(is_array($livewire->data['sections'] ?? null) ? $livewire->data['sections'] : [])) : [];
}
$page = Page::query()->with(['latestRevision', 'publishedRevision'])->find((int) $seite);
return $page instanceof Page ? $targets->anchorsForPage($page) : [];
}
private static function editsPage(mixed $livewire): bool
{
return is_object($livewire) && method_exists($livewire, 'linkOwnAnchors');
}
private static function href(string $seite, mixed $anchor, mixed $livewire): ?string
{
$targets = app(LinkTargets::class);
$anchor = is_string($anchor) && $anchor !== '' ? $anchor : null;
if ($anchor !== null && ! in_array($anchor, array_column(self::anchorsOf($seite, $livewire), 'anchor'), true)) {
return null;
}
if ($seite === 'diese') {
$href = self::editsPage($livewire) ? $targets->href(null, $anchor) : null;
} else {
$page = Page::query()->find((int) $seite);
$href = $page instanceof Page ? $targets->href($page->path, $anchor) : null;
}
return SafeUrl::isSafe($href) ? $href : null;
}
}
+25 -1
View File
@@ -5,7 +5,9 @@
use App\Domain\Catalog\FormattedText;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\RichEditorTool;
use Filament\Forms\Components\RichEditor\TextColor;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Arr;
use Illuminate\Support\Js;
/**
@@ -14,23 +16,45 @@
*/
final class RichField
{
/** Farbwerte der Schriftfarben im Editor (Weiß/Cremefläche); auf der Seite bestimmt `widgets.css` je Fläche. */
private const SITE_COLOR_VALUES = ['marine' => '#032551', 'gruen' => '#3b7b09', 'rot' => '#a8212b', 'grau' => '#3e4c5c'];
/**
* @param ?string $label Bezeichnung des Felds; sie ist auch der Name für Hilfstechnik
* @param bool $live Arbeitsplätze gleichen beim Verlassen des Felds ab ({@see ManagesRichFields}); Dialoge nicht
* @param bool $hideLabel Die Bezeichnung zeigt der Arbeitsplatz selbst
* @param bool $images Bilder aus dem Medienbestand einfügen; nur auf Seiten mit dem gemeinsamen Picker
* ({@see ManagesEditorialSurface::openTextImagePicker()})
* @param bool $website Texte der Website (Fließtext): zusätzlich Schriftgröße, Schriftfarbe und Ausrichtung aus festen
* Werten ({@see FormattedText::SITE_SIZES}, {@see FormattedText::SITE_COLORS}); gespeichert wird
* mit dem Webprofil von {@see FormattedText}
*/
public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false, bool $images = false): RichEditor
public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false, bool $images = false, bool $website = false): RichEditor
{
$toolbar = FormattedText::TOOLBAR;
if ($website) {
// Interne Seite oder Sprungmarke verlinken, gleich neben dem freien Link.
$toolbar[0] = [...$toolbar[0], 'interneSeite'];
array_splice($toolbar, 1, 0, [['fontSize', 'textColor'], ['alignStart', 'alignCenter', 'alignEnd']]);
}
if ($images) {
array_splice($toolbar, count($toolbar) - 1, 0, [['bild']]);
}
$field = RichEditor::make($name)->toolbarButtons($toolbar);
if ($website) {
$field
->plugins([new FontSizePlugin, new InternalLinkPlugin])
->textColors(Arr::mapWithKeys(
FormattedText::SITE_COLORS,
fn (string $label, string $key): array => [$key => TextColor::make($label, self::SITE_COLOR_VALUES[$key])],
))
->customTextColors(false);
}
if ($images) {
$field->tools([
RichEditorTool::make('bild')
+93 -5
View File
@@ -11,6 +11,8 @@
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\ToggleButtons;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Group;
@@ -27,7 +29,7 @@
* Rasterverhältnis) → je Platz ein Widget (Builder mit höchstens einem Eintrag, Auswahl aus dem Widget-Register).
* Abschnittseinstellungen stehen im Abschnitt, Widget-Einstellungen im Widget-Dialog: eine Dialogebene.
*
* Formularzustand eines Abschnitts: {id, layout, style: {...}, slots: {uuid: {widget: {uuid: Builder-Eintrag}}}}.
* Formularzustand eines Abschnitts: {id, name, anchor, hidden, layout, style: {...}, slots: {uuid: {widget: {uuid: Builder-Eintrag}}}}.
*/
class SectionEditor
{
@@ -91,6 +93,7 @@ private static function sectionSchema(): array
{
return [
Hidden::make('id'),
self::labelSection(),
// Abschnittsgestaltung in drei Gruppen. Im Seiten-Arbeitsplatz nur im Kontext „Abschnitt gestalten“
// sichtbar und dort offen; beim Anlegen einer Seite an jedem Abschnitt, eingeklappt.
Section::make('Raster und Breite')
@@ -154,6 +157,68 @@ private static function sectionSchema(): array
];
}
/**
* Name, Sprungmarke und Sichtbarkeit: stehen im Seitenaufbau am Abschnitt, damit man sie beim Ordnen der Seite sieht.
*/
private static function labelSection(): Section
{
return Section::make('Name, Sprungmarke und Sichtbarkeit')
->columnSpanFull()
->compact()
->collapsible()
->collapsed(fn (Get $get): bool => blank($get('name')) && blank($get('anchor')) && ! $get('hidden'))
->extraAttributes(['class' => 'luf-abschnitt-bezeichnung'])
->schema([
TextInput::make('name')
->label('Name des Abschnitts')
->placeholder('Zum Beispiel „Kursübersicht“')
->maxLength(PageSections::MAX_NAME)
->live(onBlur: true)
->hintIcon('heroicon-m-information-circle', tooltip: 'Nur zur Orientierung im Seitenaufbau und in der Linkauswahl. Der Name erscheint nie auf der Website.')
->hintColor('gray'),
TextInput::make('anchor')
->label('Sprungmarke')
->prefix('#')
->placeholder('zum-beispiel-kurse')
->maxLength(PageSections::MAX_ANCHOR)
->live(onBlur: true)
->afterStateUpdated(function (?string $state, Set $set): void {
$set('anchor', filled($state) ? Str::slug($state, '-', 'de') : null);
})
->suffixAction(Action::make('anchorFromName')
->label('Sprungmarke aus dem Namen vorschlagen')
->icon('heroicon-o-sparkles')
->tooltip('Aus dem Namen vorschlagen')
->action(fn (Get $get, Set $set) => $set('anchor', Str::limit(Str::slug((string) $get('name'), '-', 'de'), PageSections::MAX_ANCHOR, ''))))
->hintIcon('heroicon-m-information-circle', tooltip: 'Macht den Abschnitt zum Ziel eines Links. Auf derselben Seite genügt „#marke“, von anderen Seiten und von außen „Adresse der Seite#marke“. Nur Kleinbuchstaben, Ziffern und Bindestriche; jede Marke einmal je Seite.')
->hintColor('gray')
->helperText(fn (Get $get, $livewire): ?string => self::anchorLinkText($get('anchor'), $livewire)),
Toggle::make('hidden')
->label('Auf der Website ausblenden')
->live()
->hintIcon('heroicon-m-information-circle', tooltip: 'Der Abschnitt bleibt im Entwurf erhalten, erscheint aber nicht auf der Website. Auch eine Sprungmarke dieses Abschnitts führt dann ins Leere. In der Seitenvorschau steht an seiner Stelle ein Hinweis.')
->hintColor('gray')
->columnSpanFull(),
])
->columns(['default' => 1, 'md' => 2]);
}
/**
* Vollständiger Link zur Sprungmarke (für Verweise von außen); eine neue Seite hat noch keine Adresse.
*/
private static function anchorLinkText(mixed $anchor, mixed $livewire): ?string
{
if (! is_string($anchor) || $anchor === '') {
return 'Ohne Sprungmarke ist der Abschnitt kein Linkziel.';
}
$path = is_object($livewire) && property_exists($livewire, 'record') && is_object($livewire->record ?? null) ? ($livewire->record->path ?? null) : null;
return is_string($path) && $path !== ''
? 'Link von anderen Seiten: '.($path === '/' ? '' : $path).'#'.$anchor.' · von außen: '.url($path === '/' ? '/' : $path).'#'.$anchor
: 'Link auf dieser Seite: #'.$anchor.'. Die Adresse für Verweise von außen steht nach dem ersten Speichern fest.';
}
private static function onWorkplace(mixed $livewire): bool
{
return is_object($livewire) && method_exists($livewire, 'openAbschnitt');
@@ -257,6 +322,9 @@ public static function toEditorState(array $sections): array
$state[] = [
'id' => $section['id'] ?? (string) Str::uuid(),
'name' => $section['name'] ?? null,
'anchor' => $section['anchor'] ?? null,
'hidden' => (bool) ($section['hidden'] ?? false),
'layout' => $section['layout'],
'style' => SectionStyle::fromStored($section['style'] ?? []),
'slots' => $slots,
@@ -289,6 +357,9 @@ public static function fromEditorState(?array $state): array
$sections[] = [
'id' => $section['id'] ?? null,
'name' => is_string($section['name'] ?? null) ? $section['name'] : null,
'anchor' => is_string($section['anchor'] ?? null) ? $section['anchor'] : null,
'hidden' => (bool) ($section['hidden'] ?? false),
'layout' => $section['layout'] ?? SectionLayouts::DEFAULT,
'style' => is_array($section['style'] ?? null) ? $section['style'] : [],
'slots' => $slots,
@@ -484,7 +555,12 @@ public static function insertCopyAfter(array $items, string $key, string $newKey
foreach ($items as $itemKey => $item) {
$result[$itemKey] = $item;
if ((string) $itemKey === $key) {
$result[$newKey] = $item;
// Eine Sprungmarke gibt es je Seite nur einmal: Die Kopie bekommt keine, der Name wird kenntlich gemacht.
$copy = is_array($item) ? $item : [];
$copy['anchor'] = null;
$name = is_string($copy['name'] ?? null) ? trim($copy['name']) : '';
$copy['name'] = $name !== '' ? Str::limit($name, PageSections::MAX_NAME - 9, '').' (Kopie)' : null;
$result[$newKey] = $copy;
}
}
@@ -562,13 +638,25 @@ private static function sectionLabel(array $state, ?int $index): HtmlString
$meta[] = 'noch leer';
}
$name = 'Abschnitt '.(($index ?? 0) + 1);
$number = 'Abschnitt '.(($index ?? 0) + 1);
$given = PageSections::cleanName($state['name'] ?? null);
$anchor = PageSections::cleanAnchor($state['anchor'] ?? null);
$hidden = (bool) ($state['hidden'] ?? false);
$full = 'Raster '.SectionLayouts::short($layout).' · '.SectionStyle::summary($style)
.($names === [] ? ' · noch leer' : ' · '.implode(', ', $names));
return new HtmlString('<span class="luf-abschnitt" title="'.e($full).'"><span class="luf-abschnitt-nr">'.e($name).'</span>'
// Der Name steht vorn; die Nummer bleibt als Orientierung daneben. Sprungmarke und „Ausgeblendet“ sind auch
// für Screenreader lesbar, die Nummer und die Rastermeta nicht doppelt.
$text = $given !== null ? $given : $number;
$badges = ($anchor !== null ? '<span class="luf-abschnitt-marke" title="Sprungmarke">#'.e($anchor).'</span>' : '')
.($hidden ? '<span class="luf-abschnitt-aus" title="Auf der Website ausgeblendet">Ausgeblendet</span>' : '');
$spoken = ($given !== null ? $number.': ' : '').($anchor !== null ? 'Sprungmarke '.$anchor.'. ' : '').($hidden ? 'Auf der Website ausgeblendet. ' : '').$full;
return new HtmlString('<span class="luf-abschnitt'.($hidden ? ' is-ausgeblendet' : '').'" title="'.e(($given !== null ? $number.' · ' : '').$full).'"><span class="luf-abschnitt-nr">'.e($text).'</span>'
.($given !== null ? '<span class="luf-abschnitt-nummer" aria-hidden="true">'.e($number).'</span>' : '')
.$badges
.'<span class="luf-abschnitt-meta" aria-hidden="true">'.e(implode(' · ', $meta)).'</span>'
.'<span class="vw-sr">: '.e($full).'</span></span>');
.'<span class="vw-sr">: '.e($spoken).'</span></span>');
}
/**
+323
View File
@@ -0,0 +1,323 @@
<?php
namespace App\Filament\Support;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
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\Toggle;
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\Utilities\Get;
use Illuminate\Support\Str;
/**
* Formular der Anfragevorlage: Aufbau (Schritte, Feldgruppen, Einzelfelder), Regeln und Texte. Alles sind Auswahlfelder
* und Listen; es gibt keine freie Eingabe von Ausdrücken oder JSON. Die Auswahllisten der Regeln (Ziele, Quellen, Werte)
* leiten sich aus dem gerade bearbeiteten Aufbau ab.
*/
final class TemplateEditor
{
/**
* @return list<Component>
*/
public static function schema(): array
{
return [
TextInput::make('name')->label('Bezeichnung der Vorlage')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->tabs([
Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure()),
Tab::make('Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()),
]),
];
}
/**
* @return list<Component>
*/
private static function structure(): array
{
return [
Select::make('draft.issues')->label('Unterstützte Anliegen')->multiple()->live()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Welche Anliegen diese Vorlage kennt. Leer: alle angebotenen. Ein Anfrage-Einstieg kann daraus weiter auswählen.'),
Repeater::make('draft.steps')
->label('Schritte')
->helperText('Jeder Schritt ist im mehrstufigen Dialog eine Seite. Im Kompaktformular stehen alle Schritte untereinander. Die Reihenfolge von oben nach unten ist die Reihenfolge der Fragen und zugleich die Reihenfolge, in der Bedingungen ausgewertet werden.')
->schema([
Hidden::make('key')->default(fn (): string => 's'.Str::lower(Str::random(6))),
TextInput::make('title')->label('Titel des Schritts')->required()->maxLength(120)->live(onBlur: true),
Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(600),
Repeater::make('items')
->label('Inhalt des Schritts')
->schema([
Select::make('kind')->label('Art')->required()->live()->options([
'issue' => 'Auswahl des Anliegens',
'group' => 'Feldgruppe',
'field' => 'Einzelnes Feld',
]),
Select::make('group')->label('Feldgruppe')->searchable()->live()
->options(fn (): array => InquiryFieldGroup::query()->offered()->orderBy('sort_order')->pluck('name', 'key')->all())
->visible(fn (Get $get): bool => $get('kind') === 'group')->required(fn (Get $get): bool => $get('kind') === 'group'),
Select::make('field')->label('Feld')->searchable()->live()
->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->pluck('name', 'key')->all())
->visible(fn (Get $get): bool => $get('kind') === 'field')->required(fn (Get $get): bool => $get('kind') === 'field'),
Toggle::make('required')->label('Pflichtfeld')
->visible(fn (Get $get): bool => $get('kind') === 'field'),
])
->reorderableWithButtons()
->addActionLabel('Baustein hinzufügen')
->itemLabel(fn (array $state): string => match ($state['kind'] ?? null) {
'issue' => 'Auswahl des Anliegens',
'group' => 'Feldgruppe: '.(InquiryFieldGroup::query()->where('key', $state['group'] ?? '')->value('name') ?? '…'),
'field' => 'Feld: '.(InquiryField::query()->where('key', $state['field'] ?? '')->value('name') ?? '…'),
default => 'Neuer Baustein',
}),
])
->reorderableWithButtons()
->collapsible()
->addActionLabel('Schritt hinzufügen')
->live()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Neuer Schritt'),
];
}
/**
* @return list<Component>
*/
private static function rules(): array
{
return [
Section::make()->schema([
Repeater::make('draft.rules')
->label('Regeln')
->helperText('Eine Regel verändert ein Feld, eine Feldgruppe oder einen Schritt abhängig von Auswahlen davor. Bedingungen können nur auf Felder verweisen, die im Aufbau vor dem Ziel stehen; so entstehen keine Zirkelbezüge.')
->schema([
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((array) ($livewire->data['draft'] ?? []), (string) $get('effect'))),
Select::make('value')->label('Vorbelegen mit')->live()
->options(fn ($livewire, Get $get): array => self::targetValues((array) ($livewire->data['draft'] ?? []), (string) $get('target')))
->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((array) ($livewire->data['draft'] ?? []))),
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((array) ($livewire->data['draft'] ?? []), (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'], (array) ($livewire->data['draft'] ?? [])) : '')),
]),
];
}
/**
* @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 und in den Anfrage-Einstiegen gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext. Ein Anfrage-Einstieg kann einzelne Texte überschreiben.')
->schema($fields),
];
}
/**
* Felder des Entwurfs in Reihenfolge: [Schlüssel => Name], dazu die Bausteine, aus denen sie stammen.
*
* @param array<string, mixed> $draft
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool}
*/
private static function inventory(array $draft): array
{
$steps = [];
$groups = [];
$fields = [];
$hasIssue = false;
$names = InquiryField::query()->pluck('name', 'key')->all();
$groupNames = InquiryFieldGroup::query()->get()->keyBy('key');
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$key = (string) ($step['key'] ?? '');
if ($key !== '') {
$steps[$key] = (string) (($step['title'] ?? '') ?: 'Schritt');
}
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$kind = $item['kind'] ?? null;
if ($kind === 'issue') {
$hasIssue = true;
} elseif ($kind === 'group' && isset($groupNames[$item['group'] ?? ''])) {
$group = $groupNames[$item['group']];
$groups[$group->key] = $group->name;
foreach ($group->itemList() as $row) {
$fields[$row['field']] = (string) ($names[$row['field']] ?? $row['field']);
}
} elseif ($kind === 'field' && filled($item['field'] ?? null)) {
$fields[$item['field']] = (string) ($names[$item['field']] ?? $item['field']);
}
}
}
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue];
}
/**
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
private static function targets(array $draft, string $effect): array
{
$inventory = self::inventory($draft);
$steps = [];
foreach ($inventory['steps'] as $key => $title) {
$steps["step:$key"] = 'Schritt: '.$title;
}
$groups = [];
foreach ($inventory['groups'] as $key => $name) {
$groups["group:$key"] = 'Feldgruppe: '.$name;
}
$fields = [];
foreach ($inventory['fields'] as $key => $name) {
$fields["field:$key"] = 'Feld: '.$name;
}
return match ($effect) {
'skip' => $steps,
'require', 'preset' => $fields,
'show', 'hide' => ['Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Schritte' => $steps, 'Feldgruppen' => $groups, 'Felder' => $fields],
};
}
/**
* @param array<string, mixed> $draft
*/
private static function targetName(string $target, array $draft = []): string
{
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
return match ($kind) {
'step' => (string) (self::inventory($draft)['steps'][$key] ?? $key),
'field' => (string) (InquiryField::query()->where('key', $key)->value('name') ?? $key),
'group' => (string) (InquiryFieldGroup::query()->where('key', $key)->value('name') ?? $key),
default => $key,
};
}
/**
* Felder, auf deren Wert sich eine Bedingung stützen darf.
*
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function sources(array $draft): array
{
$inventory = self::inventory($draft);
$sources = [];
if ($inventory['hasIssue']) {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
}
$catalog = InquiryField::query()->whereIn('key', array_keys($inventory['fields']))->get()->keyBy('key');
foreach ($inventory['fields'] as $key => $name) {
if (isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = $name;
}
}
return $sources;
}
/**
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function sourceValues(array $draft, string $source): array
{
if ($source === 'anliegen' || $source === 'unteranliegen') {
$only = array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'));
$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);
}
/**
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function targetValues(array $draft, string $target): array
{
return str_starts_with($target, 'field:') ? self::fieldValues(substr($target, 6)) : [];
}
/**
* @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,59 @@
<?php
namespace App\Filament\Support\TipTap;
use App\Domain\Catalog\FormattedText;
use Tiptap\Core\Mark;
/**
* Schriftgröße als Auszeichnung des Texts (`<span data-size="large">`), Gegenstück zu `public/js/rich-font-size.js`. Der
* Editor führt den Wert beim Speichern durch dieses PHP-Modell; eine Auszeichnung, die hier fehlt, ginge verloren.
* Welche Größen gelten, entscheidet {@see FormattedText::SITE_SIZES}.
*/
class FontSizeExtension extends Mark
{
/**
* @var string
*/
public static $name = 'fontSize';
/**
* @return array<int, array<string, mixed>>
*/
public function parseHTML(): array
{
return [
[
'tag' => 'span',
'getAttrs' => fn ($DOMNode): bool => $DOMNode->hasAttribute('data-size'),
],
];
}
/**
* @return array<string, array<mixed>>
*/
public function addAttributes(): array
{
return [
'data-size' => [
'parseHTML' => fn ($DOMNode) => $DOMNode->getAttribute('data-size') ?: null,
'renderHTML' => function ($attributes) {
$value = is_array($attributes) ? ($attributes['data-size'] ?? null) : ($attributes->{'data-size'} ?? null);
return ['data-size' => $value];
},
],
];
}
/**
* @param object $mark
* @param array<string, mixed> $HTMLAttributes
* @return array<mixed>
*/
public function renderHTML($mark, $HTMLAttributes = []): array
{
return ['span', $HTMLAttributes, 0];
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Communication\FormEvaluator;
use App\Domain\Communication\FormPayload;
use App\Domain\Communication\FormToken;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryService;
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);
}
/**
* @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');
}
}
+1 -3
View File
@@ -35,8 +35,6 @@ public function index(Request $request, ShopCatalog $catalog, PageController $pa
return $pages->showPage($page);
}
$term = trim((string) $request->query('suche', ''));
return view('shop.index', ['cards' => $catalog->cards($term), 'term' => $term]);
return view('shop.index', ['listing' => $catalog->listing($request->query())]);
}
}
+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);
+4
View File
@@ -8,7 +8,9 @@
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;
use App\Domain\Cms\Widgets\Types\ProseWidget;
use App\Domain\Cms\Widgets\Types\ShopProductsWidget;
@@ -26,6 +28,7 @@
HeroWidget::class,
HeadingWidget::class,
ProseWidget::class,
NoticeWidget::class,
ImageTextWidget::class,
CardsWidget::class,
FeaturesWidget::class,
@@ -36,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,
];
+4
View File
@@ -33,6 +33,10 @@
'marker_days' => 30,
/* Produkte je Seite in der Shopliste (Kacheln und Liste). */
'per_page' => 12,
/*
| Kauf auf Rechnung für Vereine und Organisationen (PAY-006): auf Anfrage, Rechnung manuell durch den Betreiber.
| Standardmäßig aus: Das Mitglied sieht die Möglichkeit erst, wenn der Prozess vollständig ist (Rechnungserstellung
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Ergänzend und abwärtskompatibel: Ein Menüeintrag mit Zielseite kann auf eine Sprungmarke dieser Seite zeigen.
* Ohne Wert (bisher alle Einträge) führt er zum Seitenanfang. Ältere Programmstände ignorieren die Spalte.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('navigation_items', function (Blueprint $table) {
$table->string('anchor', 60)->nullable();
});
}
public function down(): void
{
Schema::table('navigation_items', function (Blueprint $table) {
$table->dropColumn('anchor');
});
}
};
@@ -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');
}
};
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><title>Alltagsnah</title><path d="M32 22 Q33 15 39 15 Q40 5 49 7 Q57 8 57 17 Q64 20 60 30 Q57 36 50 34 M49 23 V53" stroke="#397D0D" stroke-width="3.2" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 32 L24 13 L44 32 M8 29 V53 H40 V29 M19 53 V38 H29 V53 M4 53 H59" stroke="#08264D" stroke-width="3.2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 473 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><title>Altersgerecht</title><g fill="none" stroke="#08264D" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 31 C11 38 16 42 21 42 C27 42 32 37 31 30 L30 27"/><circle cx="46" cy="32" r="9"/><path d="M37 28 C34 22 32 25 30 29 M55 28 C58 22 60 25 62 29"/><path d="M6 56 C6 48 12 43 20.5 43 C28 43 33 49 33 56 C33 49 38 43 46 43 C54 43 60 49 60 56"/><path d="M19 36 Q21 38 24 36 M43 36 Q46 38 49 36" stroke-width="1.5"/></g><g fill="none" stroke="#397D0D" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 30 C11 23 16 19 21 19 C26 19 30 23 31 27 M5 31 L31 27"/></g><g fill="none" stroke="#FFCD00" stroke-width="3.2" stroke-linecap="round"><path d="M27 13 L23 8 M32 11 V4 M38 13 L42 8"/></g></svg>

After

Width:  |  Height:  |  Size: 837 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><title>Ausgrenzung</title><circle cx="11" cy="23" r="5.5" stroke="#08264D" stroke-width="3.2" fill="none"/><circle cx="25" cy="23" r="5.5" stroke="#08264D" stroke-width="3.2" fill="none"/><path d="M3 49 V41 Q3 31 11 31 Q20 31 20 41 V49 M20 41 Q20 31 25 31 Q33 31 33 41 V49" stroke="#08264D" stroke-width="3.2" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M41 13 Q31 30 39 53" stroke="#08264D" stroke-width="3.2" fill="none" stroke-dasharray="4 5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="51" cy="33" r="5.5" stroke="#397D0D" stroke-width="3.2" fill="none"/><path d="M42 53 Q42 42 51 42 Q60 42 60 53" stroke="#397D0D" stroke-width="3.2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 828 B

Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff. Show more