Compare commits

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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 22:29:31 +01:00
36 changed files with 2617 additions and 176 deletions

No files matched your search

+257 -21
View File
@@ -3,19 +3,34 @@
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Validation\Rule;
/**
* Kontakt-Widget: 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.
* Kontakt-Widget (ADR-60, ADR-61). Der Redakteur legt fest, welche Anfragegründe auf der Seite angeboten werden und
* welches veröffentlichte Formular jeder Grund öffnet; Formularführung (Langformular oder mehrstufig) und Darstellung
* (im Abschnitt oder als Dialog) sind zwei getrennte Einstellungen. Der Besucher wählt einen Grund und erhält genau das
* zugehörige Formular. Felder, Bedingungen, Texte und Empfänger gibt es im CMS nicht: Sie werden im Formular-Editor der
* Kommunikationsverwaltung gepflegt und gelten sofort auf allen Seiten.
*
* Seiten aus der ersten Fassung (ein Anfrage-Einstieg unter refs.entry) werden weiter dargestellt.
*/
class InquiryWidget extends WidgetType
{
public const MAX_REASONS = 8;
public function key(): string
{
return 'inquiry';
@@ -28,7 +43,7 @@ public function label(): string
public function description(): string
{
return 'Bindet einen Anfrage-Einstieg aus der Kommunikationsverwaltung ein: Kontaktformular oder mehrstufiger Anfragedialog.';
return 'Kontaktformular mit Auswahl des Anfragegrundes: Der Besucher wählt, worum es geht, und erhält genau das passende Formular.';
}
public function icon(): string
@@ -48,35 +63,122 @@ public function preferredUnits(): int
public function narrowBehavior(): string
{
return 'Das Formular nutzt die Breite des Platzes; Felder stehen untereinander, der mehrstufige Dialog bleibt einspaltig.';
return 'Das Formular nutzt die Breite des Platzes; Felder stehen untereinander, Karten der Grundauswahl stapeln, der Dialog füllt auf dem Smartphone den Bildschirm.';
}
public function stages(): array
{
return ['fluid' => 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art stehen auf breiten Plätzen nebeneinander'];
return ['fluid' => 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art und Karten stehen bei viel Platz nebeneinander'];
}
public function schematic(): array
{
return [[6, 4, 24, 3, 'ink'], [6, 10, 48, 5, 'line'], [6, 18, 48, 5, 'line'], [6, 26, 18, 5, 'accent']];
return [[6, 4, 24, 3, 'ink'], [6, 10, 22, 6, 'line'], [32, 10, 22, 6, 'line'], [6, 20, 48, 5, 'line'], [6, 28, 18, 5, 'accent']];
}
/**
* Formularführung und Präsentation sind unabhängig: Jede Kombination ist zulässig.
*
* @return array<string, array<string, string>>
*/
public function settings(): array
{
return [
'mode' => ['compact' => 'Langes Formular', 'wizard' => 'Mehrstufiger Dialog'],
'open' => ['inline' => 'Im Abschnitt', 'modal' => 'Als Dialog über der Seite'],
'picker' => ['cards' => 'Karten', 'select' => 'Auswahlfeld'],
'width' => ['normal' => 'Standard', 'narrow' => 'Schmal', 'wide' => 'Breit'],
'spacing' => ['normal' => 'Standard', 'compact' => 'Kompakt', 'airy' => 'Großzügig'],
'columns' => ['auto' => 'Automatisch', 'one' => 'Immer eine Spalte'],
'button' => ['solid' => 'Gefüllt', 'outline' => 'Umrandet'],
];
}
public function settingLabels(): array
{
return [
'mode' => ['Formularführung', 'Langes Formular: alle Bereiche stehen auf einer Seite, bedingte Felder erscheinen je nach Eingabe. Mehrstufiger Dialog: die Bereiche werden Schritt für Schritt mit Fortschrittsanzeige durchlaufen. Vorgabe: Langes Formular.'],
'open' => ['Präsentation', 'Im Abschnitt: das Formular steht direkt auf der Seite. Als Dialog: ein Button öffnet das Formular über der Seite; auf dem Smartphone füllt er den Bildschirm. Vorgabe: Im Abschnitt.'],
'picker' => ['Auswahl des Anfragegrundes', 'Karten zeigen die Gründe mit Beschreibung nebeneinander, das Auswahlfeld braucht wenig Platz. Bei nur einem Grund entfällt die Auswahl. Vorgabe: Karten.'],
'width' => ['Breite des Formulars', 'Vorgabe: Standard. Das Formular nutzt höchstens die Breite des Platzes.'],
'spacing' => ['Abstände', 'Abstand zwischen den Feldern. Vorgabe: Standard.'],
'columns' => ['Anordnung der Felder', 'Automatisch: Felder gleicher Art (zum Beispiel Vor- und Nachname) stehen bei viel Platz nebeneinander. Vorgabe: Automatisch.'],
'button' => ['Buttondarstellung', 'Gilt für den Button, der den Dialog öffnet, und für „Weiter“ und „Absenden“. Vorgabe: Gefüllt.'],
];
}
public function settingGroups(): array
{
return [
'Formularführung und Präsentation' => ['mode', 'open'],
'Gestaltung' => ['picker', 'width', 'spacing', 'columns', 'button'],
];
}
public function dataRules(): array
{
return [];
return [
// Nur die Existenz: Eine später zurückgezogene Vorlage darf eine Seite nicht unspeicherbar machen. Öffentlich
// erscheint ein Grund nur, solange sein Formular veröffentlicht ist (resolve()).
'reasons' => ['nullable', 'array', 'max:'.self::MAX_REASONS],
'reasons.*.key' => ['nullable', 'string', 'max:60'],
'reasons.*.label' => ['required', 'string', 'max:80'],
'reasons.*.description' => ['nullable', 'string', 'max:200'],
'reasons.*.template' => ['required', 'integer', Rule::exists('inquiry_templates', 'id')],
'reasons.*.issue' => ['nullable', 'string', 'max:60'],
'reasons.*.subissue' => ['nullable', 'string', 'max:60'],
'question' => ['nullable', 'string', 'max:160'],
'open_label' => ['nullable', 'string', 'max:60'],
];
}
public function dataFields(): array
{
return [];
return [
Repeater::make('reasons')
->label('Anfragegründe')
->helperText('Diese Gründe bietet die Seite an. Wählt der Besucher einen Grund, erscheint genau das zugeordnete Formular. Bei nur einem Grund entfällt die Auswahl. Ein Button kann einen Grund vorwählen: Adresse der Seite mit „?grund=Kennung“ (die Kennung steht unter dem Grund).')
->schema([
Hidden::make('key'),
TextInput::make('label')->label('Bezeichnung für Besucher')->required()->maxLength(80)->placeholder('Zum Beispiel: Kurse & Workshops'),
Textarea::make('description')->label('Kurzbeschreibung (optional)')->rows(2)->maxLength(200)->helperText('Erscheint auf der Karte unter der Bezeichnung.'),
Select::make('template')->label('Formular')->required()->searchable()->live()
->options(fn (): array => self::templateOptions())
->afterStateUpdated(function (Set $set): void {
$set('issue', null);
$set('subissue', null);
})
->helperText('Nur veröffentlichte Formulare stehen zur Auswahl. Inhalt, Felder und Bedingungen pflegst du unter „Kommunikation → Formulare & Befragungen“.'),
Select::make('issue')->label('Anliegen im Formular vorwählen (optional)')->live()
->options(fn (Get $get): array => self::issueOptions((int) $get('template')))
->placeholder('Keines: das Formular fragt selbst')
->visible(fn (Get $get): bool => self::issueOptions((int) $get('template')) !== [])
->afterStateUpdated(fn (Set $set) => $set('subissue', null))
->helperText('Mehrere Gründe können dasselbe Formular nutzen und sich im Anliegen unterscheiden. Die Frage nach dem Anliegen entfällt dann.'),
Select::make('subissue')->label('Unteranliegen vorwählen (optional)')
->options(fn (Get $get): array => self::subissueOptions((int) $get('template'), (string) $get('issue')))
->placeholder('Keines')
->visible(fn (Get $get): bool => filled($get('issue')) && self::subissueOptions((int) $get('template'), (string) $get('issue')) !== []),
Text::make(fn (Get $get): string => filled($get('key')) ? 'Kennung für Links: grund='.$get('key') : 'Die Kennung für Links entsteht beim Speichern.'),
])
->minItems(1)
->maxItems(self::MAX_REASONS)
->reorderableWithButtons()
->collapsible()
->addActionLabel('Anfragegrund hinzufügen')
->itemLabel(fn (array $state): ?string => $state['label'] ?? null),
TextInput::make('question')->label('Frage zur Auswahl des Grundes')->maxLength(160)->placeholder('Worum geht es?')
->helperText('Steht über der Auswahl, wenn mehr als ein Grund angeboten wird. Leer: „Worum geht es?“.'),
TextInput::make('open_label')->label('Beschriftung des Buttons (nur Dialog)')->maxLength(60)->placeholder('Anfrage stellen')
->helperText('Erscheint nur bei der Präsentation „Als Dialog über der Seite“.'),
];
}
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')],
// Nur die Existenz (Seiten der ersten Fassung): Ein später zurückgezogener Einstieg darf eine Seite nicht unspeicherbar machen.
'entry' => ['nullable', 'integer', Rule::exists('inquiry_entries', 'id')],
];
}
@@ -84,33 +186,167 @@ public function refFields(): array
{
return [
Select::make('entry')
->label('Anfrage-Einstieg')
->required()
->label('Bisheriger Anfrage-Einstieg')
->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.'),
->options(fn (): array => InquiryEntry::query()->orderBy('name')->pluck('name', 'id')->all())
->visible(fn (Get $get): bool => filled($get('entry')))
->helperText('Diese Seite nutzt noch einen Anfrage-Einstieg der ersten Fassung. Er wird nur angezeigt, solange oben kein Anfragegrund eingetragen ist. Neue Seiten brauchen keinen Einstieg.'),
];
}
public function editorSchema(): array
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
return parent::editorSchema();
$reasons = [];
$taken = [];
foreach (array_values((array) ($data['reasons'] ?? [])) as $reason) {
$reason = is_array($reason) ? $reason : [];
$key = Keys::valid($reason['key'] ?? null) && ! in_array($reason['key'], $taken, true) ? $reason['key'] : Keys::from((string) ($reason['label'] ?? ''), $taken);
$taken[] = $key;
$reasons[] = [
'key' => $key,
'label' => trim((string) ($reason['label'] ?? '')),
'description' => filled($reason['description'] ?? null) ? trim((string) $reason['description']) : null,
'template' => (int) ($reason['template'] ?? 0),
'issue' => filled($reason['issue'] ?? null) ? (string) $reason['issue'] : null,
'subissue' => filled($reason['issue'] ?? null) && filled($reason['subissue'] ?? null) ? (string) $reason['subissue'] : null,
];
}
$data['reasons'] = $reasons;
if ($reasons === [] && ! filled($refs['entry'] ?? null)) {
$errors->add('data.reasons', 'Mindestens ein Anfragegrund ist nötig.');
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array'));
if ($reasons === []) {
$id = $widget['refs']['entry'] ?? null;
$entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null;
return ['entry' => $entry, 'entryLive' => $entry?->isLive() ?? false];
return ['legacy' => true, 'entry' => $entry, 'entryLive' => $entry?->isLive() ?? false, 'config' => null, 'unavailable' => []];
}
$templates = InquiryTemplate::query()->with('publishedVersion')->whereIn('id', array_unique(array_map(fn (array $r): int => (int) ($r['template'] ?? 0), $reasons)))->get()->keyBy('id');
$settings = (array) ($widget['settings'] ?? []);
$mode = ($settings['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact';
$live = [];
$unavailable = [];
foreach ($reasons as $reason) {
$template = $templates[(int) ($reason['template'] ?? 0)] ?? null;
$label = (string) ($reason['label'] ?? '');
if ($template === null || $template->archived_at !== null || $template->publishedVersion === null) {
$unavailable[] = $label;
continue;
}
$query = array_filter([
'anliegen' => $reason['issue'] ?? null,
'unteranliegen' => $reason['subissue'] ?? null,
'modus' => $mode,
], fn (mixed $value): bool => filled($value));
$suffix = '?'.http_build_query($query);
$live[] = [
'key' => (string) ($reason['key'] ?? ''),
'label' => $label,
'description' => $reason['description'] ?? null,
'definitionUrl' => route('inquiry.form.definition', $template).$suffix,
'stateUrl' => route('inquiry.form.state', $template).$suffix,
'submitUrl' => route('inquiry.form.submit', $template).$suffix,
];
}
$config = $live === [] ? null : [
'open' => ($settings['open'] ?? 'inline') === 'modal' ? 'modal' : 'inline',
'picker' => ($settings['picker'] ?? 'cards') === 'select' ? 'select' : 'cards',
'question' => filled($widget['data']['question'] ?? null) ? (string) $widget['data']['question'] : 'Worum geht es?',
'openLabel' => filled($widget['data']['open_label'] ?? null) ? (string) $widget['data']['open_label'] : 'Anfrage stellen',
'preview' => $context->preview,
'reasons' => $live,
];
return ['legacy' => false, 'entry' => null, 'entryLive' => false, 'config' => $config, 'unavailable' => $unavailable];
}
public function summary(array $widget): string
{
$reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array'));
if ($reasons === []) {
$id = $widget['refs']['entry'] ?? null;
$name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null;
return $name !== null ? 'Anfrage: '.$name : 'Kein Anfrage-Einstieg gewählt';
return $name !== null ? 'Anfrage: '.$name : 'Kein Anfragegrund gewählt';
}
$labels = array_map(fn (array $reason): string => (string) ($reason['label'] ?? ''), $reasons);
$mode = ($widget['settings']['mode'] ?? 'compact') === 'wizard' ? 'mehrstufig' : 'langes Formular';
$open = ($widget['settings']['open'] ?? 'inline') === 'modal' ? 'Dialog' : 'im Abschnitt';
return 'Anfrage: '.implode(', ', $labels).' ('.$mode.', '.$open.')';
}
/**
* @return array<int, string>
*/
private static function templateOptions(): array
{
return InquiryTemplate::query()->whereNotNull('published_version_id')->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all();
}
/**
* @return array<string, string>
*/
private static function issueOptions(int $templateId): array
{
$options = [];
foreach ((array) (self::definition($templateId)['issues'] ?? []) as $issue) {
$options[(string) $issue['key']] = (string) $issue['label'];
}
return $options;
}
/**
* @return array<string, string>
*/
private static function subissueOptions(int $templateId, string $issue): array
{
$options = [];
foreach ((array) (self::definition($templateId)['issues'] ?? []) as $top) {
if ($top['key'] !== $issue) {
continue;
}
foreach ((array) $top['children'] as $child) {
$options[(string) $child['key']] = (string) $child['label'];
}
}
return $options;
}
/**
* @return array<string, mixed>
*/
private static function definition(int $templateId): array
{
if ($templateId <= 0) {
return [];
}
return (array) (InquiryTemplate::query()->with('publishedVersion')->find($templateId)?->publishedVersion?->definition ?? []);
}
}
+501
View File
@@ -0,0 +1,501 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Übersetzung zwischen dem Entwurf einer Vorlage (Schritte mit Feldgruppen und Einzelfeldern, Regeln; ADR-60) und der
* flachen Bearbeitungsansicht des Formular-Editors (ADR-61): Bereiche mit Feldern und Teilbereichen, Bedingungen direkt am
* Element. Die Engine bleibt unverändert; der Editor schreibt Felder und Teilbereiche in denselben Katalog, aus dem die
* Vorlage sie liest, und erzeugt aus den Bedingungen am Element dieselben Regeln wie die Regelliste.
*
* Ansicht (Builder-Format der Verwaltung):
* areas[] {key, title, intro, cond, items[]}
* items[] {type: field|section|end|issue, data: {...}} (end: Ende eines Teilbereichs; danach folgen Einzelfelder)
* cond {effect, match, conditions[{source, op, values[]}], pos} (leer: keine Bedingung)
* rules[] Regeln, die sich nicht an ein Element heften lassen (zusätzliche Regeln desselben Ziels, Vorbelegungen)
*
* Ein Teilbereich ist eine Überschrift im Fluss: Die Felder bis zum nächsten Teilbereich gehören zu ihm (Feldgruppe).
* Neue Elemente tragen eine vorläufige Kennung (tmp_…), die beim Speichern durch eine feste ersetzt wird.
*/
final class FormEditor
{
/** Wirkungen, die ein Element selbst trägt, je Art des Ziels. */
public const EFFECTS = [
'step' => ['show', 'hide', 'skip'],
'group' => ['show', 'hide'],
'field' => ['show', 'hide', 'require'],
];
/**
* @param array<string, mixed> $draft
* @param ?int $exceptTemplate die bearbeitete Vorlage: Sie zählt nicht als „auch verwendet in“
* @return array{issues: list<string>, areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function expand(array $draft, ?int $exceptTemplate = null): array
{
$fields = InquiryField::query()->get()->keyBy('key');
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = $this->usage($exceptTemplate);
$byTarget = [];
$rules = array_values(array_filter((array) ($draft['rules'] ?? []), 'is_array'));
foreach ($rules as $index => $rule) {
$byTarget[(string) ($rule['target'] ?? '')][] = $index;
}
$consumed = [];
$take = function (string $target, string $kind) use (&$byTarget, &$consumed, $rules): array {
foreach ($byTarget[$target] ?? [] as $index) {
if (isset($consumed[$index]) || ! in_array($rules[$index]['effect'] ?? null, self::EFFECTS[$kind], true)) {
continue;
}
$consumed[$index] = true;
return $this->cond($rules[$index], $index);
}
return [];
};
$areas = [];
$issueDone = false;
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$step = is_array($step) ? $step : [];
$key = (string) ($step['key'] ?? '');
$items = [];
$list = array_values((array) ($step['items'] ?? []));
foreach ($list as $position => $item) {
$item = is_array($item) ? $item : [];
$kind = (string) ($item['kind'] ?? '');
if ($kind === 'issue') {
$items[] = ['type' => 'issue', 'data' => ['issues' => $issueDone ? [] : array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'))]];
$issueDone = true;
} elseif ($kind === 'group') {
$groupKey = (string) ($item['group'] ?? '');
$group = $groups[$groupKey] ?? null;
$items[] = ['type' => 'section', 'data' => [
'key' => $groupKey,
'label' => $group === null ? 'Nicht mehr verfügbare Feldgruppe' : ($group->label ?: $group->name),
'description' => $group?->description,
'missing' => $group === null,
'used_in' => implode(', ', $usage['groups'][$groupKey] ?? []),
'cond' => $take('group:'.$groupKey, 'group'),
]];
foreach ($group?->itemList() ?? [] as $row) {
$field = $fields[$row['field']] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, $row['required'], $usage, $take)];
}
}
// Ein Einzelfeld direkt nach einer Feldgruppe gehört nicht zu ihr: Das Ende des Teilbereichs ist ausdrücklich.
if (($list[$position + 1]['kind'] ?? null) === 'field') {
$items[] = ['type' => 'end', 'data' => []];
}
} elseif ($kind === 'field') {
$field = $fields[(string) ($item['field'] ?? '')] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, (bool) ($item['required'] ?? false), $usage, $take)];
}
}
}
$areas[] = [
'key' => $key,
'title' => (string) ($step['title'] ?? ''),
'intro' => $step['intro'] ?? null,
'cond' => $take('step:'.$key, 'step'),
'items' => $items,
];
}
$rest = [];
foreach ($rules as $index => $rule) {
if (! isset($consumed[$index])) {
$rest[] = $this->cond($rule, $index) + ['target' => (string) ($rule['target'] ?? ''), 'value' => $rule['value'] ?? null];
}
}
return [
'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')),
'areas' => $areas,
'rules' => $rest,
];
}
/**
* Speichert die Ansicht: legt neue Felder und Teilbereiche im Katalog an, aktualisiert bearbeitete und liefert den
* Entwurf (ohne Texte, die der Editor getrennt führt).
*
* @param array<string, mixed> $editor
* @return array{issues: list<string>, steps: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function persist(array $editor): array
{
return DB::transaction(function () use ($editor): array {
$takenFields = InquiryField::query()->pluck('key')->all();
$takenGroups = InquiryFieldGroup::query()->pluck('key')->all();
$existingFields = InquiryField::query()->get()->keyBy('key');
$existingGroups = InquiryFieldGroup::query()->get()->keyBy('key');
$map = [];
$issues = [];
$steps = [];
$rules = [];
$order = 0;
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$stepKey = Keys::valid($area['key'] ?? null) || preg_match('/^s[a-z0-9]{3,12}$/', (string) ($area['key'] ?? '')) === 1 ? (string) $area['key'] : 's'.Str::lower(Str::random(6));
$items = [];
$group = null;
$flush = function () use (&$group, &$items): void {
if ($group !== null) {
$items[] = $group;
$group = null;
}
};
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$block = is_array($block) ? $block : [];
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
switch ((string) ($block['type'] ?? '')) {
case 'issue':
$flush();
$items[] = ['kind' => 'issue'];
if ($issues === []) {
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
}
break;
case 'end':
$flush();
break;
case 'section':
$flush();
$original = (string) ($data['key'] ?? '');
$isMissing = (bool) ($data['missing'] ?? false);
$current = isset($existingGroups[$original]) ? $existingGroups[$original] : null;
$key = $current?->key ?? Keys::from((string) ($data['label'] ?? ''), $takenGroups);
$takenGroups[] = $key;
$map[$original] = $key;
$group = ['kind' => 'group', 'group' => $key, '_label' => trim((string) ($data['label'] ?? '')), '_description' => $data['description'] ?? null, '_rows' => [], '_current' => $current, '_missing' => $isMissing, '_new' => $current === null];
$this->rule($rules, 'group:'.$key, (array) ($data['cond'] ?? []), 'group', $order);
break;
case 'field':
$field = $this->saveField($data, $existingFields, $takenFields);
$original = (string) ($data['key'] ?? '');
$map[$original] = $field->key;
$required = (bool) ($data['required'] ?? false);
if ($group !== null) {
$group['_rows'][] = ['field' => $field->key, 'required' => $required];
} else {
$items[] = ['kind' => 'field', 'field' => $field->key, 'required' => $required];
}
$this->rule($rules, 'field:'.$field->key, (array) ($data['cond'] ?? []), 'field', $order);
break;
}
}
$flush();
$this->rule($rules, 'step:'.$stepKey, (array) ($area['cond'] ?? []), 'step', $order);
foreach ($items as $index => $item) {
if (($item['kind'] ?? null) !== 'group') {
continue;
}
$items[$index] = $this->saveGroup($item, $existingGroups, $takenGroups);
}
$steps[] = [
'key' => $stepKey,
'title' => mb_substr(trim((string) ($area['title'] ?? '')), 0, 120),
'intro' => filled($area['intro'] ?? null) ? mb_substr(trim((string) $area['intro']), 0, 600) : null,
'items' => $items,
];
}
foreach (array_values((array) ($editor['rules'] ?? [])) as $rule) {
$rule = is_array($rule) ? $rule : [];
$target = (string) ($rule['target'] ?? '');
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$rules[] = [
'effect' => (string) ($rule['effect'] ?? ''),
'target' => $kind === '' ? $target : $kind.':'.($map[$key] ?? $key),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $this->conditions((array) ($rule['conditions'] ?? []), $map),
'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null,
'_pos' => is_numeric($rule['pos'] ?? null) ? (int) $rule['pos'] : 1000 + $order++,
];
}
foreach ($rules as $index => $rule) {
$rules[$index]['conditions'] = $this->conditions((array) $rule['conditions'], $map);
}
usort($rules, fn (array $a, array $b): int => $a['_pos'] <=> $b['_pos']);
return [
'issues' => $issues,
'steps' => $steps,
'rules' => array_map(function (array $rule): array {
unset($rule['_pos']);
return $rule;
}, $rules),
];
});
}
/**
* Eine neue Zeile in der Karteikarte der Bedingungen (leer: Standardwerte).
*
* @return array<string, mixed>
*/
public static function newCondition(): array
{
return ['source' => null, 'op' => 'eq', 'values' => []];
}
/** Vorläufige Kennung eines neuen Feldes oder Teilbereichs. */
public static function temporaryKey(): string
{
return 'tmp_'.Str::lower(Str::random(8));
}
/**
* Verwendung von Feldern und Feldgruppen in Vorlagen: [Art => [Kennung => [Vorlagennamen]]]. Zeigt im Editor, wo
* eine Änderung noch wirkt (bei der nächsten Veröffentlichung dieser Vorlagen).
*
* @return array{fields: array<string, list<string>>, groups: array<string, list<string>>}
*/
public function usage(?int $exceptTemplate = null): array
{
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = ['fields' => [], 'groups' => []];
foreach (InquiryTemplate::query()->whereNull('archived_at')->when($exceptTemplate !== null, fn ($query) => $query->whereKeyNot($exceptTemplate))->get() as $template) {
foreach ((array) ($template->draft['steps'] ?? []) as $step) {
foreach ((array) ($step['items'] ?? []) as $item) {
if (($item['kind'] ?? null) === 'field') {
$usage['fields'][(string) ($item['field'] ?? '')][$template->id] = $template->name;
} elseif (($item['kind'] ?? null) === 'group') {
$key = (string) ($item['group'] ?? '');
$usage['groups'][$key][$template->id] = $template->name;
foreach ($groups[$key]?->itemList() ?? [] as $row) {
$usage['fields'][$row['field']][$template->id] = $template->name;
}
}
}
}
}
return $usage;
}
/**
* @param array<string, mixed> $rule
* @return array<string, mixed>
*/
private function cond(array $rule, int $pos): array
{
return [
'effect' => (string) ($rule['effect'] ?? ''),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => array_values(array_map(fn (mixed $condition): array => [
'source' => (string) ($condition['source'] ?? ''),
'op' => (string) ($condition['op'] ?? 'eq'),
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
], array_filter((array) ($rule['conditions'] ?? []), 'is_array'))),
'pos' => $pos,
];
}
/**
* @param array{fields: array<string, list<string>>, groups: array<string, list<string>>} $usage
* @return array<string, mixed>
*/
private function fieldData(InquiryField $field, bool $required, array $usage, callable $take): array
{
return [
'key' => $field->key,
'label' => $field->label,
'name' => $field->name,
'help' => $field->help,
'type' => $field->type->value,
'options' => $field->optionList(),
'required' => $required,
'purpose' => $field->purpose?->value,
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
'cond' => $take('field:'.$field->key, 'field'),
];
}
/**
* @param list<array<string, mixed>> $rules
* @param array<string, mixed> $cond
*/
private function rule(array &$rules, string $target, array $cond, string $kind, int &$order): void
{
$effect = (string) ($cond['effect'] ?? '');
$conditions = array_values(array_filter((array) ($cond['conditions'] ?? []), fn (mixed $c): bool => is_array($c) && filled($c['source'] ?? null)));
if ($effect === '' || ! in_array($effect, self::EFFECTS[$kind], true) || $conditions === []) {
return;
}
$rules[] = [
'effect' => $effect,
'target' => $target,
'match' => ($cond['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $conditions,
'value' => null,
'_pos' => is_numeric($cond['pos'] ?? null) ? (int) $cond['pos'] : 1000 + $order++,
];
}
/**
* @param array<int|string, mixed> $conditions
* @param array<string, string> $map
* @return list<array{source: string, op: string, values: list<string>}>
*/
private function conditions(array $conditions, array $map): array
{
$result = [];
foreach (array_values($conditions) as $condition) {
$condition = is_array($condition) ? $condition : [];
$source = (string) ($condition['source'] ?? '');
if ($source === '') {
continue;
}
$result[] = [
'source' => $map[$source] ?? $source,
'op' => in_array($condition['op'] ?? 'eq', array_keys(TemplateCompiler::OPERATORS), true) ? (string) ($condition['op'] ?? 'eq') : 'eq',
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
];
}
return $result;
}
/**
* @param array<string, mixed> $data
* @param Collection<string, InquiryField> $existing
* @param list<string> $taken
*/
private function saveField(array $data, $existing, array &$taken): InquiryField
{
$key = (string) ($data['key'] ?? '');
$label = mb_substr(trim((string) ($data['label'] ?? '')), 0, 200);
$help = filled($data['help'] ?? null) ? mb_substr(trim((string) $data['help']), 0, 600) : null;
$type = FieldType::tryFrom((string) ($data['type'] ?? '')) ?? FieldType::Text;
$purpose = FieldPurpose::tryFrom((string) ($data['purpose'] ?? ''));
$field = $existing[$key] ?? null;
if ($field !== null) {
$type = $field->type;
}
if ($purpose !== null && ! in_array($type, $purpose->types(), true)) {
$purpose = null;
}
$options = $type->hasOptions() ? Keys::withKeys(array_values((array) ($data['options'] ?? []))) : null;
if ($field === null) {
$final = Keys::from($label, $taken);
$taken[] = $final;
return InquiryField::query()->create([
'key' => $final,
'name' => mb_substr($label, 0, 120),
'label' => $label,
'help' => $help,
'type' => $type->value,
'options' => $options,
'settings' => null,
'purpose' => $purpose?->value,
'active' => true,
]);
}
$field->fill(['label' => $label, 'help' => $help, 'options' => $options ?? $field->options, 'purpose' => $purpose?->value]);
if ($field->isDirty()) {
$field->save();
}
return $field;
}
/**
* @param array<string, mixed> $group Teilbereich mit gesammelten Feldern (_rows)
* @param Collection<string, InquiryFieldGroup> $existing
* @param list<string> $taken
* @return array{kind: string, group: string}
*/
private function saveGroup(array $group, $existing, array &$taken): array
{
$item = ['kind' => 'group', 'group' => $group['group']];
if ($group['_missing']) {
return $item;
}
$label = mb_substr($group['_label'], 0, 200);
$description = filled($group['_description']) ? mb_substr(trim((string) $group['_description']), 0, 600) : null;
$current = $group['_current'];
if ($current === null) {
InquiryFieldGroup::query()->create([
'key' => $group['group'],
'name' => mb_substr($label, 0, 120),
'label' => $label,
'description' => $description,
'items' => $group['_rows'],
'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10,
'active' => true,
]);
return $item;
}
// Die Bezeichnung bleibt, wenn der Teilbereich vorher keine eigene öffentliche Überschrift hatte und unverändert ist.
$keepLabel = blank($current->label) && $label === $current->name;
$current->fill(['label' => $keepLabel ? null : $label, 'description' => $description, 'items' => $group['_rows']]);
if ($current->isDirty()) {
$current->save();
}
return $item;
}
}
+3 -1
View File
@@ -28,7 +28,9 @@ public function evaluate(array $form, array $values): array
}
foreach ((array) $form['steps'] as $step) {
$stepVisible = ! $this->any($byTarget['step:'.$step['key']] ?? [], 'skip', $context);
// Ein Bereich lässt sich wie eine Gruppe anzeigen oder ausblenden; „überspringen“ bleibt für ältere Vorlagen gültig.
$stepRules = $byTarget['step:'.$step['key']] ?? [];
$stepVisible = ! $this->any($stepRules, 'skip', $context) && $this->visible($stepRules, $context);
$state['steps'][$step['key']] = $stepVisible;
foreach ($step['items'] as $item) {
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Domain\Communication;
/**
* Der Anfragegrund, mit dem das Widget „Anfrage“ ein veröffentlichtes Formular lädt (ADR-61): ein vorgewähltes Anliegen,
* optional ein Unteranliegen, und die Formularführung. Das ist eine Darstellungs- und Vorauswahlentscheidung, keine
* Berechtigung: Alles, was ein Anfragegrund wählen kann, bietet das veröffentlichte Formular ohnehin an. Aus dem Grund
* entsteht dieselbe Konfiguration wie bei einem Anfrage-Einstieg, damit Auslieferung, Auswertung und Annahme nur eine
* Auslegung haben (FormFactory::effective).
*/
final class FormReason
{
/**
* Bereinigt die Angaben aus der Adresse oder der Anfrage des Browsers: nur bekannte Schlüssel, nur gültige Kennungen.
*
* @param array<string, mixed> $input
* @return array{anliegen: ?string, unteranliegen: ?string, modus: ?string}
*/
public static function clean(array $input): array
{
$key = fn (mixed $value): ?string => Keys::valid($value) ? $value : null;
$mode = $input['modus'] ?? null;
return [
'anliegen' => $key($input['anliegen'] ?? null),
'unteranliegen' => $key($input['unteranliegen'] ?? null),
'modus' => $mode === 'wizard' || $mode === 'compact' ? $mode : null,
];
}
/**
* Die Konfiguration, die FormFactory::effective erwartet. Ein Anliegen, das die Fassung nicht kennt, schränkt
* nichts ein (das Formular fragt dann wie gewohnt).
*
* @param array<string, mixed> $definition aufgelöste Fassung
* @param array<string, mixed> $reason
* @return array<string, mixed>
*/
public static function config(array $definition, array $reason): array
{
$config = ['mode' => ($reason['modus'] ?? null) === 'wizard' ? 'wizard' : 'compact', 'open' => 'inline'];
$issue = $reason['anliegen'] ?? null;
foreach ((array) ($definition['issues'] ?? []) as $top) {
if ($top['key'] !== $issue) {
continue;
}
$config['allowed_issues'] = [$issue];
$config['defaults'] = ['anliegen' => $issue];
$sub = $reason['unteranliegen'] ?? null;
if ($sub !== null && in_array($sub, array_column((array) $top['children'], 'key'), true)) {
$config['allowed_subissues'] = [$sub];
$config['defaults']['unteranliegen'] = $sub;
}
}
return $config;
}
}
+8 -3
View File
@@ -16,9 +16,14 @@
*/
final class FormToken
{
public static function issue(int $entryId, int $versionId): string
/**
* @param string $kind 'entry' (Anfrage-Einstieg) oder 'form' (veröffentlichte Vorlage, vom Widget „Anfrage“ gewählt);
* $entryId ist dann die Kennung des Einstiegs beziehungsweise der Vorlage
*/
public static function issue(int $entryId, int $versionId, string $kind = 'entry'): string
{
return Crypt::encryptString(json_encode([
'k' => $kind === 'form' ? 'form' : 'entry',
'e' => $entryId,
'v' => $versionId,
't' => now()->getTimestamp(),
@@ -27,7 +32,7 @@ public static function issue(int $entryId, int $versionId): string
}
/**
* @return array{e: int, v: int, t: int, n: string}|null
* @return array{k: string, e: int, v: int, t: int, n: string}|null
*/
public static function read(mixed $token): ?array
{
@@ -45,6 +50,6 @@ public static function read(mixed $token): ?array
return null;
}
return ['e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']];
return ['k' => ($data['k'] ?? 'entry') === 'form' ? 'form' : 'entry', 'e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']];
}
}
+14
View File
@@ -44,6 +44,20 @@ public function issueTitle(): string
return trim(implode(' › ', array_filter([$this->issue_label, $this->subissue_label])));
}
/**
* Woher die Anfrage kam: der Anfrage-Einstieg (älterer Weg) oder das Formular, das das Widget „Anfrage“ eingebunden hat.
*/
public function channelTitle(): string
{
if ($this->entry !== null) {
return $this->entry->name;
}
$template = $this->templateVersion?->template;
return $template !== null ? 'Formular „'.$template->name.'“' : 'Formular gelöscht';
}
public function contactTitle(): string
{
return $this->contact_name ?: ($this->contact_email ?: 'Unbekannt');
+55 -3
View File
@@ -50,10 +50,62 @@ public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array
* @throws SubmissionException
*/
public function submit(InquiryEntry $entry, array $payload): array
{
return $this->accept('entry', $entry->id, $entry->id, fn (?int $version): ?array => $this->deliver($entry, $version), $payload);
}
/**
* Die Fassung und das wirksame Formular einer veröffentlichten Vorlage für einen Besucher, wie sie das Widget
* „Anfrage“ ausliefert. $reason legt den Anfragegrund fest: ein vorgewähltes Anliegen (und Unteranliegen) und die
* Formularführung. Null, wenn die Vorlage nicht veröffentlicht oder archiviert ist.
*
* @param array{anliegen?: ?string, unteranliegen?: ?string, modus?: ?string} $reason
* @return array{form: array<string, mixed>, version: InquiryTemplateVersion}|null
*/
public function deliverForm(InquiryTemplate $template, array $reason = [], ?int $versionId = null): ?array
{
$template->loadMissing('publishedVersion');
if ($template->archived_at !== null || $template->publishedVersion === null) {
return null;
}
$version = $template->publishedVersion;
if ($versionId !== null && $versionId !== $version->id) {
$version = InquiryTemplateVersion::query()->where('template_id', $template->id)->find($versionId) ?? $version;
}
return ['form' => $this->factory->effective($version->definition, FormReason::config($version->definition, $reason)), 'version' => $version];
}
/**
* Nimmt eine Anfrage für eine veröffentlichte Vorlage an (Widget „Anfrage“). Die Verarbeitung ist dieselbe wie über
* einen Einstieg; die Anfrage trägt dann keine Einstiegskennung, sondern verweist über ihre Fassung auf die Vorlage.
*
* @param array{anliegen?: ?string, unteranliegen?: ?string, modus?: ?string} $reason
* @param array<string, mixed> $payload
* @return array{reference: string, created: bool}
*
* @throws SubmissionException
*/
public function submitForm(InquiryTemplate $template, array $reason, array $payload): array
{
return $this->accept('form', $template->id, null, fn (?int $version): ?array => $this->deliverForm($template, $reason, $version), $payload);
}
/**
* @param callable(?int): (array{form: array<string, mixed>, version: InquiryTemplateVersion}|null) $deliver
* @param array<string, mixed> $payload
* @return array{reference: string, created: bool}
*
* @throws SubmissionException
*/
private function accept(string $kind, int $targetId, ?int $entryId, callable $deliver, array $payload): array
{
$token = FormToken::read($payload['token'] ?? null);
if ($token === null || $token['e'] !== $entry->id) {
if ($token === null || $token['k'] !== $kind || $token['e'] !== $targetId) {
throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419);
}
@@ -69,7 +121,7 @@ public function submit(InquiryEntry $entry, array $payload): array
return ['reference' => $existing->reference, 'created' => false];
}
$delivered = $this->deliver($entry, $token['v']);
$delivered = $deliver($token['v']);
if ($delivered === null) {
throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410);
@@ -101,7 +153,7 @@ public function submit(InquiryEntry $entry, array $payload): array
try {
$inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([
'reference' => $this->reference(),
'entry_id' => $entry->id,
'entry_id' => $entryId,
'template_version_id' => $delivered['version']->id,
'submission_token' => hash('sha256', $token['n']),
'issue_key' => $result['issue']['key'] ?? null,
@@ -295,7 +295,7 @@ private function rules(array $rules, array $fields, array $tree, bool $hasIssue,
}
$kindOk = match ($effect) {
'show', 'hide' => in_array($targetKind, ['group', 'field'], true),
'show', 'hide' => in_array($targetKind, ['step', 'group', 'field'], true),
'require', 'preset' => $targetKind === 'field',
'skip' => $targetKind === 'step',
default => false,
@@ -5,6 +5,10 @@
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\ExampleConfiguration;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use App\Mail\CommunicationTestMail;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
@@ -31,7 +35,7 @@ class KommunikationEinstellungen extends Page
protected static ?string $navigationLabel = 'Einstellungen';
protected static ?int $navigationSort = 7;
protected static ?int $navigationSort = 3;
protected static ?string $slug = 'kommunikation/einstellungen';
@@ -84,6 +88,17 @@ public function form(Schema $schema): Schema
}
}),
]),
Section::make('Weitere Bausteine')->description('Anliegen und der gemeinsame Feldkatalog gehören zu den Formularen. Im Formular-Editor müssen sie nicht geöffnet werden; hier lassen sie sich einsehen und ordnen.')
->visible(fn (): bool => CommunicationAccess::configure())
->collapsed()
->schema([
Actions::make([
Action::make('issues')->label('Anliegen')->url(InquiryIssueResource::getUrl('index'))->color('gray'),
Action::make('fields')->label('Feldkatalog')->url(InquiryFieldResource::getUrl('index'))->color('gray'),
Action::make('groups')->label('Feldgruppen')->url(InquiryFieldGroupResource::getUrl('index'))->color('gray'),
Action::make('entries')->label('Anfrage-Einstiege (ältere Seiten)')->url(InquiryEntryResource::getUrl('index'))->color('gray'),
]),
]),
Section::make('Aufbewahrung')->schema([
TextInput::make('retention_months')->label('Anfragen löschen nach … Monaten')->numeric()->minValue(1)->maxValue(120)
->helperText('Leer: Anfragen werden nicht automatisch gelöscht. Der Befehl „php artisan communication:purge“ löscht Anfragen, die älter sind. Einzelne Anfragen lassen sich jederzeit im Posteingang löschen. Die Dauer ist mit dem Datenschutzkonzept abzustimmen.'),
@@ -43,6 +43,12 @@ class InquiryEntryResource extends CommunicationResource
protected static ?int $navigationSort = 6;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -43,6 +43,12 @@ class InquiryFieldResource extends CommunicationResource
protected static ?int $navigationSort = 3;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
/**
* @return list<Component>
*/
@@ -36,6 +36,12 @@ class InquiryFieldGroupResource extends CommunicationResource
protected static ?int $navigationSort = 4;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -98,7 +98,7 @@ public static function infolist(Schema $schema): Schema
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('channel')->label('Eingegangen über')->state(fn (Inquiry $record): string => $record->channelTitle()),
TextEntry::make('source_path')->label('Quellseite')->placeholder('Unbekannt'),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i'),
TextEntry::make('reference')->label('Kennzeichen')->copyable(),
@@ -58,7 +58,7 @@ public function bestand(): array
protected function catalogRows(): array
{
$query = Inquiry::query()->with('entry');
$query = Inquiry::query()->with(['entry', 'templateVersion.template']);
if ($this->anliegen !== 'alle') {
$query->where('issue_key', $this->anliegen);
@@ -79,7 +79,7 @@ protected function catalogRows(): array
$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'),
'meta' => $inquiry->created_at->format('d.m.Y H:i').' · '.($inquiry->issueTitle() ?: 'Ohne Anliegen').' · '.$inquiry->channelTitle(),
'text' => Str::limit((string) $inquiry->message, 180),
'suchtext' => implode(' ', array_filter([$inquiry->contact_email, $inquiry->reference, $inquiry->contact_phone])),
'symbol' => 'modul',
@@ -34,6 +34,12 @@ class InquiryIssueResource extends CommunicationResource
protected static ?int $navigationSort = 2;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -13,24 +13,24 @@
use Filament\Tables\Table;
/**
* Anfragevorlagen: ein vollständiger fachlicher Anfrageprozess. Der Entwurf ist frei bearbeitbar; wirksam wird nur eine
* Formulare & Befragungen (Anfragevorlagen): ein vollständiger fachlicher Anfrageprozess, bearbeitet im Formular-Editor (ADR-61). Der Entwurf ist frei bearbeitbar; wirksam wird nur eine
* bewusst veröffentlichte, unveränderliche Fassung.
*/
class InquiryTemplateResource extends CommunicationResource
{
protected static ?string $model = InquiryTemplate::class;
protected static ?string $navigationLabel = 'Anfragevorlagen';
protected static ?string $navigationLabel = 'Formulare & Befragungen';
protected static ?string $modelLabel = 'Anfragevorlage';
protected static ?string $modelLabel = 'Formular';
protected static ?string $pluralModelLabel = 'Anfragevorlagen';
protected static ?string $pluralModelLabel = 'Formulare & Befragungen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/vorlagen';
protected static ?int $navigationSort = 5;
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
@@ -2,6 +2,7 @@
namespace App\Filament\Resources\Communication\Templates\Pages;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use App\Domain\Communication\TemplateCompiler;
@@ -38,7 +39,7 @@ public function getSubheading(): string|Htmlable|null
}
if (! $template->isPublished()) {
return 'Noch nicht veröffentlicht. Besucher sehen diese Vorlage erst nach „Veröffentlichen“.';
return 'Noch nicht veröffentlicht. Besucher sehen dieses Formular erst nach „Veröffentlichen“.';
}
$version = $template->publishedVersion;
@@ -76,7 +77,7 @@ protected function getHeaderActions(): array
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->modalHeading('Neue Fassung veröffentlichen')
->modalHeading('Formular veröffentlichen')
->modalSubmitActionLabel('Jetzt veröffentlichen')
->modalWidth('2xl')
->schema(fn (): array => [
@@ -89,7 +90,7 @@ protected function getHeaderActions(): array
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();
Notification::make()->title('Das Formular lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send();
return;
}
@@ -107,17 +108,17 @@ 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.';
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
$names = array_map(fn (array $row): string => $row['entry']->name.($row['entry']->published_config !== null ? ' (veröffentlicht)' : ' (Entwurf)'), $rows);
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. 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.';
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist, und für diese Anfrage-Einstiege (ältere Seiten): '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
protected function archiveNote(): string
{
return 'Die Vorlage wird archiviert. Anfrage-Einstiege, die sie verwenden, liefern dann kein Formular mehr aus. Eingegangene Anfragen bleiben unverändert.';
return 'Das Formular wird archiviert. Seiten, die es einbinden, bieten es dann nicht mehr an (auch Anfrage-Einstiege liefern nichts mehr aus). Eingegangene Anfragen bleiben unverändert.';
}
protected function archiveAttributes(): array
@@ -134,16 +135,38 @@ 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;
return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit diesem Formular. Bitte zuerst zurückziehen oder auf ein anderes Formular umstellen." : null;
}
protected function mutateFormDataBeforeFill(array $data): array
{
$data['editor'] = app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey());
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$data['draft'] = TemplateDraft::clean((array) ($data['draft'] ?? []));
// Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf.
$saved = app(FormEditor::class)->persist((array) ($data['editor'] ?? []));
unset($data['editor']);
$data['draft'] = TemplateDraft::clean([
'texts' => (array) ($data['draft']['texts'] ?? []),
'issues' => $saved['issues'],
'steps' => $saved['steps'],
'rules' => $saved['rules'],
]);
return $data;
}
protected function afterSave(): void
{
// Neue Felder und Teilbereiche tragen jetzt ihre festen Kennungen. Ohne neues Laden würde ein zweites Speichern sie doppelt anlegen.
$this->fillForm();
}
protected function getRedirectUrl(): ?string
{
return null;
@@ -22,19 +22,19 @@ class ListInquiryTemplates extends ListRecords
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.';
return 'Hier entstehen Formulare und Befragungen: Bereiche mit Feldern, Bedingungen und Texte, alles in einem Editor. Änderungen sind zunächst ein Entwurf und gelten erst nach „Veröffentlichen“. Im Widget „Anfrage“ einer Seite wählst du, welches Formular zu welchem Anfragegrund gehört.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Vorlage anlegen')
->modalHeading('Neue Anfragevorlage')
->modalDescription('Der Aufbau entsteht danach auf der Seite der Vorlage.')
->modalSubmitActionLabel('Vorlage anlegen')
->label('Formular anlegen')
->modalHeading('Neues Formular')
->modalDescription('Der Aufbau entsteht danach im Editor des Formulars.')
->modalSubmitActionLabel('Formular anlegen')
->schema([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120),
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400),
])
->action(function (array $data): void {
@@ -48,7 +48,7 @@ protected function getHeaderActions(): array
'draft' => $draft,
]);
Notification::make()->title('Die Vorlage ist angelegt.')->success()->send();
Notification::make()->title('Das Formular ist angelegt.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template]));
}),
];
@@ -68,7 +68,7 @@ protected function catalogRows(): array
$rows[] = [
'schluessel' => 't'.$template->id,
'titel' => $template->name,
'meta' => 'Anfragevorlage · '.$steps.' '.($steps === 1 ? 'Schritt' : 'Schritte').' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege'),
'meta' => 'Formular · '.$steps.' '.($steps === 1 ? 'Bereich' : 'Bereiche').($template->entries_count > 0 ? ' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege').' (ältere Seiten)' : ''),
'text' => (string) ($template->description ?? ''),
'symbol' => 'modul',
'url' => $url,
@@ -104,11 +104,11 @@ protected function suchPlatzhalter(): string
protected function einheit(): array
{
return ['Anfragevorlage', 'Anfragevorlagen'];
return ['Formular', 'Formulare'];
}
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.'];
return ['titel' => 'Noch keine Formulare', 'text' => 'Mit „Formular anlegen“ oben entsteht das erste Formular. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
@@ -33,6 +33,9 @@ public function table(Table $table): Table
$template = $this->getOwnerRecord();
return $table
->heading('Fassungen')
->emptyStateHeading('Noch keine Fassung veröffentlicht')
->emptyStateDescription('Mit „Veröffentlichen“ entsteht die erste Fassung.')
->columns([
TextColumn::make('version')->label('Fassung')->prefix('Nr. '),
TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i'),
+261 -106
View File
@@ -2,12 +2,15 @@
namespace App\Filament\Support;
use App\Domain\Communication\FieldPurpose;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\FormEditor;
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\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
@@ -18,28 +21,38 @@
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
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.
* Formular-Editor (ADR-61): ein Formular wird an einer Stelle bearbeitet. Es besteht aus Bereichen (im mehrstufigen Dialog
* je ein Schritt), darin Felder und Teilbereiche, Bedingungen direkt am Element. Felder werden hier angelegt und
* geändert; sie landen im selben Katalog wie bisher (FormEditor). Die Regelliste bleibt für alles, was sich nicht an ein
* Element heften lässt. Alles sind Auswahlfelder und Listen; es gibt keine freie Eingabe von Ausdrücken oder JSON.
*/
final class TemplateEditor
{
private const EFFECT_LABELS = [
'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'],
'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'],
'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'],
];
/**
* @return list<Component>
*/
public static function schema(): array
{
return [
TextInput::make('name')->label('Bezeichnung der Vorlage')->required()->maxLength(120),
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120)
->helperText('So heißt das Formular in der Verwaltung und in der Auswahl des Widgets „Anfrage“.'),
Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->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()),
Tab::make('Weitere Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
]),
];
}
@@ -50,50 +63,170 @@ public static function schema(): array
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.')
Text::make('Ein Formular besteht aus Bereichen. Im mehrstufigen Dialog ist jeder Bereich ein Schritt, im langen Formular stehen alle Bereiche untereinander. In einem Bereich legst du Felder an; ein Teilbereich fasst Felder unter einer Überschrift zusammen. Bedingungen stehen direkt am Feld oder Bereich. Neue Felder und Auswahlwerte stehen in Bedingungen zur Verfügung, sobald das Formular einmal gespeichert ist.'),
Repeater::make('editor.areas')
->label('Bereiche')
->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),
TextInput::make('title')->label('Titel des Bereichs')->required()->maxLength(120)->live(onBlur: true)
->helperText('Im mehrstufigen Dialog die Überschrift des Schritts.'),
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'),
])
self::condition('step'),
Builder::make('items')
->label('Inhalt des Bereichs')
->blocks(self::blocks())
->addActionLabel('Feld oder Teilbereich hinzufügen')
->blockPickerColumns(2)
->blockNumbers(false)
->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',
}),
->collapsible()
->live(),
])
->reorderableWithButtons()
->collapsible()
->addActionLabel('Schritt hinzufügen')
->addActionLabel('Bereich hinzufügen')
->live()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Neuer Schritt'),
->itemLabel(fn (array $state): string => (($state['title'] ?? '') ?: 'Neuer Bereich').(filled($state['cond']['effect'] ?? null) ? ' · mit Bedingung' : '')),
];
}
/**
* @return list<Block>
*/
private static function blocks(): array
{
return [
Block::make('field')
->label(fn (?array $state): string => $state === null ? 'Feld' : 'Feld: '.(($state['label'] ?? '') ?: 'neu').self::fieldBadges($state))
->icon('heroicon-o-pencil-square')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('name'),
Hidden::make('used_in'),
Select::make('pick')->label('Vorhandenes Feld verwenden (optional)')->searchable()->live()->dehydrated(false)
->options(fn ($livewire): array => self::catalogFields((array) ($livewire->data['editor'] ?? [])))
->placeholder('Neues Feld anlegen')
->visible(fn (Get $get): bool => str_starts_with((string) $get('key'), 'tmp_'))
->afterStateUpdated(function ($state, Set $set): void {
$field = filled($state) ? InquiryField::query()->where('key', $state)->first() : null;
if ($field === null) {
return;
}
$set('key', $field->key);
$set('name', $field->name);
$set('label', $field->label);
$set('help', $field->help);
$set('type', $field->type->value);
$set('options', $field->optionList());
$set('purpose', $field->purpose?->value);
$set('pick', null);
})
->helperText('Felder wie „E-Mail-Adresse“ lassen sich in mehreren Formularen verwenden.'),
TextInput::make('label')->label('Frage oder Beschriftung im Formular')->required()->maxLength(200)->live(onBlur: true),
Select::make('type')->label('Art der Antwort')->required()->live()->dehydrated()
->options(FieldType::options())
->disabled(fn (Get $get): bool => ! str_starts_with((string) $get('key'), 'tmp_'))
->helperText('Nach dem Speichern nicht mehr änderbar, weil Bedingungen und bisherige Anfragen darauf aufbauen. Soll sich die Art ändern, lege ein neues Feld an.'),
Repeater::make('options')->label('Auswahlwerte')
->schema([Hidden::make('key'), TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120)])
->reorderableWithButtons()
->addActionLabel('Auswahlwert hinzufügen')
->minItems(1)
->itemLabel(fn (array $state): ?string => $state['label'] ?? null)
->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false)
->helperText('Jeder Wert behält seine feste interne Kennung; eine Umbenennung beschädigt keine Anfragen.'),
Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600)->helperText('Steht unter der Frage.'),
Toggle::make('required')->label('Pflichtfeld'),
Section::make('Weitere Einstellungen')->compact()->collapsed()->schema([
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 zeigt. Jedes Formular braucht ein Feld „E-Mail-Adresse für Rückfragen“.'),
]),
Text::make(fn (Get $get): string => 'Dieses Feld wird auch in diesen Formularen verwendet: '.$get('used_in').'. Eine Änderung gilt dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('field'),
]),
Block::make('section')
->label(fn (?array $state): string => $state === null ? 'Teilbereich' : 'Teilbereich: '.(($state['label'] ?? '') ?: 'neu').(filled($state['cond']['effect'] ?? null) ? ' (Bedingung)' : ''))
->icon('heroicon-o-rectangle-group')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('missing')->default(false),
Hidden::make('used_in'),
TextInput::make('label')->label('Überschrift des Teilbereichs')->required()->maxLength(200)->live(onBlur: true)
->helperText('Die Felder darunter stehen im Formular unter dieser Überschrift, bis ein weiterer Teilbereich oder „Ende des Teilbereichs“ folgt.'),
Textarea::make('description')->label('Erläuterung (optional)')->rows(2)->maxLength(600),
Text::make(fn (Get $get): string => 'Dieser Teilbereich wird auch in diesen Formularen verwendet: '.$get('used_in').'. Änderungen an seinen Feldern gelten dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('group'),
]),
Block::make('end')
->label('Ende des Teilbereichs')
->icon('heroicon-o-arrow-uturn-down')
->schema([Text::make('Die folgenden Felder stehen wieder ohne Teilbereich.')]),
Block::make('issue')
->label('Frage nach dem Anliegen')
->icon('heroicon-o-chat-bubble-left-right')
->maxItems(1)
->schema([
Select::make('issues')->label('Angebotene Anliegen')->multiple()->live()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Welche Anliegen dieses Formular kennt. Leer: alle angebotenen. Ein Anfragegrund im Widget kann daraus eines vorwählen; die Frage entfällt dann. Anliegen und Unteranliegen pflegst du unter „Einstellungen → Anliegen“.'),
]),
];
}
/**
* Bedingung am Element: Wirkung, Verknüpfung und eine Liste von Vergleichen. Ohne Wirkung gibt es keine Bedingung.
*/
private static function condition(string $kind): Section
{
return Section::make('Bedingung (optional)')->statePath('cond')->compact()->collapsed()->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->options(self::EFFECT_LABELS[$kind])->placeholder('Keine Bedingung')->live()
->helperText($kind === 'step' ? 'Zum Beispiel: Bereich „Angaben zur Schule“ nur anzeigen, wenn das Anliegen „Kursanfrage“ ist.' : null),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')
->visible(fn (Get $get): bool => filled($get('effect'))),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn (Select $component, $livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), $component->getStatePath())),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn (Get $get, $livewire): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (string) $get('source'))),
])
->addActionLabel('Bedingung hinzufügen')
->visible(fn (Get $get): bool => filled($get('effect')))
->helperText('Zur Auswahl stehen Felder, die im Formular weiter oben stehen.'),
]);
}
/**
* @param array<string, mixed>|null $state
*/
private static function fieldBadges(?array $state): string
{
$parts = [];
if (filled($state['type'] ?? null)) {
$parts[] = FieldType::tryFrom((string) $state['type'])?->label();
}
if ($state['required'] ?? false) {
$parts[] = 'Pflicht';
}
if (filled($state['cond']['effect'] ?? null)) {
$parts[] = 'Bedingung';
}
$parts = array_filter($parts);
return $parts === [] ? '' : ' ('.implode(', ', $parts).')';
}
/**
* @return list<Component>
*/
@@ -101,32 +234,33 @@ 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.')
Text::make('Hier stehen Regeln, die sich nicht an ein einzelnes Feld oder einen Bereich heften lassen: weitere Regeln für dasselbe Ziel und Vorbelegungen. Bedingungen für ein Feld oder einen Bereich legst du direkt am Element an. Eine Bedingung darf nur auf Felder verweisen, die im Formular weiter oben stehen.'),
Repeater::make('editor.rules')
->label('Weitere Regeln')
->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS),
Select::make('target')->label('Ziel')->required()->live()->searchable()
->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['draft'] ?? []), (string) $get('effect'))),
->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['editor'] ?? []), (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')))
->options(fn (Get $get): array => str_starts_with((string) $get('target'), 'field:') ? self::fieldValues(substr((string) $get('target'), 6)) : [])
->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')->required(),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn ($livewire): array => self::sources((array) ($livewire->data['draft'] ?? []))),
->options(fn ($livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), null)),
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'))),
->options(fn ($livewire, Get $get): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (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'] ?? [])) : '')),
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], (array) ($livewire->data['editor'] ?? [])) : '')),
]),
];
}
@@ -148,68 +282,77 @@ private static function texts(): array
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.')
->description('Alle Texte des Formulars werden hier gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext.')
->schema($fields),
];
}
/**
* Felder des Entwurfs in Reihenfolge: [Schlüssel => Name], dazu die Bausteine, aus denen sie stammen.
* Felder des Katalogs, die im Formular noch nicht vorkommen.
*
* @param array<string, mixed> $draft
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool}
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function inventory(array $draft): array
private static function catalogFields(array $editor): array
{
$used = array_keys(self::inventory($editor)['fields']);
return InquiryField::query()->offered()->whereNotIn('key', $used)->orderBy('name')->pluck('name', 'key')->all();
}
/**
* Inhalt des Formulars in Reihenfolge: Bereiche, Teilbereiche, Felder, und ob die Frage nach dem Anliegen vorkommt.
*
* @param array<string, mixed> $editor
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool, issues: list<string>}
*/
private static function inventory(array $editor): array
{
$steps = [];
$groups = [];
$fields = [];
$hasIssue = false;
$names = InquiryField::query()->pluck('name', 'key')->all();
$groupNames = InquiryFieldGroup::query()->get()->keyBy('key');
$issues = [];
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$key = (string) ($step['key'] ?? '');
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$key = (string) ($area['key'] ?? '');
if ($key !== '') {
$steps[$key] = (string) (($step['title'] ?? '') ?: 'Schritt');
$steps[$key] = (string) (($area['title'] ?? '') ?: 'Bereich');
}
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$kind = $item['kind'] ?? null;
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$data = (array) ($block['data'] ?? []);
$type = $block['type'] ?? null;
if ($kind === 'issue') {
if ($type === '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']);
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
} elseif ($type === 'section' && filled($data['key'] ?? null)) {
$groups[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Teilbereich');
} elseif ($type === 'field' && filled($data['key'] ?? null)) {
$fields[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Feld');
}
}
}
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue];
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue, 'issues' => $issues];
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, mixed>
*/
private static function targets(array $draft, string $effect): array
private static function targets(array $editor, string $effect): array
{
$inventory = self::inventory($draft);
$inventory = self::inventory($editor);
$steps = [];
foreach ($inventory['steps'] as $key => $title) {
$steps["step:$key"] = 'Schritt: '.$title;
$steps["step:$key"] = 'Bereich: '.$title;
}
$groups = [];
foreach ($inventory['groups'] as $key => $name) {
$groups["group:$key"] = 'Feldgruppe: '.$name;
$groups["group:$key"] = 'Teilbereich: '.$name;
}
$fields = [];
foreach ($inventory['fields'] as $key => $name) {
@@ -219,47 +362,68 @@ private static function targets(array $draft, string $effect): array
return match ($effect) {
'skip' => $steps,
'require', 'preset' => $fields,
'show', 'hide' => ['Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Schritte' => $steps, 'Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Bereiche' => $steps, 'Teilbereiche' => $groups, 'Felder' => $fields],
};
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
*/
private static function targetName(string $target, array $draft = []): string
private static function targetName(string $target, array $editor = []): string
{
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$inventory = self::inventory($editor);
return match ($kind) {
'step' => (string) (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),
'step' => (string) ($inventory['steps'][$key] ?? $key),
'field' => (string) ($inventory['fields'][$key] ?? InquiryField::query()->where('key', $key)->value('name') ?? $key),
'group' => (string) ($inventory['groups'][$key] ?? $key),
default => $key,
};
}
/**
* Felder, auf deren Wert sich eine Bedingung stützen darf.
* Felder, auf deren Wert sich eine Bedingung stützen darf: gespeicherte Auswahlfelder und Ja/Nein-Felder. Mit
* Zustandspfad der Bedingung nur Felder, die im Formular davor stehen (sonst lehnt die Prüfung die Regel ab).
*
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sources(array $draft): array
private static function sources(array $editor, ?string $path): array
{
$inventory = self::inventory($draft);
$sources = [];
$areaId = null;
$blockId = null;
if ($inventory['hasIssue']) {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
if ($path !== null) {
$segments = explode('.', $path);
$areaAt = array_search('areas', $segments, true);
$itemAt = array_search('items', $segments, true);
$areaId = $areaAt === false ? null : ($segments[$areaAt + 1] ?? null);
$blockId = $itemAt === false ? null : ($segments[$itemAt + 1] ?? null);
}
$catalog = InquiryField::query()->whereIn('key', array_keys($inventory['fields']))->get()->keyBy('key');
$catalog = InquiryField::query()->get()->keyBy('key');
$sources = [];
foreach ($inventory['fields'] as $key => $name) {
if (isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = $name;
foreach ((array) ($editor['areas'] ?? []) as $currentArea => $area) {
if ($areaId !== null && (string) $currentArea === $areaId && $blockId === null) {
break;
}
foreach ((array) ($area['items'] ?? []) as $currentBlock => $block) {
if ($areaId !== null && (string) $currentArea === $areaId && (string) $currentBlock === $blockId) {
break 2;
}
$data = (array) ($block['data'] ?? []);
$key = (string) ($data['key'] ?? '');
if (($block['type'] ?? null) === 'issue') {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
} elseif (($block['type'] ?? null) === 'field' && isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = (string) (($data['label'] ?? '') ?: $catalog[$key]->label);
}
}
}
@@ -267,13 +431,13 @@ private static function sources(array $draft): array
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sourceValues(array $draft, string $source): array
private static function sourceValues(array $editor, string $source): array
{
if ($source === 'anliegen' || $source === 'unteranliegen') {
$only = array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'));
$only = self::inventory($editor)['issues'];
$options = [];
foreach (InquiryIssue::tree() as $issue) {
@@ -298,15 +462,6 @@ private static function sourceValues(array $draft, string $source): array
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>
*/
@@ -4,9 +4,11 @@
use App\Domain\Communication\FormEvaluator;
use App\Domain\Communication\FormPayload;
use App\Domain\Communication\FormReason;
use App\Domain\Communication\FormToken;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryService;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\SubmissionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -68,6 +70,59 @@ public function submit(Request $request, InquiryEntry $entry): JsonResponse
return $this->json(['reference' => $result['reference']], 201);
}
/**
* Widget „Anfrage“ (ADR-61): das veröffentlichte Formular einer Vorlage für den gewählten Anfragegrund. Der Grund
* (Anliegen, Unteranliegen, Formularführung) steht in der Adresse, damit Zustand und Absendung ohne weitere
* Angaben dasselbe Formular meinen.
*/
public function formDefinition(Request $request, InquiryTemplate $template): JsonResponse
{
$delivered = $this->service->deliverForm($template, FormReason::clean($request->query()));
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
return $this->json([
...FormPayload::definition($delivered['form'], $this->evaluator),
'token' => FormToken::issue($template->id, $delivered['version']->id, 'form'),
'csrf' => csrf_token(),
]);
}
public function formState(Request $request, InquiryTemplate $template): JsonResponse
{
$delivered = $this->service->deliverForm($template, FormReason::clean($request->query()));
if ($delivered === null) {
return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404);
}
$values = $request->input('values');
if (! is_array($values) || strlen((string) json_encode($values)) > 40000) {
return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422);
}
return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator));
}
public function formSubmit(Request $request, InquiryTemplate $template): JsonResponse
{
try {
$result = $this->service->submitForm($template, FormReason::clean($request->query()), [
'token' => $request->input('token'),
'values' => $request->input('values'),
'website' => $request->input('website'),
'source' => $request->input('source'),
]);
} catch (SubmissionException $e) {
return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422);
}
return $this->json(['reference' => $result['reference']], 201);
}
/**
* @param array<string, mixed> $data
*/
@@ -907,3 +907,24 @@ ## ADR-60 – Zentrale Kommunikationsverwaltung: Anfragevorlagen, Anfrage-Einsti
**Folgen.** Eine additive Migration `2026_12_03_100000_create_communication_tables` mit neun neuen Tabellen (`inquiry_issues`, `inquiry_fields`, `inquiry_field_groups`, `inquiry_templates`, `inquiry_template_versions`, `inquiries`, `inquiry_entries`, `inquiry_notes`, `communication_settings`); nichts Bestehendes wird verändert. Neue Widget-Art `inquiry`; eine einmal gespeicherte Kennung bleibt (Rückfall: ein Code-Stand ohne das Widget zeigt den Baustein nicht, die übrige Seite bleibt unverändert). Es entstehen keine Beispieldaten durch Migration; eine Beispielkonfiguration legt ein Betreiber mit „Kommunikation → Einstellungen → Beispielkonfiguration anlegen“ an (nur in einer leeren Verwaltung). Der Befehl `communication:purge` löscht Anfragen nach der gewählten Aufbewahrungsdauer; ein Zeitplaner ist nicht eingerichtet (offen).
**Ausblick (nicht umgesetzt, nur nicht verbaut).** Ein KI-Assistent könnte dieselben Vorlagen und Felder nutzen und am Ende denselben Anfrageservice aufrufen (kein zweiter Service, keine zweite Datenhaltung, Absenden erst nach ausdrücklicher Bestätigung, klassisches Formular bleibt). Eine Dachmarke braucht eigene Anfragevorlagen und Einstiege, keine Mehrmandantenfähigkeit. Anmeldung, Termine, Plätze und Zahlung sind ausdrücklich ausgeschlossen. Anfragen können später manuell weiterbearbeitet werden; eine automatische Weitergabe oder Trainervermittlung ist nicht vorgesehen und braucht einen eigenen rechtlichen Prozess.
**Quelle.** Entwicklungsauftrag von Lars vom 27.11.2026; ADR-30, ADR-32, ADR-38.
## ADR-61 – Kommunikation: Formular-Editor an einem Ort und Anfragegründe im CMS-Widget
**Status am 27.11.2026:** Umgesetzt auf `feature/kommunikation-ux` und `develop`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Ergänzt ADR-60, ersetzt es nicht. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` (Abschnitt 12).
**Kontext.** Die Engine aus ADR-60 funktioniert, die Bedienung war zu technisch: Für ein Formular mussten Anliegen, Feldkatalog, Feldgruppen, Anfragevorlage und Anfrage-Einstieg getrennt bedient werden, und das CMS-Widget wählte nur einen vorher angelegten Einstieg. Der Auftrag vom 27.11.2026 verlangt weniger Bedienaufwand und eine bessere CMS-Einbindung, ausdrücklich ohne Umbau der Engine, ohne neues Datenmodell und ohne Änderung der Anfrageverarbeitung, soweit nicht zwingend.
**Entscheidung.**
- **Navigation:** Anfragen, Formulare & Befragungen, Einstellungen. Anliegen, Feldkatalog, Feldgruppen und Anfrage-Einstiege bleiben als Objekte, Seiten und Adressen erhalten (Verweise, ältere Seiten, Tests), stehen aber nicht mehr in der Hauptnavigation; „Einstellungen“ verweist darauf.
- **Formular-Editor** (`FormEditor`, `TemplateEditor`): ein Formular wird an einer Stelle bearbeitet. Ansicht: Bereiche (im mehrstufigen Dialog je ein Schritt), darin Felder, Teilbereiche (Überschrift im Fluss, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“) und die Frage nach dem Anliegen. Felder entstehen direkt im Bereich oder werden aus dem Katalog übernommen. Es gibt keine zweite Datenhaltung: Der Editor schreibt neue und geänderte Felder und Teilbereiche in dieselben Katalogtabellen und liefert denselben Entwurf (`steps`, `rules`) wie bisher; beim Öffnen wird er in die flache Ansicht übersetzt. Ein Test belegt, dass jedes Beispielformular unverändert öffnet und wieder genau denselben Entwurf und denselben Katalog ergibt.
- **Gemeinsame Felder:** Ein Feld oder Teilbereich, der in mehreren Formularen vorkommt, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare („gilt dort mit der nächsten Veröffentlichung“). Bestehende Fassungen sind unveränderlich. Die Art eines vorhandenen Feldes ist nicht änderbar (Bedingungen und Antworten bauen darauf auf); eine andere Art ist ein neues Feld. Auswahlwerte behalten ihre Kennung bei Umbenennung.
- **Bedingungen am Element:** Feld, Teilbereich und Bereich tragen ihre Bedingung selbst (Wirkung, „alle/mindestens eine“, Vergleiche, alles als Auswahl). Beim Speichern entstehen daraus dieselben Regeln der Engine. Was sich nicht an ein Element heften lässt (weitere Regeln desselben Ziels, Vorbelegungen), bleibt unter „Weitere Regeln“ erhalten und wird nie verworfen. Zur Auswahl stehen nur Felder, die im Formular weiter oben stehen (die Prüfung verlangt es ohnehin). Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung.
- **Kleine Erweiterung der Engine:** `show` und `hide` wirken auch auf Bereiche (bisher nur `skip`), damit „Bereich nur anzeigen, wenn …“ ohne umgekehrte Bedingungen ausdrückbar ist. `skip` bleibt gültig.
- **Widget „Anfrage“ ohne Anfrage-Einstieg:** Das Widget speichert Anfragegründe (`data.reasons`: Kennung, Bezeichnung, Beschreibung, Formular, optional vorgewähltes Anliegen und Unteranliegen), die Frage der Auswahl und die Beschriftung des Buttons sowie Einstellungen: **Formularführung** (`mode`: langes Formular oder mehrstufiger Dialog) und **Präsentation** (`open`: im Abschnitt oder als Dialog) unabhängig voneinander; Gestaltung: Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten folgt der Containerbreite; es gibt keine Einstellung je Bildschirmgröße.
- **Genau ein Formular je Grund:** Der Besucher wählt einen Grund; erst dann lädt der Browser das Formular dieses Grundes (`/anfrage/formular/{vorlage}?anliegen=…&unteranliegen=…&modus=…`, Zustand und Absenden ebenso). Je Grund gibt es höchstens eine Formularinstanz; ein Wechsel blendet nur um, Eingaben bleiben. Bei einem einzigen Grund entfällt die Auswahl. Eine Vorauswahl über die Adresse (`?grund=Kennung`) wählt den Grund und öffnet bei „Dialog“ den Dialog.
- **Der Grund ist Vorauswahl und Darstellung, keine Berechtigung.** Alles, was ein Grund wählen kann, bietet das veröffentlichte Formular ohnehin an. Deshalb steht der Grund in der Adresse und nicht in einer signierten Konfiguration; die Auslieferung bleibt zustandslos. Aus dem Grund entsteht dieselbe Konfiguration wie bei einem Einstieg (`FormReason`, `FormFactory::effective`). Auslieferbar ist jede veröffentlichte, nicht archivierte Vorlage; die Veröffentlichung ist die bewusste Handlung.
- **Anfrageverarbeitung unverändert:** Dieselbe Auswertung, Prüfung, Doppelsende- und Köderfeld-Abwehr, Ratenbegrenzung und Benachrichtigung. Das Formular-Token erhält die Art des Ziels (`entry` oder `form`) und ist nicht zwischen beiden austauschbar. Eine Anfrage über das Widget hat keine Einstiegskennung (`entry_id` war bereits optional) und verweist über ihre Fassung auf die Vorlage; der Posteingang zeigt „Formular …“. Keine Migration.
- **Dialog:** natives `dialog`-Element (`showModal`): Esc und „Schließen“ behalten die Eingaben, der Fokus kehrt zum Button zurück, die Seite dahinter ist fixiert, auf dem Smartphone füllt der Dialog den Bildschirm, die Aktionen bleiben unten erreichbar. In den Vorschau-Iframes des Seiteneditors (nur Stile, kleine feste Fläche) steht der Dialog als gerahmtes Beispiel; Seitenvorschau und Geräteansicht öffnen den echten Dialog.
- **Ältere Seiten:** Eine Seite mit `refs.entry` und ohne Anfragegründe wird weiter dargestellt; der Anfrage-Einstieg bleibt als Objekt erhalten.
**Alternativen.** Signierte Widget-Konfiguration in der Seite (verworfen: Der Grund ist keine Berechtigung; mehr bewegliche Teile ohne Gewinn). Neue Tabellen für Widget-Konfigurationen (ausgeschlossen: kein neues Datenmodell). Verschachtelte Teilbereiche mit eigenen Feldlisten im Editor (verworfen: sechs Ebenen Formularstruktur, schwer bedienbar; die flache Liste mit „Ende des Teilbereichs“ bildet dasselbe ab). Feldänderungen je Formular als Kopie (verworfen: zweite Wahrheit; der Hinweis auf gemeinsame Verwendung genügt, Fassungen sind unveränderlich).
**Folgen.** Keine Migration. Zwei bestehende Tests wurden bewusst geändert (Widget-Vertrag: Anfragegründe statt Einstieg). Rückfall: ein Code-Stand ohne ADR-61 kennt `data.reasons` nicht und zeigt ein so gespeichertes Widget nicht an (die Seite bleibt gültig); Formulare und Anfragen bleiben unverändert, im Katalog angelegte Felder bleiben bestehen.
**Quelle.** Entwicklungsauftrag von Lars (UX-Überarbeitung der Kommunikationsverwaltung und des CMS-Kontakt-Widgets) vom 27.11.2026; ADR-60.
+7 -7
View File
@@ -136,15 +136,15 @@ ## 4. Registrierte Widget-Arten
- Das Kit lädt das Einstiegsbild immer sofort; hier nur beim ersten Widget der Seite, alle anderen verzögert.
- Kit-CSS ergänzt: Überschriften erben Farbe (globale h1–h3-Regeln), Unterstreichung als Block, Fläche `clear` übernimmt die Farben dunkler Abschnitte, Strahlen-Akzent aus `components/brand/rays.blade.php`, Fokusfarbe aus den Tokens.
### Anfrage (`inquiry`, Version 1, ADR-60)
### Anfrage (`inquiry`, Version 1, ADR-60, ADR-61)
Bindet einen veröffentlichten **Anfrage-Einstieg** der Kommunikationsverwaltung ein. Gespeichert wird nur `refs.entry` (Kennung); `data`, `settings` und Varianten sind leer beziehungsweise Standard. Das Widget kennt weder Felder noch Texte, Regeln oder Empfänger; diese werden ausschließlich unter „Kommunikation“ gepflegt (`docs/architektur/kommunikationsverwaltung.md`).
Kontaktformular mit Auswahl des **Anfragegrundes**. `data.reasons` (bis zu 8): `key` (entsteht beim Speichern, stabil), `label`, `description`, `template` (Kennung eines veröffentlichten Formulars), optional `issue` und `subissue` (vorgewähltes Anliegen); dazu `question` und `open_label`. Einstellungen (`settings`): `mode` (compact, wizard), `open` (inline, modal), `picker` (cards, select), `width`, `spacing`, `columns`, `button`; Formularführung und Präsentation sind unabhängig. Das Widget kennt weder Felder noch Texte, Regeln oder Empfänger; diese werden unter „Kommunikation → Formulare & Befragungen“ gepflegt. Seiten der ersten Fassung (`refs.entry`, kein Grund) werden weiter dargestellt.
- Auswahl im Editor: nur veröffentlichte, nicht archivierte Einstiege (`refRules` prüft das beim Speichern).
- Darstellung: ein Einhängepunkt (`x-inquiry.mount`) mit den Adressen von Formular, Zustand und Annahme; das Formular baut `resources/js/inquiry-form.js` zur Laufzeit. Die gespeicherte Seite enthält keinen Formularstand; eine zentrale Veröffentlichung wirkt sofort auf allen Seiten.
- Ein zurückgezogener, archivierter oder gelöschter Einstieg lässt das Widget öffentlich leer (die Seite bleibt gültig); die Seitenvorschau nennt den Grund.
- Platz: 3 oder 4 Rastereinheiten; das Formular begrenzt sich selbst auf Lesebreite.
- Sprungmarke: Ein Abschnitt mit der Sprungmarke `anfrage` lässt sich mit Links wie `/kurse#anfrage` direkt ansteuern.
- Prüfung: nur die Existenz des Formulars (`reasons.*.template`), damit eine später zurückgezogene Vorlage eine Seite nicht unspeicherbar macht. Öffentlich erscheint ein Grund nur, solange sein Formular veröffentlicht und nicht archiviert ist; ohne verfügbaren Grund bleibt das Widget leer, die Vorschau nennt den Grund.
- Darstellung: `data-config` mit Gründen und Adressen (`/anfrage/formular/{vorlage}?anliegen=…&modus=…`); `resources/js/inquiry-widget.js` zeigt die Auswahl, lädt erst nach der Wahl das Formular des Grundes und hält je Grund eine Instanz. Dialog als natives `dialog`. Vorauswahl über `?grund=Kennung`.
- Vorschau-Iframes im Seiteneditor laden nur Stile: Die Widget-Ansicht lädt dort `resources/js/inquiry-embed.js` (eigener Vite-Einstieg); der Dialog steht dort als gerahmtes Beispiel.
- Platz: 3 oder 4 Rastereinheiten; Breite, Abstände und Feldanordnung sind Einstellungen, Umbrüche folgen der Containerbreite.
- Sprungmarke: Ein Abschnitt mit Sprungmarke lässt sich mit Links wie `/kontakt?grund=kurse_workshops#anfrage` ansteuern.
## 5. Neues Widget hinzufügen
@@ -104,3 +104,32 @@ ## 11. Offene fachliche und rechtliche Prüfpunkte
- Kursformate sind Arbeitsvorschläge; das Formular darf keine Termine, Preise oder Buchung suggerieren (Texte der Beispiele sind entsprechend formuliert).
- Spam-Schutz: Köderfeld, Mindestdauer und Ratenbegrenzung. Ein externes Captcha ist nicht eingebaut (Datenschutz); bei Missbrauch nachrüsten.
- Texte des Beispiels sind Entwürfe des Betreibers zur Prüfung.
## 12. UX-Überarbeitung (ADR-61)
Stand: 27.11.2026. Menü der Gruppe „Kommunikation“: **Anfragen**, **Formulare & Befragungen**, **Einstellungen**. Die Abschnitte 4 und 9 gelten für Anliegen, Feldkatalog, Feldgruppen und Einstiege weiter, nur ohne eigenen Menüpunkt; erreichbar sind sie unter „Einstellungen → Weitere Bausteine“.
### Formular bearbeiten
1. „Formulare & Befragungen“ → „Formular anlegen“ (Name) → der Editor öffnet.
2. Reiter **Aufbau:** Bereiche (Titel, Einleitung, Bedingung), darin „Feld oder Teilbereich hinzufügen“.
- **Feld:** Frage, Art der Antwort (nach dem Speichern fest), Auswahlwerte, Hilfetext, Pflicht, Bedingung; „Vorhandenes Feld verwenden“ übernimmt ein Feld aus dem Katalog (zum Beispiel die E-Mail-Adresse). Unter „Weitere Einstellungen“ die Verwendung in der Anfrageübersicht. Jedes Formular braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“.
- **Teilbereich:** Überschrift für die folgenden Felder, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“.
- **Frage nach dem Anliegen:** die Auswahl des Anliegens (angebotene Anliegen).
- **Bedingung** (Feld, Teilbereich, Bereich): „nur anzeigen, wenn …“, „ausblenden, wenn …“, bei Feldern „Pflichtfeld, wenn …“, bei Bereichen „überspringen, wenn …“. Beispiel: Teilbereich „Angaben zur Schule“ nur anzeigen, wenn „Sind Sie eine Schule?“ = Ja.
3. Reiter **Texte:** Überschrift, Beschreibung, Schaltflächen, Bestätigung, Datenschutzhinweis. Reiter **Weitere Regeln:** nur, was sich nicht an ein Element heften lässt (zum Beispiel Vorbelegungen).
4. **Speichern**, **Konfiguration prüfen**, **Vorschau** (als langes Formular oder mehrstufig, es wird nichts gesendet), **Veröffentlichen** (neue Fassung, sofort gültig überall, wo das Formular eingebunden ist), Fassungen unten (zurückkehren möglich).
Ein Feld, das mehrere Formulare nutzen, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare. Die Änderung gilt dort mit deren nächster Veröffentlichung.
### Widget „Anfrage“ im Seiteneditor
- Reiter **Inhalt:** **Anfragegründe** (Bezeichnung, Kurzbeschreibung, Formular, optional Anliegen und Unteranliegen vorwählen), Frage der Auswahl, Beschriftung des Buttons. Die Kennung eines Grundes (für Links) entsteht beim Speichern.
- Reiter **Darstellung:** **Formularführung** (langes Formular oder mehrstufiger Dialog) und **Präsentation** (im Abschnitt oder als Dialog über der Seite) getrennt; Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten ergibt sich aus der verfügbaren Breite.
- **Vorauswahl durch einen Button der Seite:** Link auf die Seite mit `?grund=Kennung` (und gegebenenfalls `#Sprungmarke`). Das Widget wählt den Grund und öffnet bei „Dialog“ den Dialog.
- Mehrere zulässige Gründe: Der Besucher sieht zuerst die Frage, danach nur das Formular seines Grundes („Anderen Grund wählen“ wechselt, Eingaben bleiben je Grund erhalten). Ein einziger Grund: kein Auswahlschritt.
- Vorschau im Dialog des Widgets, in der Seitenvorschau und in der Geräteansicht.
### Öffentliche Adressen und Grenzen
`/anfrage/formular/{vorlage}` (Beschreibung und Token), `/zustand`, `/senden`; Grund in der Adresse (`anliegen`, `unteranliegen`, `modus`). Dieselbe Ratenbegrenzung wie bei Einstiegen. Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. Nicht umgesetzt: Vorbelegung weiterer Felder (zum Beispiel Kursformat) je Anfragegrund; dafür bleibt der Anfrage-Einstieg.
@@ -17,6 +17,7 @@ ## 1. Inhalt (Stand 21.11.2026 abends: 22 Commits seit `main`)
| Abschnitte: Name, Sprungmarke, Ausblenden | Abschnitte lassen sich benennen (nur zur Orientierung), als Sprungmarke nutzen (Link „#marke“, „/pfad#marke“, von außen „Adresse#marke“) und für die Website ausblenden; Anzeige im Seitenaufbau. Keine Migration (neue optionale Felder in `sections`). **Rollback:** ältere Stände kennen „ausgeblendet“ nicht und zeigen solche Abschnitte wieder | Claude |
| Interne Links wählen | Alle Linkfelder der Widgets und das Werkzeug im formatierten Text bieten einen Dialog für Seiten und Sprungmarken; Menüeinträge können auf eine Sprungmarke zeigen. Migration `2026_12_02_100000_add_anchor_to_navigation_items` (additiv) | Claude |
| Kommunikationsverwaltung und Widget „Anfrage“ | Neue Gruppe „Kommunikation“ (Anfragen, Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen, Anfrage-Einstiege, Einstellungen), öffentliche Schnittstelle `/anfrage/{einstieg}` und CMS-Widget `inquiry` (ADR-60). **Vor dem Merge:** Mailversand in `/etc/luf/prod.env` prüfen (`MAIL_*`), Empfänger und Datenschutzhinweis festlegen, Testnachricht in den Einstellungen senden; Beispielkonfiguration auf Prod nur auf ausdrücklichen Wunsch anlegen. Rückfall: ältere Stände kennen das Widget nicht und zeigen es nicht | Claude |
| Kommunikation: Formular-Editor und Anfragegründe (ADR-61) | Navigation Anfragen, Formulare & Befragungen, Einstellungen; ein Editor für Bereiche, Felder und Bedingungen; Widget „Anfrage“ mit Anfragegründen statt Einstieg, Formularführung und Präsentation (Dialog) getrennt, Auslieferung `/anfrage/formular/{vorlage}`. Keine Migration. Rückfall: ein Stand ohne ADR-61 zeigt ein Widget mit Anfragegründen nicht an (Seite bleibt gültig), Formulare und Anfragen bleiben unverändert. Zwei Widget-Tests bewusst geändert. | Claude |
| Hero mit Video | Der Einstieg (Variante Foto mit Textfläche) spielt auf Wunsch ein freigegebenes Video stumm auf der Fläche des Fotos ab, mit Schaltfläche zum Anhalten; Foto als Rückfall (ADR-43 Nachtrag). Keine Migration | Claude |
| Website-Datei eines Films | Ablage der Datei eines eigenständigen Präsentationsmediums über die Warteschlange, nachträgliches Hochladen am Medium (Behebung: der Web-Prozess darf `derived/` nicht schreiben) | Lars (anderer Rechner) |
| Medienmanager | „Medium löschen“ erreicht Standbilder und übernommene CMS-Bilder (Fremdschlüssel gelockert) | Claude |
+312
View File
@@ -448,3 +448,315 @@ @media (prefers-reduced-motion: reduce) {
transition: none !important;
}
}
/*
* Widget „Anfrage“ (ADR-61): Auswahl des Anfragegrundes, Formular je Grund, Dialog. Breite, Abstände, Feldanordnung und
* Buttons sind Einstellungen des Widgets (Klassen iw-…); das Verhalten bei wenig Platz folgt der Breite des Containers.
*/
.inquiry-widget {
--iw-width: 44rem;
container-type: inline-size;
max-width: var(--iw-width);
margin-inline: auto;
color: var(--color-text);
}
.inquiry-widget.iw-width-narrow {
--iw-width: 32rem;
}
.inquiry-widget.iw-width-wide {
--iw-width: 60rem;
}
.inquiry-widget [hidden] {
display: none !important;
}
.inquiry-widget .inquiry {
--inquiry-width: 100%;
max-width: none;
margin-inline: 0;
}
.iw-body {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.iw-picker {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
border: 0;
min-width: 0;
}
.iw-question {
padding: 0;
font-size: 1.2em;
font-weight: 700;
color: var(--color-heading);
}
.iw-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
gap: var(--space-3);
}
.iw-card {
position: relative;
display: flex;
min-width: 0;
}
.iw-card input {
position: absolute;
inset-block-start: var(--space-3);
inset-inline-end: var(--space-3);
width: 1.4rem;
height: 1.4rem;
margin: 0;
accent-color: var(--color-action);
}
.iw-card label {
display: grid;
align-content: start;
gap: var(--space-1);
flex: 1;
min-height: var(--touch-target);
padding: var(--space-3) calc(var(--space-3) + 2rem) var(--space-3) var(--space-3);
border: 2px solid var(--color-border);
border-radius: var(--radius-card);
background: var(--color-surface);
cursor: pointer;
transition: border-color 0.15s ease, background-color 0.15s ease;
}
.iw-card label:hover {
border-color: var(--color-border-strong);
}
.iw-card input:checked + label {
border-color: var(--color-action);
background: var(--color-success-surface);
}
.iw-card input:focus-visible + label {
outline: 3px solid var(--color-focus);
outline-offset: 2px;
}
.iw-card-label {
font-weight: 700;
color: var(--color-heading);
}
.iw-card-desc {
font-size: 0.92em;
color: var(--color-text-muted);
}
.iw-select {
width: 100%;
min-height: var(--touch-target);
padding: var(--space-2) var(--space-3);
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-small);
background: var(--color-surface);
color: var(--color-text);
font: inherit;
}
.iw-select:focus-visible,
.iw-change:focus-visible,
.iw-close:focus-visible,
.iw-opener:focus-visible {
outline: 3px solid var(--color-focus);
outline-offset: 2px;
}
.iw-chosen {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: var(--space-2);
margin: 0;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-small);
background: var(--color-surface-subtle);
}
.iw-change {
padding: 0.25rem 0;
min-height: var(--touch-target);
border: 0;
background: none;
color: var(--color-action);
font: inherit;
font-weight: 600;
text-decoration: underline;
cursor: pointer;
}
.iw-forms {
min-width: 0;
}
.iw-forms > .inquiry:focus {
outline: none;
}
/* Abstände */
.iw-spacing-compact .inquiry-form,
.iw-spacing-compact .inquiry-step,
.iw-spacing-compact .inquiry-group {
gap: var(--space-2);
}
.iw-spacing-airy .inquiry-form {
gap: var(--space-6);
}
.iw-spacing-airy .inquiry-step,
.iw-spacing-airy .inquiry-group {
gap: var(--space-5);
}
/* Anordnung der Felder: „Immer eine Spalte“ hebt die zweispaltige Anordnung bei viel Platz auf. */
.iw-cols-one .inquiry-group {
grid-template-columns: 1fr;
}
/* Buttons: „Umrandet“ für die Haupthandlungen; „Zurück“ bleibt die Nebenschaltfläche. */
.iw-btn-outline .button:not(.button-secondary):not(.button-quiet) {
background: transparent;
border-color: var(--color-action);
color: var(--color-action);
}
.iw-btn-outline .button:not(.button-secondary):not(.button-quiet):hover {
background: var(--color-success-surface);
color: var(--color-action);
}
.iw-opener {
max-width: 100%;
}
/* Dialog über der Seite */
.iw-dialog {
width: min(calc(100vw - 2 * var(--space-4)), var(--iw-width, 44rem));
max-width: none;
max-height: calc(100dvh - 2 * var(--space-4));
margin: auto;
padding: 0;
border: 0;
border-radius: var(--radius-panel);
background: var(--color-surface);
color: var(--color-text);
box-shadow: var(--shadow-raised);
overflow: hidden;
}
.iw-dialog[open] {
display: flex;
flex-direction: column;
}
.iw-dialog::backdrop {
background: rgb(3 37 81 / 55%);
}
.iw-dialog-head {
display: flex;
justify-content: flex-end;
flex: none;
padding: var(--space-2) var(--space-3) 0;
}
.iw-close {
display: inline-flex;
align-items: center;
justify-content: center;
width: var(--touch-target);
height: var(--touch-target);
border: 0;
border-radius: var(--radius-pill);
background: transparent;
color: var(--color-text);
font-size: 1.8rem;
line-height: 1;
cursor: pointer;
}
.iw-close:hover {
background: var(--color-surface-subtle);
}
.iw-dialog .iw-body {
flex: 1;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
padding: 0 var(--space-5) var(--space-5);
}
/* Im Dialog bleiben „Zurück“, „Weiter“ und „Absenden“ am unteren Rand erreichbar, auch wenn das Formular länger ist. */
.iw-dialog .inquiry-actions {
position: sticky;
bottom: 0;
z-index: 1;
padding-block: var(--space-3);
border-top: 1px solid var(--color-border);
background: var(--color-surface);
}
html.iw-locked {
overflow: hidden;
}
/* Smartphone: Der Dialog füllt den Bildschirm. */
@media (max-width: 40rem) {
.iw-dialog {
width: 100vw;
height: 100dvh;
max-height: none;
border-radius: 0;
}
.iw-dialog .iw-body {
padding: 0 var(--space-4) var(--space-5);
}
}
@media (prefers-reduced-motion: reduce) {
.inquiry-widget * {
scroll-behavior: auto !important;
transition: none !important;
}
}
/* Vorschau im Seiteneditor: der geöffnete Dialog als gerahmtes Beispiel statt als Dialog über der Seite. */
.iw-sample-note {
margin: var(--space-3) 0 var(--space-2);
font-size: 0.9em;
color: var(--color-text-muted);
}
.iw-dialog--sample {
display: flex;
flex-direction: column;
width: auto;
max-height: none;
border: 2px dashed var(--color-border-strong);
box-shadow: none;
}
.iw-dialog--sample .iw-body {
overflow: visible;
}
+1
View File
@@ -4,6 +4,7 @@ import './card-clip.js';
import './notice.js';
import './hero-video.js';
import './inquiry-form.js';
import './inquiry-widget.js';
import './member-nav.js';
function attachPlayback(video) {
+6
View File
@@ -0,0 +1,6 @@
/*
* Einstieg für Vorschauen, die nur Stile laden (Iframes im Seiteneditor): bringt das Anfrageformular und das Widget
* „Anfrage“ zum Laufen. Die öffentliche Seite und die Seitenvorschau laden dasselbe über app.js.
*/
import './inquiry-form.js';
import './inquiry-widget.js';
+8
View File
@@ -62,6 +62,13 @@ class InquiryForm {
const response = await fetch(this.root.dataset.definitionUrl, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
if (!response.ok) {
if (this.root.dataset.embedded === '1') {
// Vom Widget „Anfrage“ eingebettet: Der Besucher hat das Formular gewählt, also sagen wir, dass es fehlt.
this.root.replaceChildren(h('p', { class: 'inquiry-note', role: 'alert', text: 'Dieses Anfrageformular ist zurzeit nicht verfügbar. Bitte versuchen Sie es später noch einmal.' }));
return;
}
this.root.replaceChildren();
this.root.hidden = true;
@@ -913,6 +920,7 @@ class InquiryForm {
success(reference) {
this.finished = true;
this.root.dispatchEvent(new CustomEvent('inquiry:sent', { bubbles: true }));
const preview = reference === 'Vorschau';
const box = h('div', { class: 'inquiry-success', role: 'status', tabindex: '-1' },
h('h3', { text: this.def.texts.success_title }),
+322
View File
@@ -0,0 +1,322 @@
/*
* Widget „Anfrage“ (ADR-61): Auswahl des Anfragegrundes, genau ein Formular je Grund, inline oder als Dialog.
* Das Formular selbst baut resources/js/inquiry-form.js aus der Beschreibung, die der Server für den Grund liefert.
* Je Grund gibt es höchstens eine Formularinstanz; ein Wechsel blendet sie nur aus, Eingaben bleiben erhalten. Es ist nie
* mehr als ein Formular sichtbar.
*/
import { initInquiryForms } from './inquiry-form.js';
let counter = 0;
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(attrs)) {
if (value === false || value === null || value === undefined) {
continue;
}
if (key === 'class') {
el.className = value;
} else if (key === 'text') {
el.textContent = value;
} else if (key.startsWith('on')) {
el.addEventListener(key.slice(2), value);
} else if (value === true) {
el.setAttribute(key, '');
} else {
el.setAttribute(key, String(value));
}
}
for (const child of children.flat()) {
if (child === null || child === undefined || child === false) {
continue;
}
el.append(child.nodeType ? child : document.createTextNode(String(child)));
}
return el;
}
class InquiryWidget {
constructor(root) {
this.root = root;
this.id = 'iw' + ++counter;
this.config = JSON.parse(root.dataset.config);
this.reasons = this.config.reasons;
this.forms = new Map();
this.active = null;
this.sent = false;
this.modal = this.config.open === 'modal';
// In den Vorschau-Iframes des Seiteneditors (srcdoc, kleine feste Fläche) ist ein echter Dialog nicht darstellbar:
// Dort steht der geöffnete Dialog als gerahmtes Beispiel unter dem Button. Auf der Seite und in der Seitenvorschau
// öffnet der Button den echten Dialog.
this.sample = this.modal && this.config.preview && Boolean(window.frameElement?.hasAttribute?.('srcdoc'));
}
start() {
const wanted = new URLSearchParams(window.location.search).get('grund');
const preselected = this.reasons.find((reason) => reason.key === wanted) || null;
this.build();
if (this.reasons.length === 1) {
this.choose(this.reasons[0].key, false);
} else if (preselected) {
this.choose(preselected.key, false);
}
if (this.sample) {
return;
}
if (this.modal) {
// Ein Button der Seite mit ?grund=… will den Dialog sofort sehen; ohne Vorwahl öffnet der Besucher selbst.
if (preselected) {
this.open();
}
} else if (preselected && window.location.hash === '') {
this.root.scrollIntoView({ block: 'start' });
}
}
/* ------------------------------------------------------------------ Aufbau */
build() {
this.question = this.config.question;
this.picker = this.reasons.length > 1 ? this.buildPicker() : null;
this.chosenBar = this.reasons.length > 1 ? this.buildChosenBar() : null;
this.formHost = h('div', { class: 'iw-forms' });
this.body = h('div', { class: 'iw-body' }, ...[this.picker, this.chosenBar, this.formHost].filter(Boolean));
this.root.replaceChildren();
if (!this.modal) {
this.root.append(this.body);
this.root.classList.add('is-inline');
return;
}
this.root.classList.add('is-modal');
if (this.sample) {
this.opener = h('button', { type: 'button', class: 'button iw-opener', text: this.config.openLabel });
this.root.append(
this.opener,
h('p', { class: 'iw-sample-note', text: 'Vorschau: So sieht der geöffnete Dialog aus.' }),
h('div', { class: 'iw-dialog iw-dialog--sample', role: 'group', 'aria-label': this.config.openLabel }, h('div', { class: 'iw-dialog-head' }, h('span', { class: 'iw-close', 'aria-hidden': 'true' }, '×')), this.body),
);
return;
}
this.opener = h('button', {
type: 'button',
class: 'button iw-opener',
'aria-haspopup': 'dialog',
text: this.config.openLabel,
onclick: () => this.open(),
});
this.close = h('button', { type: 'button', class: 'iw-close', 'aria-label': 'Dialog schließen', onclick: () => this.dialog.close() }, '×');
this.dialog = h('dialog', { class: 'iw-dialog', 'aria-label': this.config.openLabel },
h('div', { class: 'iw-dialog-head' }, this.close),
this.body,
);
this.dialog.addEventListener('close', () => this.onClose());
this.dialog.addEventListener('click', (event) => {
// Klick auf den abgedunkelten Hintergrund (das Dialogelement selbst) schließt; Eingaben bleiben erhalten.
if (event.target === this.dialog) {
this.dialog.close();
}
});
this.root.append(this.opener, this.dialog);
}
buildPicker() {
const name = this.id + '-grund';
const legendId = this.id + '-question';
if (this.config.picker === 'select') {
const select = h('select', {
id: this.id + '-select',
class: 'iw-select',
onchange: () => {
if (select.value !== '') {
this.choose(select.value, true);
}
},
}, h('option', { value: '', text: 'Bitte wählen …' }), ...this.reasons.map((reason) => h('option', { value: reason.key, text: reason.label })));
this.select = select;
return h('div', { class: 'iw-picker iw-picker--select' },
h('label', { class: 'iw-question', for: select.id, text: this.question }),
select,
);
}
const cards = this.reasons.map((reason) => {
const input = h('input', {
type: 'radio',
name,
id: `${this.id}-r-${reason.key}`,
value: reason.key,
onchange: () => this.choose(reason.key, true),
});
return h('div', { class: 'iw-card' }, input,
h('label', { for: input.id },
h('span', { class: 'iw-card-label', text: reason.label }),
reason.description ? h('span', { class: 'iw-card-desc', text: reason.description }) : null,
),
);
});
return h('fieldset', { class: 'iw-picker iw-picker--cards', 'aria-labelledby': legendId },
h('legend', { class: 'iw-question', id: legendId, text: this.question }),
h('div', { class: 'iw-cards' }, ...cards),
);
}
buildChosenBar() {
this.chosenLabel = h('strong', { class: 'iw-chosen-label' });
this.changeButton = h('button', { type: 'button', class: 'iw-change', onclick: () => this.change() }, 'Anderen Grund wählen');
return h('p', { class: 'iw-chosen', hidden: true }, 'Anfragegrund: ', this.chosenLabel, ' ', this.changeButton);
}
/* ------------------------------------------------------------------ Auswahl */
choose(key, focus) {
const reason = this.reasons.find((candidate) => candidate.key === key);
if (!reason) {
return;
}
this.active = key;
if (!this.forms.has(key)) {
this.forms.set(key, this.mount(reason));
}
for (const [formKey, el] of this.forms) {
el.hidden = formKey !== key;
}
if (this.picker) {
this.picker.hidden = true;
this.chosenBar.hidden = false;
this.chosenLabel.textContent = reason.label;
if (this.select) {
this.select.value = key;
}
const radio = this.root.querySelector(`input[type='radio'][value='${key}']`);
if (radio) {
radio.checked = true;
}
}
if (focus) {
const heading = this.forms.get(key).querySelector('.inquiry-heading');
(heading || this.forms.get(key)).focus?.({ preventScroll: false });
}
}
change() {
if (this.sent) {
return;
}
this.picker.hidden = false;
this.chosenBar.hidden = true;
for (const el of this.forms.values()) {
el.hidden = true;
}
this.active = null;
const target = this.select || this.picker.querySelector('input:checked') || this.picker.querySelector('input');
target?.focus();
}
mount(reason) {
const el = h('div', {
class: 'inquiry',
'data-inquiry': '',
'data-embedded': '1',
'data-definition-url': reason.definitionUrl,
'data-state-url': reason.stateUrl,
'data-submit-url': reason.submitUrl,
'data-preview': this.config.preview ? '1' : null,
tabindex: '-1',
}, h('p', { class: 'inquiry-loading', text: `Das Formular „${reason.label}“ wird geladen …` }));
el.addEventListener('inquiry:sent', () => this.onSent());
this.formHost.append(el);
initInquiryForms(this.formHost);
return el;
}
onSent() {
this.sent = true;
if (this.picker) {
this.picker.hidden = true;
this.chosenBar.hidden = true;
}
}
/* ------------------------------------------------------------------ Dialog */
open() {
if (this.dialog.open) {
return;
}
this.lastFocus = document.activeElement;
this.dialog.showModal();
document.documentElement.classList.add('iw-locked');
this.opener.setAttribute('aria-expanded', 'true');
const target = this.active ? this.forms.get(this.active).querySelector('.inquiry-heading') : this.picker?.querySelector('input, select');
(target || this.close).focus?.();
}
onClose() {
document.documentElement.classList.remove('iw-locked');
this.opener.setAttribute('aria-expanded', 'false');
(this.lastFocus && document.contains(this.lastFocus) ? this.lastFocus : this.opener).focus?.();
}
}
export function initInquiryWidgets(root = document) {
root.querySelectorAll('[data-inquiry-widget]').forEach((el) => {
if (el.dataset.inquiryReady === '1') {
return;
}
el.dataset.inquiryReady = '1';
try {
new InquiryWidget(el).start();
} catch {
el.replaceChildren(h('p', { class: 'inquiry-note', role: 'alert', text: 'Das Anfrageformular konnte nicht geladen werden. Bitte laden Sie die Seite neu.' }));
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => initInquiryWidgets());
} else {
initInquiryWidgets();
}
+26
View File
@@ -1,6 +1,13 @@
@php
/** @var \App\Domain\Communication\InquiryEntry|null $entry */
$classes = collect([
'iw-width-'.($settings['width'] ?? 'normal'),
'iw-spacing-'.($settings['spacing'] ?? 'normal'),
'iw-cols-'.($settings['columns'] ?? 'auto'),
'iw-btn-'.($settings['button'] ?? 'solid'),
])->implode(' ');
@endphp
@if ($legacy)
@if ($entryLive)
<x-inquiry.mount
:definition-url="route('inquiry.definition', $entry)"
@@ -17,3 +24,22 @@
@endif
</p>
@endif
@else
@if ($config !== null)
{{-- Das Formular, die Bedingungen und das Token kommen zur Laufzeit vom Server (resources/js/inquiry-widget.js). --}}
<div class="inquiry-widget {{ $classes }}" data-inquiry-widget data-config='@json($config)'>
<p class="inquiry-loading">Das Anfrageformular wird geladen …</p>
<noscript><p class="inquiry-note">Für das Anfrageformular wird JavaScript benötigt. Bitte aktivieren Sie JavaScript in Ihrem Browser.</p></noscript>
</div>
@endif
@if ($context->preview && $unavailable !== [])
<p class="preview-note">
Nicht angeboten, weil das Formular nicht veröffentlicht oder archiviert ist: {{ implode(', ', $unavailable) }}.
@if ($config === null) Öffentlich erscheint an dieser Stelle nichts. @endif
</p>
@endif
@endif
@if ($context->preview)
{{-- Vorschau-Iframes im Seiteneditor laden nur Stile: Das Skript lässt das Formular dort wie auf der Seite erscheinen. --}}
@vite('resources/js/inquiry-embed.js')
@endif
+7
View File
@@ -71,6 +71,13 @@
Route::post('/stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
// Anfrage-Einstiege der Kommunikationsverwaltung (ADR-60): Formular, Auswertung der Bedingungen und Annahme.
// Widget „Anfrage“ (ADR-61): das veröffentlichte Formular einer Vorlage für einen Anfragegrund (Anliegen in der Adresse).
Route::prefix('anfrage/formular/{template}')->whereNumber('template')->name('inquiry.form.')->group(function () {
Route::get('/', [InquiryFormController::class, 'formDefinition'])->name('definition');
Route::post('/zustand', [InquiryFormController::class, 'formState'])->middleware('throttle:inquiry-state')->name('state');
Route::post('/senden', [InquiryFormController::class, 'formSubmit'])->middleware('throttle:inquiry-submit')->name('submit');
});
Route::prefix('anfrage/{entry}')->whereNumber('entry')->name('inquiry.')->group(function () {
Route::get('/', [InquiryFormController::class, 'definition'])->name('definition');
Route::post('/zustand', [InquiryFormController::class, 'state'])->middleware('throttle:inquiry-state')->name('state');
+272
View File
@@ -0,0 +1,272 @@
<?php
namespace Tests\Feature;
use App\Domain\Communication\ExampleConfiguration;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\FormJson;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use App\Domain\Communication\TemplateCompiler;
use App\Filament\Resources\Communication\Templates\Pages\EditInquiryTemplate;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;
/**
* Formular-Editor (ADR-61): Übersetzung zwischen Entwurf und Bearbeitungsansicht, Anlegen von Feldern im Katalog.
*/
class CommunicationEditorTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
app(ExampleConfiguration::class)->install();
}
/**
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
private function structure(array $draft): array
{
return FormJson::normalize(['issues' => $draft['issues'], 'steps' => $draft['steps'], 'rules' => $draft['rules']]);
}
public function test_every_example_form_opens_and_saves_unchanged_in_the_editor(): void
{
$editor = app(FormEditor::class);
foreach (InquiryTemplate::query()->get() as $template) {
$draft = (array) $template->draft;
$fieldsBefore = InquiryField::query()->get()->map->getAttributes()->all();
$groupsBefore = InquiryFieldGroup::query()->get()->map->getAttributes()->all();
$saved = $editor->persist($editor->expand($draft));
$this->assertSame($this->structure($draft), $this->structure($saved), 'Entwurf unverändert: '.$template->name);
$this->assertSame($fieldsBefore, InquiryField::query()->get()->map->getAttributes()->all(), 'Feldkatalog unverändert: '.$template->name);
$this->assertSame($groupsBefore, InquiryFieldGroup::query()->get()->map->getAttributes()->all(), 'Feldgruppen unverändert: '.$template->name);
}
}
public function test_the_example_courses_form_shows_its_conditions_at_the_elements_and_keeps_the_rest_as_rules(): void
{
$view = app(FormEditor::class)->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft);
$second = $view['areas'][1];
$this->assertSame('skip', $second['cond']['effect']);
$this->assertSame('unteranliegen', $second['cond']['conditions'][0]['source']);
$sections = collect($second['items'])->where('type', 'section')->keyBy('data.key');
$this->assertSame('show', $sections['traeger_angaben']['data']['cond']['effect']);
$this->assertSame('ja', $sections['traeger_angaben']['data']['cond']['conditions'][0]['values'][0]);
$fields = collect($view['areas'])->flatMap(fn (array $area) => $area['items'])->where('type', 'field')->keyBy('data.key');
$this->assertSame('show', $fields['schulart']['data']['cond']['effect'], 'Die erste Regel am Ziel erscheint am Feld.');
// Die zweite Regel desselben Ziels (Pflichtfeld, wenn …) bleibt als weitere Regel erhalten.
$this->assertCount(1, $view['rules']);
$this->assertSame('require', $view['rules'][0]['effect']);
$this->assertSame('field:schulart', $view['rules'][0]['target']);
}
public function test_new_fields_and_sections_are_created_in_the_catalog_and_the_form_publishes(): void
{
$editor = app(FormEditor::class);
$view = [
'issues' => [],
'rules' => [],
'areas' => [[
'key' => 'sabc123', 'title' => 'Ihre Angaben', 'intro' => null, 'cond' => [],
'items' => [
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Wie heißen Sie?', 'help' => 'Vor- und Nachname', 'type' => 'text', 'required' => true, 'purpose' => 'name', 'options' => [], 'cond' => []]],
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'E-Mail für Rückfragen', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
['type' => 'section', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Angaben zur Schule', 'description' => 'Nur für Schulen', 'cond' => []]],
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Welche Schulart?', 'type' => 'select', 'required' => false, 'purpose' => null, 'options' => [['key' => '', 'label' => 'Grundschule'], ['key' => '', 'label' => 'Gymnasium']], 'cond' => []]],
],
]],
];
$draft = $editor->persist($view);
$name = InquiryField::query()->where('label', 'Wie heißen Sie?')->firstOrFail();
$this->assertSame('wie_heissen_sie', $name->key);
$this->assertSame('name', $name->purpose->value);
$schule = InquiryField::query()->where('label', 'Welche Schulart?')->firstOrFail();
$this->assertSame(['grundschule', 'gymnasium'], array_column($schule->optionList(), 'key'));
$group = InquiryFieldGroup::query()->where('label', 'Angaben zur Schule')->firstOrFail();
$this->assertSame([['field' => $schule->key, 'required' => false]], $group->itemList());
$this->assertSame([
['kind' => 'field', 'field' => 'wie_heissen_sie', 'required' => true],
['kind' => 'field', 'field' => (string) InquiryField::query()->where('label', 'E-Mail für Rückfragen')->value('key'), 'required' => true],
['kind' => 'group', 'group' => $group->key],
], $draft['steps'][0]['items']);
$template = InquiryTemplate::query()->create(['key' => 'neu', 'name' => 'Neu', 'draft' => [...InquiryTemplate::emptyDraft(), ...$draft]]);
$result = app(TemplateCompiler::class)->compile((array) $template->draft);
$this->assertSame([], $result['errors']);
app(Publisher::class)->publishTemplate($template, null, null);
$this->assertTrue($template->fresh()->isPublished());
}
public function test_conditions_at_elements_become_engine_rules_in_document_order_with_keys_resolved(): void
{
$editor = app(FormEditor::class);
$ja = [['source' => 'traeger_abweichend', 'op' => 'eq', 'values' => ['ja']]];
$view = [
'issues' => [], 'rules' => [],
'areas' => [
['key' => 'sa1', 'title' => 'Eins', 'intro' => null, 'cond' => [], 'items' => [
['type' => 'field', 'data' => ['key' => 'traeger_abweichend', 'label' => 'Abweichender Träger?', 'type' => 'boolean', 'required' => false, 'options' => [], 'cond' => []]],
['type' => 'field', 'data' => ['key' => 'email', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
]],
['key' => 'sa2', 'title' => 'Zwei', 'intro' => null, 'cond' => ['effect' => 'show', 'match' => 'all', 'conditions' => $ja], 'items' => [
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Name des Trägers', 'type' => 'text', 'required' => true, 'options' => [], 'cond' => ['effect' => 'require', 'match' => 'all', 'conditions' => $ja]]],
]],
],
];
$draft = $editor->persist($view);
$this->assertSame([
['effect' => 'require', 'target' => 'field:name_des_traegers', 'match' => 'all', 'conditions' => $ja, 'value' => null],
['effect' => 'show', 'target' => 'step:sa2', 'match' => 'all', 'conditions' => $ja, 'value' => null],
], $draft['rules']);
$template = InquiryTemplate::query()->create(['key' => 'bedingt', 'name' => 'Bedingt', 'draft' => [...InquiryTemplate::emptyDraft(), ...$draft]]);
$this->assertSame([], app(TemplateCompiler::class)->compile((array) $template->draft)['errors']);
}
public function test_an_existing_field_keeps_its_key_and_type_and_options_keep_their_keys_when_renamed(): void
{
$editor = app(FormEditor::class);
$view = $editor->expand((array) InquiryTemplate::query()->where('key', 'allgemein')->firstOrFail()->draft);
$found = false;
foreach ($view['areas'] as &$area) {
foreach ($area['items'] as &$block) {
if ($block['type'] === 'field' && $block['data']['key'] === 'nachricht') {
$block['data']['label'] = 'Was möchten Sie uns mitteilen?';
$block['data']['type'] = 'text';
$found = true;
}
}
}
unset($area, $block);
$this->assertTrue($found);
$editor->persist($view);
$field = InquiryField::query()->where('key', 'nachricht')->firstOrFail();
$this->assertSame('Was möchten Sie uns mitteilen?', $field->label);
$this->assertSame('textarea', $field->type->value, 'Der Feldtyp eines vorhandenen Feldes ändert sich nicht.');
$options = InquiryField::query()->where('key', 'kursformat')->firstOrFail()->optionList();
$view = $editor->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft);
foreach ($view['areas'] as &$area) {
foreach ($area['items'] as &$block) {
if ($block['type'] === 'field' && $block['data']['key'] === 'kursformat') {
$block['data']['options'][0]['label'] = 'Umbenannt';
}
}
}
unset($area, $block);
$editor->persist($view);
$renamed = InquiryField::query()->where('key', 'kursformat')->firstOrFail()->optionList();
$this->assertSame($options[0]['key'], $renamed[0]['key']);
$this->assertSame('Umbenannt', $renamed[0]['label']);
}
private function staff(): User
{
$user = User::factory()->redakteur()->create();
$user->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $user;
}
private function emptyForm(string $key): InquiryTemplate
{
return InquiryTemplate::query()->create(['key' => $key, 'name' => ucfirst($key), 'draft' => [...InquiryTemplate::emptyDraft(), 'steps' => [['key' => 'sstart1', 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]]]]);
}
public function test_a_form_is_built_in_the_editor_saved_twice_without_duplicates_and_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('frisch');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areas = $component->get('data.editor.areas');
$this->assertCount(1, $areas);
$areaId = array_key_first($areas);
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Rufname', 'type' => 'text', 'required' => true, 'purpose' => 'name', 'options' => [], 'cond' => []]],
'b' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihre Mailadresse zur Antwort', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
])->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$draft = $template->fresh()->draft;
$this->assertSame(['ihr_rufname', 'ihre_mailadresse_zur_antwort'], array_column($draft['steps'][0]['items'], 'field'));
// Ein zweites Speichern legt nichts doppelt an, weil die Ansicht nach dem Speichern die festen Kennungen trägt.
$component->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$this->assertSame($draft, $template->fresh()->draft);
$component->callAction('check')->assertNotified('Die Konfiguration ist in Ordnung.');
$component->callAction('publish', ['note' => 'Erste Fassung'])->assertHasNoActionErrors();
$this->assertTrue($template->fresh()->isPublished());
}
public function test_an_invalid_form_is_not_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('ohnemail');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areaId = array_key_first($component->get('data.editor.areas'));
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Name', 'type' => 'text', 'required' => true, 'options' => [], 'cond' => []]],
])->call('save');
$component->callAction('publish', ['note' => null]);
$this->assertFalse($template->fresh()->isPublished());
}
public function test_the_navigation_offers_forms_for_editors_and_the_technical_blocks_stay_reachable(): void
{
$this->actingAs($this->staff(), 'staff');
$html = $this->get('/verwaltung')->assertOk()->getContent();
$this->assertStringContainsString('Formulare &amp; Befragungen', $html);
$this->assertStringNotContainsString('Feldkatalog', $html);
$this->assertStringNotContainsString('Anfrage-Einstiege', $html);
$this->assertStringNotContainsString('Feldgruppen', $html);
$this->get('/verwaltung/kommunikation/felder')->assertOk();
$this->get('/verwaltung/kommunikation/anliegen')->assertOk();
}
public function test_the_usage_in_other_forms_is_reported(): void
{
$usage = app(FormEditor::class)->usage();
$this->assertContains('Allgemeine Kontaktaufnahme', $usage['fields']['email']);
$this->assertGreaterThan(1, count($usage['fields']['email']));
}
}
+14 -6
View File
@@ -165,10 +165,11 @@ public function test_the_widget_mounts_a_published_entry_on_two_pages_without_an
$this->assertStringNotContainsString('nachricht', $html);
}
// Die Revision enthält nur die Kennung.
// Die Revision enthält nur die Kennung des Einstiegs (Seiten der ersten Fassung); das Widget kennt seit ADR-61
// zusätzlich Anfragegründe, hier leer.
$blocks = Page::query()->where('path', '/kontakt')->firstOrFail()->publishedRevision->blocks;
$this->assertSame(['entry' => $entry->id], $blocks[0]['refs']);
$this->assertSame([], $blocks[0]['data']);
$this->assertSame([], $blocks[0]['data']['reasons']);
}
public function test_a_central_change_reaches_every_page_without_touching_the_pages(): void
@@ -233,14 +234,21 @@ public function test_the_notification_link_is_built_from_the_web_request_not_ins
Queue::assertPushed(SendInquiryNotification::class, fn ($job): bool => str_starts_with((string) $job->adminUrl, 'http://anfrage-test.example:3011/verwaltung/anfragen/'));
}
public function test_the_widget_offers_nothing_but_the_entry_choice_in_the_cms(): void
public function test_the_widget_offers_reasons_and_presentation_but_never_form_content_in_the_cms(): void
{
// Geändert mit ADR-61: Das Widget wählt Anfragegründe (Formular je Grund) und die Darstellung, nicht mehr einen
// Einstieg. Felder, Bedingungen, Texte und Empfänger bleiben der Kommunikationsverwaltung vorbehalten.
$type = app(WidgetRegistry::class)->get('inquiry');
$this->assertSame([], $type->dataRules());
$this->assertSame([], $type->dataFields());
$this->assertSame(['reasons', 'question', 'open_label'], array_map(fn ($field): string => $field->getName(), $type->dataFields()));
$this->assertSame(['entry'], array_keys($type->refRules()));
$this->assertSame([], $type->settings());
$this->assertSame(['mode', 'open', 'picker', 'width', 'spacing', 'columns', 'button'], array_keys($type->settings()));
$this->assertSame(['compact', 'wizard'], array_keys($type->settings()['mode']));
$this->assertSame(['inline', 'modal'], array_keys($type->settings()['open']));
foreach (array_keys($type->dataRules()) as $rule) {
$this->assertMatchesRegularExpression('/^(reasons|question|open_label)/', $rule);
}
}
public function test_the_preview_of_a_page_shows_a_note_for_an_unpublished_entry(): void
+281
View File
@@ -0,0 +1,281 @@
<?php
namespace Tests\Feature;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Communication\ExampleConfiguration;
use App\Domain\Communication\FormToken;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
/**
* Widget „Anfrage“ (ADR-61): Anfragegründe zeigen auf veröffentlichte Formulare; der Besucher erhält genau das Formular
* seines Grundes, ohne Anfrage-Einstieg.
*/
class CommunicationWidgetTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
config(['communication.min_fill_seconds' => 0]);
Queue::fake();
app(ExampleConfiguration::class)->install();
}
private function template(string $key): InquiryTemplate
{
return InquiryTemplate::query()->where('key', $key)->firstOrFail();
}
/**
* @param list<array<string, mixed>> $reasons
* @param array<string, string> $settings
*/
private function page(string $path, array $reasons, array $settings = []): Page
{
$page = Page::query()->create(['path' => $path]);
$revision = app(PageService::class)->saveRevision($page, [[
'name' => 'Anfrage', 'anchor' => 'anfrage', 'layout' => 'u4',
'slots' => [['type' => 'inquiry', 'v' => 1, 'variant' => 'standard', 'settings' => $settings, 'data' => ['reasons' => $reasons], 'refs' => []]],
]], null, null, null);
app(PageService::class)->publish($page, $revision);
return $page->fresh();
}
/** @return array<string, mixed> */
private function reason(string $label, string $template, ?string $issue = null, ?string $sub = null): array
{
return ['key' => null, 'label' => $label, 'description' => null, 'template' => $this->template($template)->id, 'issue' => $issue, 'subissue' => $sub];
}
public function test_a_reason_delivers_exactly_its_form_with_the_issue_preselected(): void
{
$template = $this->template('kursanfragen');
$json = $this->getJson(route('inquiry.form.definition', $template).'?anliegen=kurse&unteranliegen=kursvorhaben&modus=wizard')->assertOk()->json();
$this->assertSame('wizard', $json['mode']);
$this->assertSame('Kursanfrage', $json['texts']['heading']);
$this->assertSame('kurse', $json['defaults']['anliegen']);
$this->assertSame('kursvorhaben', $json['defaults']['unteranliegen']);
$this->assertCount(1, $json['issues']);
$this->assertFalse($json['state']['fields']['anliegen'], 'Das Anliegen ist vorgewählt und wird nicht erneut gefragt.');
$this->assertTrue($json['state']['steps']['skurs2']);
$this->assertArrayNotHasKey('rules', $json);
$this->assertSame('form', FormToken::read($json['token'])['k']);
}
public function test_an_unknown_issue_restricts_nothing_and_an_invalid_mode_falls_back_to_the_compact_form(): void
{
$json = $this->getJson(route('inquiry.form.definition', $this->template('kursanfragen')).'?anliegen=gibtesnicht&modus=quatsch')->assertOk()->json();
$this->assertSame('compact', $json['mode']);
$this->assertArrayNotHasKey('anliegen', (array) $json['defaults']);
}
public function test_an_unpublished_or_archived_form_is_not_delivered(): void
{
$draft = InquiryTemplate::query()->create(['key' => 'entwurf', 'name' => 'Entwurf', 'draft' => InquiryTemplate::emptyDraft()]);
$this->getJson(route('inquiry.form.definition', $draft))->assertNotFound();
$this->postJson(route('inquiry.form.state', $draft), ['values' => []])->assertNotFound();
$this->postJson(route('inquiry.form.submit', $draft), ['values' => [], 'token' => 'x'])->assertStatus(419);
$published = $this->template('allgemein');
$published->forceFill(['archived_at' => now()])->save();
$this->getJson(route('inquiry.form.definition', $published))->assertNotFound();
}
public function test_the_server_evaluates_the_state_for_the_chosen_reason(): void
{
$template = $this->template('kursanfragen');
$url = route('inquiry.form.state', $template).'?anliegen=kurse';
$info = $this->postJson($url, ['values' => ['unteranliegen' => 'kursinfo']])->assertOk()->json();
$this->assertFalse($info['steps']['skurs2']);
$project = $this->postJson($url, ['values' => ['unteranliegen' => 'kursvorhaben']])->assertOk()->json();
$this->assertTrue($project['steps']['skurs2']);
}
public function test_a_submission_is_stored_without_an_entry_and_points_to_the_form_version(): void
{
$template = $this->template('allgemein');
$definition = $this->getJson(route('inquiry.form.definition', $template).'?anliegen=allgemein')->assertOk()->json();
$this->postJson(route('inquiry.form.submit', $template).'?anliegen=allgemein', [
'token' => $definition['token'],
'source' => '/kontakt',
'values' => ['name' => 'Mira Beispiel', 'email' => 'mira@example.org', 'nachricht' => 'Hallo!'],
])->assertCreated()->assertJsonStructure(['reference']);
$inquiry = Inquiry::query()->firstOrFail();
$this->assertNull($inquiry->entry_id);
$this->assertSame($template->publishedVersion->id, $inquiry->template_version_id);
$this->assertSame('allgemein', $inquiry->issue_key);
$this->assertSame('/kontakt', $inquiry->source_path);
$this->assertSame('Formular „Allgemeine Kontaktaufnahme“', $inquiry->channelTitle());
}
public function test_the_submission_is_validated_like_every_other_inquiry(): void
{
$template = $this->template('allgemein');
$definition = $this->getJson(route('inquiry.form.definition', $template).'?anliegen=allgemein')->json();
$this->postJson(route('inquiry.form.submit', $template).'?anliegen=allgemein', [
'token' => $definition['token'],
'values' => ['name' => 'Mira', 'email' => 'keine-adresse', 'unbekannt' => 'x'],
])->assertStatus(422);
$this->assertSame(0, Inquiry::query()->count());
}
public function test_tokens_of_entries_and_forms_are_not_interchangeable(): void
{
$template = $this->template('allgemein');
$version = $template->publishedVersion;
$entry = $template->entries()->firstOrFail();
$entryToken = FormToken::issue($entry->id, $version->id);
$this->postJson(route('inquiry.form.submit', $template), ['token' => $entryToken, 'values' => []])->assertStatus(419);
$formToken = FormToken::issue($template->id, $version->id, 'form');
$this->postJson(route('inquiry.submit', $entry), ['token' => $formToken, 'values' => []])->assertStatus(419);
$other = $this->template('kursanfragen');
$this->postJson(route('inquiry.form.submit', $other), ['token' => $formToken, 'values' => []])->assertStatus(419);
}
public function test_the_page_carries_only_the_reasons_whose_form_is_published(): void
{
$page = $this->page('/kontakt', [
$this->reason('Allgemeine Anfrage', 'allgemein', 'allgemein'),
$this->reason('Kurse & Workshops', 'kursanfragen', 'kurse'),
$this->reason('Material', 'materialanfragen', 'materialien'),
], ['mode' => 'wizard', 'open' => 'modal', 'picker' => 'select', 'width' => 'wide', 'spacing' => 'airy', 'columns' => 'one', 'button' => 'outline']);
$this->template('materialanfragen')->forceFill(['archived_at' => now()])->save();
$html = $this->get('/kontakt')->assertOk()->getContent();
$this->assertStringContainsString('data-inquiry-widget', $html);
$this->assertStringContainsString('iw-width-wide iw-spacing-airy iw-cols-one iw-btn-outline', $html);
preg_match("/data-config='([^']+)'/", $html, $match);
$config = json_decode(html_entity_decode($match[1]), true);
$this->assertSame('modal', $config['open']);
$this->assertSame('select', $config['picker']);
$this->assertSame('Worum geht es?', $config['question']);
$this->assertSame('Anfrage stellen', $config['openLabel']);
$this->assertSame(['allgemeine_anfrage', 'kurse_workshops'], array_column($config['reasons'], 'key'));
$this->assertStringContainsString('anliegen=kurse', $config['reasons'][1]['definitionUrl']);
$this->assertStringContainsString('modus=wizard', $config['reasons'][1]['submitUrl']);
$this->assertStringContainsString('/anfrage/formular/'.$this->template('kursanfragen')->id, $config['reasons'][1]['stateUrl']);
$this->assertStringNotContainsString('rules', $match[1]);
}
public function test_a_page_without_any_available_form_shows_nothing_publicly_but_explains_it_in_the_preview(): void
{
$page = $this->page('/kontakt', [$this->reason('Allgemeine Anfrage', 'allgemein')]);
$this->template('allgemein')->forceFill(['archived_at' => now()])->save();
$this->assertStringNotContainsString('data-inquiry-widget', $this->get('/kontakt')->assertOk()->getContent());
$type = app(WidgetRegistry::class)->get('inquiry');
$widget = ['data' => ['reasons' => [$this->reason('Allgemeine Anfrage', 'allgemein')]], 'refs' => [], 'settings' => []];
$preview = $type->resolve($widget, RenderContext::preview());
$this->assertNull($preview['config']);
$this->assertSame(['Allgemeine Anfrage'], $preview['unavailable']);
}
public function test_pages_of_the_first_version_with_an_entry_are_still_rendered(): void
{
$entry = $this->template('allgemein')->entries()->firstOrFail();
$page = Page::query()->create(['path' => '/alt']);
$revision = app(PageService::class)->saveRevision($page, [[
'name' => 'Anfrage', 'anchor' => 'anfrage', 'layout' => 'u4',
'slots' => [['type' => 'inquiry', 'v' => 1, 'variant' => 'standard', 'data' => [], 'refs' => ['entry' => $entry->id]]],
]], null, null, null);
app(PageService::class)->publish($page, $revision);
$html = $this->get('/alt')->assertOk()->getContent();
$this->assertStringContainsString('data-definition-url="'.route('inquiry.definition', $entry).'"', $html);
$this->assertStringNotContainsString('data-inquiry-widget', $html);
}
public function test_reasons_get_stable_keys_and_a_widget_needs_at_least_one_reason(): void
{
$type = app(WidgetRegistry::class)->get('inquiry');
$errors = new WidgetErrors;
[$data] = $type->clean(['reasons' => [
['label' => 'Kurse & Workshops', 'template' => 1, 'issue' => 'kurse', 'subissue' => 'kursinfo'],
['key' => 'kurse_workshops', 'label' => 'Kurse & Workshops', 'template' => 1],
['label' => 'Kooperation', 'template' => 1, 'subissue' => 'unsinn'],
]], [], $errors);
$this->assertSame(['kurse_workshops', 'kurse_workshops_2', 'kooperation'], array_column($data['reasons'], 'key'));
$this->assertNull($data['reasons'][2]['subissue'], 'Ein Unteranliegen ohne Anliegen wird nicht gespeichert.');
$this->assertTrue($errors->isEmpty());
$empty = new WidgetErrors;
$type->clean(['reasons' => []], [], $empty);
$this->assertArrayHasKey('data.reasons', $empty->all());
$legacy = new WidgetErrors;
$type->clean(['reasons' => []], ['entry' => 3], $legacy);
$this->assertTrue($legacy->isEmpty());
}
public function test_a_page_can_be_saved_while_its_form_gets_withdrawn_later(): void
{
$template = $this->template('materialanfragen');
$page = $this->page('/material', [$this->reason('Material', 'materialanfragen')]);
$template->forceFill(['archived_at' => now()])->save();
$revision = app(PageService::class)->saveRevision($page, [[
'name' => 'Anfrage', 'anchor' => 'anfrage', 'layout' => 'u4',
'slots' => [['type' => 'inquiry', 'v' => 1, 'variant' => 'standard', 'settings' => [], 'data' => ['reasons' => [$this->reason('Material', 'materialanfragen')]], 'refs' => []]],
]], null, null, null);
$this->assertNotNull($revision->id);
}
public function test_a_step_can_be_shown_or_hidden_like_a_group(): void
{
$draft = [
'texts' => [], 'issues' => [],
'steps' => [
['key' => 'sa', 'title' => 'Kontakt', 'intro' => null, 'items' => [
['kind' => 'field', 'field' => 'nachricht', 'required' => false],
['kind' => 'field', 'field' => 'email', 'required' => true],
['kind' => 'field', 'field' => 'kursformat', 'required' => false],
]],
['key' => 'sb', 'title' => 'Schulangaben', 'intro' => null, 'items' => [['kind' => 'field', 'field' => 'region', 'required' => false]]],
],
'rules' => [['effect' => 'show', 'target' => 'step:sb', 'match' => 'all', 'conditions' => [['source' => 'kursformat', 'op' => 'eq', 'values' => ['schul_ag']]], 'value' => null]],
];
$template = InquiryTemplate::query()->create(['key' => 'schritte', 'name' => 'Schritte', 'draft' => $draft]);
app(Publisher::class)->publishTemplate($template, null, null);
$off = $this->postJson(route('inquiry.form.state', $template), ['values' => ['kursformat' => 'workshop']])->assertOk()->json();
$on = $this->postJson(route('inquiry.form.state', $template), ['values' => ['kursformat' => 'schul_ag']])->assertOk()->json();
$this->assertFalse($off['steps']['sb']);
$this->assertFalse($off['fields']['region']);
$this->assertTrue($on['steps']['sb']);
$this->assertTrue($on['fields']['region']);
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
input: ['resources/css/app.css', 'resources/js/app.js', 'resources/js/inquiry-embed.js'],
refresh: true,
fonts: [
// Vorläufige Markenschriften (Website-Zielkonzept 7.2, nicht freigegeben); beim Build lokal abgelegt.