diff --git a/app/Domain/Cms/Widgets/Types/InquiryWidget.php b/app/Domain/Cms/Widgets/Types/InquiryWidget.php index 4a6ae72..1fa8180 100644 --- a/app/Domain/Cms/Widgets/Types/InquiryWidget.php +++ b/app/Domain/Cms/Widgets/Types/InquiryWidget.php @@ -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> + */ + 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 { - $id = $widget['refs']['entry'] ?? null; - $entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null; + $reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array')); - return ['entry' => $entry, 'entryLive' => $entry?->isLive() ?? false]; + if ($reasons === []) { + $id = $widget['refs']['entry'] ?? null; + $entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null; + + return ['legacy' => true, 'entry' => $entry, 'entryLive' => $entry?->isLive() ?? false, 'config' => null, 'unavailable' => []]; + } + + $templates = InquiryTemplate::query()->with('publishedVersion')->whereIn('id', array_unique(array_map(fn (array $r): int => (int) ($r['template'] ?? 0), $reasons)))->get()->keyBy('id'); + $settings = (array) ($widget['settings'] ?? []); + $mode = ($settings['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact'; + $live = []; + $unavailable = []; + + foreach ($reasons as $reason) { + $template = $templates[(int) ($reason['template'] ?? 0)] ?? null; + $label = (string) ($reason['label'] ?? ''); + + if ($template === null || $template->archived_at !== null || $template->publishedVersion === null) { + $unavailable[] = $label; + + continue; + } + + $query = array_filter([ + 'anliegen' => $reason['issue'] ?? null, + 'unteranliegen' => $reason['subissue'] ?? null, + 'modus' => $mode, + ], fn (mixed $value): bool => filled($value)); + $suffix = '?'.http_build_query($query); + + $live[] = [ + 'key' => (string) ($reason['key'] ?? ''), + 'label' => $label, + 'description' => $reason['description'] ?? null, + 'definitionUrl' => route('inquiry.form.definition', $template).$suffix, + 'stateUrl' => route('inquiry.form.state', $template).$suffix, + 'submitUrl' => route('inquiry.form.submit', $template).$suffix, + ]; + } + + $config = $live === [] ? null : [ + 'open' => ($settings['open'] ?? 'inline') === 'modal' ? 'modal' : 'inline', + 'picker' => ($settings['picker'] ?? 'cards') === 'select' ? 'select' : 'cards', + 'question' => filled($widget['data']['question'] ?? null) ? (string) $widget['data']['question'] : 'Worum geht es?', + 'openLabel' => filled($widget['data']['open_label'] ?? null) ? (string) $widget['data']['open_label'] : 'Anfrage stellen', + 'preview' => $context->preview, + 'reasons' => $live, + ]; + + return ['legacy' => false, 'entry' => null, 'entryLive' => false, 'config' => $config, 'unavailable' => $unavailable]; } public function summary(array $widget): string { - $id = $widget['refs']['entry'] ?? null; - $name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null; + $reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array')); - return $name !== null ? 'Anfrage: '.$name : 'Kein Anfrage-Einstieg gewählt'; + if ($reasons === []) { + $id = $widget['refs']['entry'] ?? null; + $name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null; + + return $name !== null ? 'Anfrage: '.$name : 'Kein Anfragegrund gewählt'; + } + + $labels = array_map(fn (array $reason): string => (string) ($reason['label'] ?? ''), $reasons); + $mode = ($widget['settings']['mode'] ?? 'compact') === 'wizard' ? 'mehrstufig' : 'langes Formular'; + $open = ($widget['settings']['open'] ?? 'inline') === 'modal' ? 'Dialog' : 'im Abschnitt'; + + return 'Anfrage: '.implode(', ', $labels).' ('.$mode.', '.$open.')'; + } + + /** + * @return array + */ + private static function templateOptions(): array + { + return InquiryTemplate::query()->whereNotNull('published_version_id')->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all(); + } + + /** + * @return array + */ + 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 + */ + 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 + */ + private static function definition(int $templateId): array + { + if ($templateId <= 0) { + return []; + } + + return (array) (InquiryTemplate::query()->with('publishedVersion')->find($templateId)?->publishedVersion?->definition ?? []); } } diff --git a/app/Domain/Communication/FormEvaluator.php b/app/Domain/Communication/FormEvaluator.php index d665d2e..5da1a0b 100644 --- a/app/Domain/Communication/FormEvaluator.php +++ b/app/Domain/Communication/FormEvaluator.php @@ -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) { diff --git a/app/Domain/Communication/FormReason.php b/app/Domain/Communication/FormReason.php new file mode 100644 index 0000000..25c541e --- /dev/null +++ b/app/Domain/Communication/FormReason.php @@ -0,0 +1,62 @@ + $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 $definition aufgelöste Fassung + * @param array $reason + * @return array + */ + 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; + } +} diff --git a/app/Domain/Communication/FormToken.php b/app/Domain/Communication/FormToken.php index b886b26..13e9e75 100644 --- a/app/Domain/Communication/FormToken.php +++ b/app/Domain/Communication/FormToken.php @@ -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']]; } } diff --git a/app/Domain/Communication/Inquiry.php b/app/Domain/Communication/Inquiry.php index ee354bd..bb3cdf6 100644 --- a/app/Domain/Communication/Inquiry.php +++ b/app/Domain/Communication/Inquiry.php @@ -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'); diff --git a/app/Domain/Communication/InquiryService.php b/app/Domain/Communication/InquiryService.php index a2fadb0..a5214ae 100644 --- a/app/Domain/Communication/InquiryService.php +++ b/app/Domain/Communication/InquiryService.php @@ -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, 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 $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, version: InquiryTemplateVersion}|null) $deliver + * @param array $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, diff --git a/app/Domain/Communication/TemplateCompiler.php b/app/Domain/Communication/TemplateCompiler.php index 5ef2dd2..ad1c4fc 100644 --- a/app/Domain/Communication/TemplateCompiler.php +++ b/app/Domain/Communication/TemplateCompiler.php @@ -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, diff --git a/app/Filament/Resources/Communication/Inquiries/InquiryResource.php b/app/Filament/Resources/Communication/Inquiries/InquiryResource.php index 587e52f..c3d8de5 100644 --- a/app/Filament/Resources/Communication/Inquiries/InquiryResource.php +++ b/app/Filament/Resources/Communication/Inquiries/InquiryResource.php @@ -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(), diff --git a/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php b/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php index 6f9f185..ee4dcbf 100644 --- a/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php +++ b/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php @@ -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', diff --git a/app/Http/Controllers/InquiryFormController.php b/app/Http/Controllers/InquiryFormController.php index 85948b0..04031e3 100644 --- a/app/Http/Controllers/InquiryFormController.php +++ b/app/Http/Controllers/InquiryFormController.php @@ -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 $data */ diff --git a/resources/css/components/lf-anfrage.css b/resources/css/components/lf-anfrage.css index 9c6af39..3b069da 100644 --- a/resources/css/components/lf-anfrage.css +++ b/resources/css/components/lf-anfrage.css @@ -448,3 +448,285 @@ @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) var(--space-5) 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); +} + +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; + } +} diff --git a/resources/js/app.js b/resources/js/app.js index ce561e0..37ee7ee 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -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) { diff --git a/resources/js/inquiry-form.js b/resources/js/inquiry-form.js index e0dacb6..eab963f 100644 --- a/resources/js/inquiry-form.js +++ b/resources/js/inquiry-form.js @@ -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 }), diff --git a/resources/js/inquiry-widget.js b/resources/js/inquiry-widget.js new file mode 100644 index 0000000..a902d4a --- /dev/null +++ b/resources/js/inquiry-widget.js @@ -0,0 +1,302 @@ +/* + * 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'; + } + + 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.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'); + 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(); +} diff --git a/resources/views/widgets/inquiry.blade.php b/resources/views/widgets/inquiry.blade.php index 846177d..bdab325 100644 --- a/resources/views/widgets/inquiry.blade.php +++ b/resources/views/widgets/inquiry.blade.php @@ -1,19 +1,41 @@ @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 ($entryLive) - -@elseif ($context->preview) -

- @if ($entry === null) - Der gewählte Anfrage-Einstieg existiert nicht mehr. Öffentlich erscheint an dieser Stelle nichts. - @else - Der Anfrage-Einstieg „{{ $entry->name }}“ ist nicht veröffentlicht oder seine Vorlage hat keine gültige Fassung. Öffentlich erscheint an dieser Stelle nichts. - @endif -

+@if ($legacy) + @if ($entryLive) + + @elseif ($context->preview) +

+ @if ($entry === null) + Der gewählte Anfrage-Einstieg existiert nicht mehr. Öffentlich erscheint an dieser Stelle nichts. + @else + Der Anfrage-Einstieg „{{ $entry->name }}“ ist nicht veröffentlicht oder seine Vorlage hat keine gültige Fassung. Öffentlich erscheint an dieser Stelle nichts. + @endif +

+ @endif +@else + @if ($config !== null) + {{-- Das Formular, die Bedingungen und das Token kommen zur Laufzeit vom Server (resources/js/inquiry-widget.js). --}} +
+

Das Anfrageformular wird geladen …

+ +
+ @endif + @if ($context->preview && $unavailable !== []) +

+ Nicht angeboten, weil das Formular nicht veröffentlicht oder archiviert ist: {{ implode(', ', $unavailable) }}. + @if ($config === null) Öffentlich erscheint an dieser Stelle nichts. @endif +

+ @endif @endif diff --git a/routes/web.php b/routes/web.php index c6d91a5..de208cb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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'); diff --git a/tests/Feature/CommunicationPublicTest.php b/tests/Feature/CommunicationPublicTest.php index c5328e1..2fe234b 100644 --- a/tests/Feature/CommunicationPublicTest.php +++ b/tests/Feature/CommunicationPublicTest.php @@ -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 diff --git a/tests/Feature/CommunicationWidgetTest.php b/tests/Feature/CommunicationWidgetTest.php new file mode 100644 index 0000000..073d702 --- /dev/null +++ b/tests/Feature/CommunicationWidgetTest.php @@ -0,0 +1,281 @@ + 0]); + Queue::fake(); + app(ExampleConfiguration::class)->install(); + } + + private function template(string $key): InquiryTemplate + { + return InquiryTemplate::query()->where('key', $key)->firstOrFail(); + } + + /** + * @param list> $reasons + * @param array $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 */ + 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']); + } +}