diff --git a/app/Console/Commands/PurgeInquiries.php b/app/Console/Commands/PurgeInquiries.php new file mode 100644 index 0000000..0bf7dba --- /dev/null +++ b/app/Console/Commands/PurgeInquiries.php @@ -0,0 +1,43 @@ +retention_months; + + if ($months === null || $months < 1) { + $this->info('Keine Aufbewahrungsdauer eingestellt; es wird nichts gelöscht.'); + + return self::SUCCESS; + } + + $query = Inquiry::query()->where('created_at', '<', now()->subMonths($months)); + $count = $query->count(); + + if ($this->option('pretend')) { + $this->info("$count Anfragen wären älter als $months Monate."); + + return self::SUCCESS; + } + + $query->delete(); + $this->info("$count Anfragen gelöscht (älter als $months Monate)."); + + return self::SUCCESS; + } +} diff --git a/app/Domain/Cms/Widgets/Types/InquiryWidget.php b/app/Domain/Cms/Widgets/Types/InquiryWidget.php new file mode 100644 index 0000000..36c3891 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/InquiryWidget.php @@ -0,0 +1,352 @@ + 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art und Karten stehen bei viel Platz nebeneinander']; + } + + public function schematic(): array + { + return [[6, 4, 24, 3, 'ink'], [6, 10, 22, 6, 'line'], [32, 10, 22, 6, 'line'], [6, 20, 48, 5, 'line'], [6, 28, 18, 5, 'accent']]; + } + + /** + * Formularführung und Präsentation sind unabhängig: Jede Kombination ist zulässig. + * + * @return array> + */ + public function settings(): array + { + return [ + 'mode' => ['compact' => 'Langes Formular', 'wizard' => 'Mehrstufig, Schritt für Schritt'], + 'open' => ['inline' => 'Im Abschnitt', 'modal' => 'Im Pop-up-Fenster über der Seite'], + 'picker' => ['cards' => 'Karten', 'select' => 'Auswahlfeld'], + 'width' => ['normal' => 'Standard', 'narrow' => 'Schmal', 'wide' => 'Breit'], + 'spacing' => ['normal' => 'Standard', 'compact' => 'Kompakt', 'airy' => 'Großzügig'], + 'columns' => ['auto' => 'Automatisch', 'one' => 'Immer eine Spalte'], + 'button' => ['solid' => 'Gefüllt', 'outline' => 'Umrandet'], + ]; + } + + public function settingLabels(): array + { + return [ + 'mode' => ['Formularführung', 'Wie das Formular aufgebaut ist, nicht wo es steht. Langes Formular: alle Bereiche stehen untereinander, bedingte Felder erscheinen je nach Eingabe. Mehrstufig: die Bereiche werden Schritt für Schritt mit Fortschrittsanzeige durchlaufen. Ob das Formular im Abschnitt oder in einem Pop-up-Fenster erscheint, legt „Präsentation“ fest. Vorgabe: Langes Formular.'], + 'open' => ['Präsentation', 'Wo das Formular erscheint, unabhängig von „Formularführung“. Im Abschnitt: das Formular steht direkt auf der Seite. Im Pop-up-Fenster: ein Button öffnet das Formular in einem Fenster über der Seite; auf dem Smartphone füllt es den Bildschirm. Vorgabe: Im Abschnitt.'], + 'picker' => ['Auswahl des Anfragegrundes', 'Karten zeigen die Gründe mit Beschreibung nebeneinander, das Auswahlfeld braucht wenig Platz. Bei nur einem Grund entfällt die Auswahl. Vorgabe: Karten.'], + 'width' => ['Breite des Formulars', 'Vorgabe: Standard. Das Formular nutzt höchstens die Breite des Platzes.'], + 'spacing' => ['Abstände', 'Abstand zwischen den Feldern. Vorgabe: Standard.'], + 'columns' => ['Anordnung der Felder', 'Automatisch: Felder gleicher Art (zum Beispiel Vor- und Nachname) stehen bei viel Platz nebeneinander. Vorgabe: Automatisch.'], + 'button' => ['Buttondarstellung', 'Gilt für den Button, der das Pop-up-Fenster öffnet, und für „Weiter“ und „Absenden“. Vorgabe: Gefüllt.'], + ]; + } + + public function settingGroups(): array + { + return [ + 'Formularführung und Präsentation' => ['mode', 'open'], + 'Gestaltung' => ['picker', 'width', 'spacing', 'columns', 'button'], + ]; + } + + public function dataRules(): array + { + return [ + // Nur die Existenz: Eine später zurückgezogene Vorlage darf eine Seite nicht unspeicherbar machen. Öffentlich + // erscheint ein Grund nur, solange sein Formular veröffentlicht ist (resolve()). + 'reasons' => ['nullable', 'array', 'max:'.self::MAX_REASONS], + 'reasons.*.key' => ['nullable', 'string', 'max:60'], + 'reasons.*.label' => ['required', 'string', 'max:80'], + 'reasons.*.description' => ['nullable', 'string', 'max:200'], + 'reasons.*.template' => ['required', 'integer', Rule::exists('inquiry_templates', 'id')], + 'reasons.*.issue' => ['nullable', 'string', 'max:60'], + 'reasons.*.subissue' => ['nullable', 'string', 'max:60'], + 'question' => ['nullable', 'string', 'max:160'], + 'open_label' => ['nullable', 'string', 'max:60'], + ]; + } + + public function dataFields(): array + { + return [ + Repeater::make('reasons') + ->label('Anfragegründe') + ->helperText('Diese Gründe bietet die Seite an. Wählt der Besucher einen Grund, erscheint genau das zugeordnete Formular. Bei nur einem Grund entfällt die Auswahl. Ein Button kann einen Grund vorwählen: Adresse der Seite mit „?grund=Kennung“ (die Kennung steht unter dem Grund).') + ->schema([ + Hidden::make('key'), + TextInput::make('label')->label('Bezeichnung für Besucher')->required()->maxLength(80)->placeholder('Zum Beispiel: Kurse & Workshops'), + Textarea::make('description')->label('Kurzbeschreibung (optional)')->rows(2)->maxLength(200)->helperText('Erscheint auf der Karte unter der Bezeichnung.'), + Select::make('template')->label('Formular')->required()->searchable()->live() + ->options(fn (): array => self::templateOptions()) + ->afterStateUpdated(function (Set $set): void { + $set('issue', null); + $set('subissue', null); + }) + ->helperText('Nur veröffentlichte Formulare stehen zur Auswahl. Inhalt, Felder und Bedingungen pflegst du unter „Kommunikation → Formulare & Befragungen“.'), + Select::make('issue')->label('Anliegen im Formular vorwählen (optional)')->live() + ->options(fn (Get $get): array => self::issueOptions((int) $get('template'))) + ->placeholder('Keines: das Formular fragt selbst') + ->visible(fn (Get $get): bool => self::issueOptions((int) $get('template')) !== []) + ->afterStateUpdated(fn (Set $set) => $set('subissue', null)) + ->helperText('Mehrere Gründe können dasselbe Formular nutzen und sich im Anliegen unterscheiden. Die Frage nach dem Anliegen entfällt dann.'), + Select::make('subissue')->label('Unteranliegen vorwählen (optional)') + ->options(fn (Get $get): array => self::subissueOptions((int) $get('template'), (string) $get('issue'))) + ->placeholder('Keines') + ->visible(fn (Get $get): bool => filled($get('issue')) && self::subissueOptions((int) $get('template'), (string) $get('issue')) !== []), + Text::make(fn (Get $get): string => filled($get('key')) ? 'Kennung für Links: grund='.$get('key') : 'Die Kennung für Links entsteht beim Speichern.'), + ]) + ->minItems(1) + ->maxItems(self::MAX_REASONS) + ->reorderableWithButtons() + ->collapsible() + ->addActionLabel('Anfragegrund hinzufügen') + ->itemLabel(fn (array $state): ?string => $state['label'] ?? null), + TextInput::make('question')->label('Frage zur Auswahl des Grundes')->maxLength(160)->placeholder('Worum geht es?') + ->helperText('Steht über der Auswahl, wenn mehr als ein Grund angeboten wird. Leer: „Worum geht es?“.'), + TextInput::make('open_label')->label('Beschriftung des Buttons (nur Pop-up-Fenster)')->maxLength(60)->placeholder('Anfrage stellen') + ->helperText('Erscheint nur bei der Präsentation „Im Pop-up-Fenster über der Seite“.'), + ]; + } + + public function refRules(): array + { + return [ + // Nur die Existenz (Seiten der ersten Fassung): Ein später zurückgezogener Einstieg darf eine Seite nicht unspeicherbar machen. + 'entry' => ['nullable', 'integer', Rule::exists('inquiry_entries', 'id')], + ]; + } + + public function refFields(): array + { + return [ + Select::make('entry') + ->label('Bisheriger Anfrage-Einstieg') + ->searchable() + ->options(fn (): array => InquiryEntry::query()->orderBy('name')->pluck('name', 'id')->all()) + ->visible(fn (Get $get): bool => filled($get('entry'))) + ->helperText('Diese Seite nutzt noch einen Anfrage-Einstieg der ersten Fassung. Er wird nur angezeigt, solange oben kein Anfragegrund eingetragen ist. Neue Seiten brauchen keinen Einstieg.'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + $reasons = []; + $taken = []; + + foreach (array_values((array) ($data['reasons'] ?? [])) as $reason) { + $reason = is_array($reason) ? $reason : []; + $key = Keys::valid($reason['key'] ?? null) && ! in_array($reason['key'], $taken, true) ? $reason['key'] : Keys::from((string) ($reason['label'] ?? ''), $taken); + $taken[] = $key; + $reasons[] = [ + 'key' => $key, + 'label' => trim((string) ($reason['label'] ?? '')), + 'description' => filled($reason['description'] ?? null) ? trim((string) $reason['description']) : null, + 'template' => (int) ($reason['template'] ?? 0), + 'issue' => filled($reason['issue'] ?? null) ? (string) $reason['issue'] : null, + 'subissue' => filled($reason['issue'] ?? null) && filled($reason['subissue'] ?? null) ? (string) $reason['subissue'] : null, + ]; + } + + $data['reasons'] = $reasons; + + if ($reasons === [] && ! filled($refs['entry'] ?? null)) { + $errors->add('data.reasons', 'Mindestens ein Anfragegrund ist nötig.'); + } + + return [$data, $refs]; + } + + public function resolve(array $widget, RenderContext $context): array + { + $reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array')); + + if ($reasons === []) { + $id = $widget['refs']['entry'] ?? null; + $entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null; + + return ['legacy' => true, 'entry' => $entry, 'entryLive' => $entry?->isLive() ?? false, 'config' => null, 'unavailable' => []]; + } + + $templates = InquiryTemplate::query()->with('publishedVersion')->whereIn('id', array_unique(array_map(fn (array $r): int => (int) ($r['template'] ?? 0), $reasons)))->get()->keyBy('id'); + $settings = (array) ($widget['settings'] ?? []); + $mode = ($settings['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact'; + $live = []; + $unavailable = []; + + foreach ($reasons as $reason) { + $template = $templates[(int) ($reason['template'] ?? 0)] ?? null; + $label = (string) ($reason['label'] ?? ''); + + if ($template === null || $template->archived_at !== null || $template->publishedVersion === null) { + $unavailable[] = $label; + + continue; + } + + $query = array_filter([ + 'anliegen' => $reason['issue'] ?? null, + 'unteranliegen' => $reason['subissue'] ?? null, + 'modus' => $mode, + ], fn (mixed $value): bool => filled($value)); + $suffix = '?'.http_build_query($query); + + $live[] = [ + 'key' => (string) ($reason['key'] ?? ''), + 'label' => $label, + 'description' => $reason['description'] ?? null, + 'definitionUrl' => route('inquiry.form.definition', $template).$suffix, + 'stateUrl' => route('inquiry.form.state', $template).$suffix, + 'submitUrl' => route('inquiry.form.submit', $template).$suffix, + ]; + } + + $config = $live === [] ? null : [ + 'open' => ($settings['open'] ?? 'inline') === 'modal' ? 'modal' : 'inline', + 'picker' => ($settings['picker'] ?? 'cards') === 'select' ? 'select' : 'cards', + 'question' => filled($widget['data']['question'] ?? null) ? (string) $widget['data']['question'] : 'Worum geht es?', + 'openLabel' => filled($widget['data']['open_label'] ?? null) ? (string) $widget['data']['open_label'] : 'Anfrage stellen', + 'preview' => $context->preview, + 'reasons' => $live, + ]; + + return ['legacy' => false, 'entry' => null, 'entryLive' => false, 'config' => $config, 'unavailable' => $unavailable]; + } + + public function summary(array $widget): string + { + $reasons = array_values(array_filter((array) ($widget['data']['reasons'] ?? []), 'is_array')); + + if ($reasons === []) { + $id = $widget['refs']['entry'] ?? null; + $name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null; + + return $name !== null ? 'Anfrage: '.$name : 'Kein Anfragegrund gewählt'; + } + + $labels = array_map(fn (array $reason): string => (string) ($reason['label'] ?? ''), $reasons); + $mode = ($widget['settings']['mode'] ?? 'compact') === 'wizard' ? 'mehrstufig' : 'langes Formular'; + $open = ($widget['settings']['open'] ?? 'inline') === 'modal' ? 'Pop-up' : 'im Abschnitt'; + + return 'Anfrage: '.implode(', ', $labels).' ('.$mode.', '.$open.')'; + } + + /** + * @return array + */ + 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/CommunicationAccess.php b/app/Domain/Communication/CommunicationAccess.php new file mode 100644 index 0000000..6dcc5f5 --- /dev/null +++ b/app/Domain/Communication/CommunicationAccess.php @@ -0,0 +1,44 @@ +user() ?? auth('staff')->user(); + + return $user instanceof User ? $user : null; + } + + public static function configure(?User $user = null): bool + { + $user ??= self::user(); + + return $user !== null && ($user->hasStaffRole(StaffRole::Redakteur) || $user->hasStaffRole(StaffRole::Systemverwalter)); + } + + public static function inbox(?User $user = null): bool + { + $user ??= self::user(); + + return $user !== null && ($user->hasStaffRole(StaffRole::Kundenbetreuung) || $user->hasStaffRole(StaffRole::Systemverwalter)); + } + + /** Anfragen endgültig löschen (Datenschutz): nur Systemverwaltung. */ + public static function erase(?User $user = null): bool + { + $user ??= self::user(); + + return $user !== null && $user->hasStaffRole(StaffRole::Systemverwalter); + } +} diff --git a/app/Domain/Communication/CommunicationSettings.php b/app/Domain/Communication/CommunicationSettings.php new file mode 100644 index 0000000..8bebe35 --- /dev/null +++ b/app/Domain/Communication/CommunicationSettings.php @@ -0,0 +1,35 @@ + 'array', 'retention_months' => 'integer']; + } + + public static function current(): self + { + return self::query()->first() ?? self::query()->create(['recipients' => []]); + } + + /** + * @return list + */ + public function recipientList(): array + { + return array_values(array_filter( + (array) $this->recipients, + fn (mixed $address): bool => is_string($address) && filter_var($address, FILTER_VALIDATE_EMAIL) !== false, + )); + } +} diff --git a/app/Domain/Communication/ExampleConfiguration.php b/app/Domain/Communication/ExampleConfiguration.php new file mode 100644 index 0000000..9ec15a5 --- /dev/null +++ b/app/Domain/Communication/ExampleConfiguration.php @@ -0,0 +1,268 @@ +exists() && ! InquiryField::query()->exists() && ! InquiryTemplate::query()->exists(); + } + + public function install(?User $by = null): void + { + if (! self::isEmpty()) { + throw new RuntimeException('Die Kommunikationsverwaltung enthält bereits Konfiguration; die Beispiele werden nicht daneben angelegt.'); + } + + DB::transaction(function () use ($by): void { + $this->issues(); + $this->fields(); + $this->groups(); + $templates = $this->templates(); + $this->entries($templates, $by); + }); + } + + private function issues(): void + { + $tree = [ + ['allgemein', 'Allgemeine Informationen', 'Allgemeine Fragen zu Lara & Felix, dem Trainingskonzept oder Sonstiges.', []], + ['kurse', 'Kurse & Workshops', 'Präsenzkurse und individuelle Kursvorhaben.', [ + ['kursinfo', 'Allgemeine Kursinformation', 'Ich möchte mich zunächst informieren.'], + ['kursvorhaben', 'Konkretes Kursvorhaben', 'Ich plane ein konkretes Kursvorhaben.'], + ]], + ['materialien', 'Programme & Materialien', 'Trainingsprogramme, Module, Filmgeschichten, Übungen, Materialien und Nutzungsrechte.', []], + ['kooperation', 'Kooperationen', 'Anfragen möglicher Trainer, Institutionen und anderer Kooperationspartner.', []], + ]; + + foreach ($tree as $i => [$key, $label, $description, $children]) { + $parent = InquiryIssue::query()->create(['key' => $key, 'label' => $label, 'description' => $description, 'sort_order' => ($i + 1) * 10]); + + foreach ($children as $j => [$childKey, $childLabel, $childDescription]) { + InquiryIssue::query()->create(['parent_id' => $parent->id, 'key' => $childKey, 'label' => $childLabel, 'description' => $childDescription, 'sort_order' => ($j + 1) * 10]); + } + } + } + + private function fields(): void + { + $text = fn (string $key, string $name, string $label, ?string $purpose = null, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'text', 'purpose' => $purpose, 'help' => $help]; + $select = fn (string $key, string $name, string $label, array $options, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'select', 'help' => $help, 'options' => array_map(fn (string $k, string $l): array => ['key' => $k, 'label' => $l], array_keys($options), $options)]; + $yesNo = fn (string $key, string $name, string $label): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'boolean']; + $number = fn (string $key, string $name, string $label, int $min = 1, int $max = 1000): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'number', 'settings' => ['min' => $min, 'max' => $max]]; + + $fields = [ + $text('name', 'Name (ein Feld)', 'Ihr Name', 'name'), + ['key' => 'email', 'name' => 'E-Mail-Adresse', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'purpose' => 'email'], + ['key' => 'nachricht', 'name' => 'Nachricht', 'label' => 'Ihre Nachricht', 'type' => 'textarea', 'purpose' => 'nachricht', 'help' => 'Bitte nennen Sie hier keine Namen oder persönlichen Daten einzelner Kinder.'], + $text('vorname', 'Vorname', 'Vorname', 'vorname'), + $text('nachname', 'Nachname', 'Nachname', 'nachname'), + ['key' => 'telefon', 'name' => 'Telefonnummer', 'label' => 'Telefonnummer (optional)', 'type' => 'phone', 'purpose' => 'telefon'], + $text('funktion', 'Funktion / Rolle', 'Ihre Funktion oder Rolle', null, 'Zum Beispiel Schulleitung, Lehrkraft, Vereinsvorstand.'), + $text('region', 'Region / Ort', 'Region oder Ort', null, 'Wo würde das Angebot stattfinden? Die Region genügt.'), + $text('einrichtung_name', 'Name der Einrichtung', 'Name der Schule oder Einrichtung', 'organisation'), + $select('einrichtungstyp', 'Einrichtungstyp', 'Einrichtungstyp', [ + 'grundschule' => 'Grundschule', 'weiterfuehrend' => 'Weiterführende Schule', 'verein' => 'Verein', + 'jugendeinrichtung' => 'Kinder- oder Jugendeinrichtung', 'bildungstraeger' => 'Sonstiger Bildungsträger', 'sonstiges' => 'Sonstiges', + ]), + $select('schulart', 'Schulart', 'Schulart', ['gs' => 'Grundschule', 'foerder' => 'Förderschule', 'gemeinschaft' => 'Gemeinschaftsschule', 'sek' => 'Sekundarschule', 'gym' => 'Gymnasium', 'andere' => 'Andere']), + $text('einrichtung_strasse', 'Straße und Hausnummer (Einrichtung)', 'Straße und Hausnummer'), + $text('einrichtung_plz', 'Postleitzahl (Einrichtung)', 'Postleitzahl'), + $text('einrichtung_ort', 'Ort (Einrichtung)', 'Ort'), + $yesNo('traeger_abweichend', 'Träger weicht von der Einrichtung ab', 'Weicht der Bildungsträger bzw. Auftraggeber von der Einrichtung ab?'), + $text('traeger_name', 'Name des Trägers', 'Name des Trägers oder Auftraggebers'), + $select('traeger_art', 'Art des Trägers', 'Art des Trägers', ['kommune' => 'Kommune oder Land', 'freier' => 'Freier Träger', 'verein' => 'Verein', 'sonstiges' => 'Sonstiges']), + $text('traeger_ansprechpartner', 'Ansprechpartner beim Träger', 'Ansprechpartner beim Träger (optional)'), + $yesNo('ort_abweichend', 'Abweichender Durchführungsort', 'Findet der Kurs an einem anderen Ort statt als in der Einrichtung?'), + $text('ort_strasse', 'Straße und Hausnummer (Durchführungsort)', 'Straße und Hausnummer des Durchführungsorts'), + $text('ort_plz', 'Postleitzahl (Durchführungsort)', 'Postleitzahl des Durchführungsorts'), + $text('ort_ort', 'Ort (Durchführungsort)', 'Ort des Durchführungsorts'), + ['key' => 'ort_hinweise', 'name' => 'Hinweise zum Durchführungsort', 'label' => 'Organisatorische Hinweise zum Ort (optional)', 'type' => 'textarea'], + $text('alter', 'Alter / Altersbereich', 'Alter oder Altersbereich der Kinder', null, 'Zum Beispiel 8 bis 10 Jahre.'), + $text('klassenstufe', 'Klassenstufe', 'Klassenstufe (falls zutreffend)'), + $number('anzahl_kinder', 'Anzahl der Kinder', 'Anzahl der Kinder insgesamt'), + $number('anzahl_gruppen', 'Anzahl der Gruppen oder Klassen', 'Anzahl der Gruppen oder Klassen', 1, 100), + ['key' => 'besonderheiten', 'name' => 'Organisatorische Anforderungen', 'label' => 'Besondere organisatorische Anforderungen (optional)', 'type' => 'textarea', 'help' => 'Bitte keine Angaben zu einzelnen Kindern.'], + $select('kursformat', 'Kursformat', 'Welches Format interessiert Sie?', [ + 'kompakt' => 'Kompakttraining', 'vertiefung' => 'Vertiefungsprogramm', 'schul_ag' => 'Schul-AG', 'unentschieden' => 'Noch unentschieden', + ], 'Kompakttraining: kurzes, individuell abgestimmtes Schultraining mit wenigen Terminen. Vertiefungsprogramm: mehrere aufeinander aufbauende Einheiten über einen längeren Zeitraum. Schul-AG: regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Die Formate sind Arbeitsvorschläge; Termine, Preise und Umfang werden erst im Gespräch festgelegt.'), + ['key' => 'zeitraum', 'name' => 'Geplanter Zeitraum', 'label' => 'Geplanter Zeitraum', 'type' => 'period'], + $text('zeitwuensche', 'Zeitwünsche', 'Zeitwünsche (optional)', null, 'Zum Beispiel Wochentage oder Tageszeiten.'), + $number('einheiten', 'Anzahl geplanter Einheiten', 'Anzahl geplanter Einheiten (optional)', 1, 200), + $select('haeufigkeit', 'Gewünschte Häufigkeit', 'Gewünschte Häufigkeit', ['woechentlich' => 'Einmal pro Woche', 'zweiwoechentlich' => 'Alle zwei Wochen', 'absprache' => 'Nach Absprache']), + $select('laufzeit', 'Laufzeit der Schul-AG', 'Gewünschte Laufzeit', ['halbjahr' => 'Ein Schulhalbjahr', 'schuljahr' => 'Ein Schuljahr', 'absprache' => 'Nach Absprache']), + ['key' => 'kurs_hinweise', 'name' => 'Ergänzende Informationen (Kurs)', 'label' => 'Ergänzende Informationen (optional)', 'type' => 'textarea'], + $select('material_interesse', 'Interesse an Materialien', 'Wofür interessieren Sie sich?', [ + 'programme' => 'Trainingsprogramme', 'module' => 'Module', 'filmgeschichten' => 'Filmgeschichten', 'uebungen' => 'Übungen', + 'materialien' => 'Materialien', 'rechte' => 'Nutzungsrechte', + ]), + $select('koop_art', 'Art der Kooperation', 'Wer sind Sie?', ['trainer' => 'Trainerin oder Trainer', 'institution' => 'Institution', 'sonstiges' => 'Sonstiges']), + $text('koop_organisation', 'Organisation (Kooperation)', 'Organisation (optional)', 'organisation'), + ]; + + foreach ($fields as $i => $field) { + InquiryField::query()->create([ + 'key' => $field['key'], + 'name' => $field['name'], + 'label' => $field['label'], + 'help' => $field['help'] ?? null, + 'type' => $field['type'], + 'options' => $field['options'] ?? null, + 'settings' => $field['settings'] ?? null, + 'purpose' => $field['purpose'] ?? null, + ]); + } + } + + private function groups(): void + { + $groups = [ + ['kontakt_einfach', 'Kontakt (einfach)', 'Ihre Kontaktdaten', [['name', true], ['email', true]]], + ['ansprechpartner', 'Ansprechpartner', 'Ihre Kontaktdaten', [['vorname', true], ['nachname', true], ['email', true], ['telefon', false], ['funktion', false]]], + ['einrichtung', 'Einrichtung', 'Ihre Einrichtung', [['einrichtung_name', true], ['einrichtungstyp', true], ['schulart', false], ['einrichtung_strasse', true], ['einrichtung_plz', true], ['einrichtung_ort', true]]], + ['traeger_frage', 'Träger', 'Bildungsträger oder Auftraggeber', [['traeger_abweichend', true]]], + ['traeger_angaben', 'Trägerangaben', 'Angaben zum Träger', [['traeger_name', true], ['traeger_art', false], ['traeger_ansprechpartner', false]]], + ['ort_frage', 'Durchführungsort', 'Wo soll der Kurs stattfinden?', [['ort_abweichend', true]]], + ['ort_angaben', 'Abweichender Durchführungsort', 'Adresse des Durchführungsorts', [['ort_strasse', true], ['ort_plz', true], ['ort_ort', true], ['ort_hinweise', false]]], + ['kindergruppe', 'Kindergruppe', 'Die Kindergruppe', [['alter', true], ['klassenstufe', false], ['anzahl_kinder', true], ['anzahl_gruppen', false], ['besonderheiten', false]]], + ['kursplanung', 'Kursplanung', 'Ihre Planung', [['zeitraum', false], ['zeitwuensche', false], ['einheiten', false], ['kurs_hinweise', false]]], + ['schul_ag', 'Schul-AG', 'Zur Schul-AG', [['laufzeit', true], ['haeufigkeit', true]]], + ['material', 'Programm- und Materialbezug', 'Ihr Interesse', [['material_interesse', true]]], + ['kooperation', 'Kooperation', 'Zu Ihrer Kooperationsanfrage', [['koop_art', true], ['koop_organisation', false]]], + ]; + + foreach ($groups as $i => [$key, $name, $label, $items]) { + InquiryFieldGroup::query()->create([ + 'key' => $key, + 'name' => $name, + 'label' => $label, + 'items' => array_map(fn (array $row): array => ['field' => $row[0], 'required' => $row[1]], $items), + 'sort_order' => ($i + 1) * 10, + ]); + } + } + + /** + * @return array + */ + private function templates(): array + { + $cond = fn (string $source, string $op, string ...$values): array => ['source' => $source, 'op' => $op, 'values' => $values]; + $rule = fn (string $effect, string $target, array $conditions, ?string $value = null): array => ['effect' => $effect, 'target' => $target, 'match' => 'all', 'conditions' => $conditions, 'value' => $value]; + $group = fn (string $key): array => ['kind' => 'group', 'group' => $key]; + + $general = [ + 'texts' => ['heading' => 'Schreiben Sie uns', 'intro' => 'Wir freuen uns über Ihre Frage.', 'success_text' => 'Danke, wir melden uns in der Regel innerhalb weniger Werktage.'], + 'issues' => ['allgemein'], + 'steps' => [['key' => 'sallg1', 'title' => 'Ihre Nachricht', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $courses = [ + 'texts' => [ + 'heading' => 'Kursanfrage', + 'intro' => 'Beschreiben Sie uns, was Sie planen. Alle Angaben sind unverbindlich; Termine, Preise und Umfang besprechen wir gemeinsam.', + 'privacy_note' => 'Wir verwenden Ihre Angaben ausschließlich, um Ihre Anfrage zu beantworten. Bitte nennen Sie keine Namen oder persönlichen Daten einzelner Kinder.', + 'success_text' => 'Wir haben Ihre Kursanfrage erhalten und melden uns bei Ihnen. Eine Buchung ist damit noch nicht verbunden.', + ], + 'issues' => ['kurse'], + 'steps' => [ + ['key' => 'skurs1', 'title' => 'Ihr Anliegen', 'intro' => null, 'items' => [['kind' => 'issue'], ['kind' => 'field', 'field' => 'kursformat', 'required' => false]]], + ['key' => 'skurs2', 'title' => 'Ihr Vorhaben', 'intro' => 'Einrichtung, Träger, Standort, Zielgruppe und Planung.', 'items' => [ + $group('einrichtung'), $group('traeger_frage'), $group('traeger_angaben'), $group('ort_frage'), $group('ort_angaben'), + $group('kindergruppe'), $group('schul_ag'), $group('kursplanung'), + ]], + ['key' => 'skurs3', 'title' => 'Kontakt und Zusammenfassung', 'intro' => null, 'items' => [ + ['kind' => 'field', 'field' => 'region', 'required' => true], $group('ansprechpartner'), ['kind' => 'field', 'field' => 'nachricht', 'required' => false], + ]], + ], + 'rules' => [ + $rule('show', 'field:kursformat', [$cond('anliegen', 'eq', 'kurse')]), + $rule('skip', 'step:skurs2', [$cond('unteranliegen', 'eq', 'kursinfo')]), + $rule('show', 'group:traeger_angaben', [$cond('traeger_abweichend', 'eq', 'ja')]), + $rule('show', 'group:ort_angaben', [$cond('ort_abweichend', 'eq', 'ja')]), + $rule('show', 'group:schul_ag', [$cond('kursformat', 'eq', 'schul_ag')]), + $rule('show', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]), + $rule('require', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]), + $rule('show', 'field:region', [$cond('unteranliegen', 'eq', 'kursinfo')]), + ], + ]; + + $materials = [ + 'texts' => ['heading' => 'Frage zu Programmen und Materialien', 'intro' => 'Zu Trainingsprogrammen, Modulen, Filmgeschichten, Übungen, Materialien und Nutzungsrechten.'], + 'issues' => ['materialien'], + 'steps' => [['key' => 'smat1', 'title' => 'Ihre Frage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('material'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $cooperation = [ + 'texts' => ['heading' => 'Kooperation anfragen', 'intro' => 'Für Trainerinnen, Trainer, Institutionen und weitere Partner.'], + 'issues' => ['kooperation'], + 'steps' => [['key' => 'skoop1', 'title' => 'Ihre Anfrage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kooperation'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $templates = []; + + foreach ([ + ['allgemein', 'Allgemeine Kontaktaufnahme', $general], + ['kursanfragen', 'Kursanfragen', $courses], + ['materialanfragen', 'Materialanfragen', $materials], + ['kooperationsanfragen', 'Kooperationsanfragen', $cooperation], + ] as [$key, $name, $draft]) { + $templates[$key] = InquiryTemplate::query()->create(['key' => $key, 'name' => $name, 'draft' => $draft]); + } + + return $templates; + } + + /** + * @param array $templates + */ + private function entries(array $templates, ?User $by): void + { + foreach ($templates as $template) { + $result = $this->publisher->publishTemplate($template, $by, 'Beispielkonfiguration'); + $template->refresh(); + } + + $entries = [ + ['allgemeiner_kontakt', 'Allgemeiner Kontakt', 'allgemein', ['mode' => 'compact', 'allowed_issues' => ['allgemein']]], + ['kurse_workshops', 'Kurse & Workshops', 'kursanfragen', [ + 'mode' => 'wizard', 'allowed_issues' => ['kurse'], + 'texts' => ['heading' => 'Kurse & Workshops anfragen'], + ]], + ['schul_ag', 'Schul-AG', 'kursanfragen', [ + 'mode' => 'wizard', 'allowed_issues' => ['kurse'], + 'defaults' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag'], + 'texts' => ['heading' => 'Schul-AG anfragen', 'intro' => 'Regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Alle Angaben sind unverbindlich.'], + ]], + ['programme_materialien', 'Programme & Materialien', 'materialanfragen', ['mode' => 'compact', 'allowed_issues' => ['materialien']]], + ['kooperation', 'Kooperation', 'kooperationsanfragen', ['mode' => 'compact', 'allowed_issues' => ['kooperation']]], + ]; + + foreach ($entries as [$key, $name, $template, $config]) { + $entry = InquiryEntry::query()->create([ + 'key' => $key, + 'name' => $name, + 'template_id' => $templates[$template]->id, + 'config' => array_merge(InquiryEntry::emptyConfig(), $config), + ]); + + $this->publisher->publishEntry($entry); + } + } +} diff --git a/app/Domain/Communication/FieldPurpose.php b/app/Domain/Communication/FieldPurpose.php new file mode 100644 index 0000000..3b7132d --- /dev/null +++ b/app/Domain/Communication/FieldPurpose.php @@ -0,0 +1,56 @@ + 'Vorname des Ansprechpartners', + self::LastName => 'Nachname des Ansprechpartners', + self::FullName => 'Name des Ansprechpartners', + self::Email => 'E-Mail-Adresse für Rückfragen', + self::Phone => 'Telefonnummer', + self::Organisation => 'Organisation oder Einrichtung', + self::Message => 'Nachricht', + }; + } + + /** @return list */ + public function types(): array + { + return match ($this) { + self::Email => [FieldType::Email], + self::Phone => [FieldType::Phone], + self::Message => [FieldType::Textarea, FieldType::Text], + default => [FieldType::Text], + }; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/FieldType.php b/app/Domain/Communication/FieldType.php new file mode 100644 index 0000000..f631164 --- /dev/null +++ b/app/Domain/Communication/FieldType.php @@ -0,0 +1,62 @@ + 'Text, einzeilig', + self::Textarea => 'Text, mehrzeilig', + self::Email => 'E-Mail-Adresse', + self::Phone => 'Telefonnummer', + self::Number => 'Zahl', + self::Select => 'Einfachauswahl', + self::Multiselect => 'Mehrfachauswahl', + self::Boolean => 'Ja/Nein', + self::Date => 'Datum', + self::Period => 'Zeitraum (von – bis)', + }; + } + + public function hasOptions(): bool + { + return in_array($this, [self::Select, self::Multiselect], true); + } + + /** Ob Bedingungen auf den Wert dieses Feldes aufbauen dürfen. */ + public function canControl(): bool + { + return $this === self::Select || $this === self::Multiselect || $this === self::Boolean; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/FieldValue.php b/app/Domain/Communication/FieldValue.php new file mode 100644 index 0000000..05388b2 --- /dev/null +++ b/app/Domain/Communication/FieldValue.php @@ -0,0 +1,286 @@ + $field + */ + public static function forRules(array $field, mixed $raw): string|array|null + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + + return match ($type) { + FieldType::Select => self::option($field, $raw), + FieldType::Multiselect => self::options($field, $raw) ?: null, + FieldType::Boolean => self::yesNo($raw), + default => null, + }; + } + + /** + * @param array $field + * @return array{0: mixed, 1: ?string} bereinigter Wert (null = nicht beantwortet) und Fehlermeldung + */ + public static function check(array $field, mixed $raw, bool $required): array + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + $label = (string) ($field['label'] ?? 'Dieses Feld'); + $settings = (array) ($field['settings'] ?? []); + $missing = 'Bitte füllen Sie dieses Feld aus.'; + + if ($type === null) { + return [null, 'Dieses Feld ist nicht verfügbar.']; + } + + if (is_string($raw)) { + $raw = str_replace(["\r\n", "\r"], "\n", $raw); + $raw = preg_replace('/[^\P{C}\n\t]/u', '', $raw) ?? ''; + $raw = trim($raw); + } + + $empty = $raw === null || $raw === '' || $raw === [] || (is_array($raw) && $type === FieldType::Period && trim((string) ($raw['von'] ?? '')) === '' && trim((string) ($raw['bis'] ?? '')) === ''); + + if ($empty) { + return [null, $required ? $missing : null]; + } + + switch ($type) { + case FieldType::Text: + case FieldType::Textarea: + if (! is_string($raw)) { + return [null, 'Bitte geben Sie einen Text ein.']; + } + + $max = (int) ($settings['max_length'] ?? ($type === FieldType::Text ? self::TEXT_MAX : self::TEXTAREA_MAX)); + $max = max(1, min($max, $type === FieldType::Text ? 500 : 8000)); + + if ($type === FieldType::Text) { + $raw = preg_replace('/\s*\n\s*/', ' ', $raw) ?? $raw; + } + + if (mb_strlen($raw) > $max) { + return [null, "Bitte höchstens $max Zeichen."]; + } + + return [$raw, null]; + + case FieldType::Email: + if (! is_string($raw) || mb_strlen($raw) > 200 || filter_var($raw, FILTER_VALIDATE_EMAIL) === false) { + return [null, 'Bitte geben Sie eine gültige E-Mail-Adresse ein.']; + } + + return [$raw, null]; + + case FieldType::Phone: + if (! is_string($raw) || preg_match('/^\+?[0-9][0-9 ()\/.\-]{3,28}[0-9]$/', $raw) !== 1) { + return [null, 'Bitte geben Sie eine gültige Telefonnummer ein.']; + } + + return [$raw, null]; + + case FieldType::Number: + if (is_string($raw)) { + $raw = str_replace(',', '.', $raw); + } + + if (! is_numeric($raw) || is_nan((float) $raw) || is_infinite((float) $raw)) { + return [null, 'Bitte geben Sie eine Zahl ein.']; + } + + $number = $raw + 0; + + if (isset($settings['min']) && $settings['min'] !== '' && $number < (float) $settings['min']) { + return [null, 'Bitte mindestens '.self::plain($settings['min']).'.']; + } + + if (isset($settings['max']) && $settings['max'] !== '' && $number > (float) $settings['max']) { + return [null, 'Bitte höchstens '.self::plain($settings['max']).'.']; + } + + return [$number, null]; + + case FieldType::Select: + $option = self::option($field, $raw); + + return $option === null ? [null, 'Bitte wählen Sie einen der angebotenen Werte.'] : [$option, null]; + + case FieldType::Multiselect: + if (! is_array($raw)) { + return [null, 'Bitte wählen Sie aus den angebotenen Werten.']; + } + + $values = self::options($field, $raw); + + if ($values === [] || count($values) !== count(array_unique(array_filter($raw, 'is_string')))) { + return [null, 'Bitte wählen Sie aus den angebotenen Werten.']; + } + + return [$values, null]; + + case FieldType::Boolean: + $answer = self::yesNo($raw); + + return $answer === null ? [null, 'Bitte antworten Sie mit Ja oder Nein.'] : [$answer, null]; + + case FieldType::Date: + $date = self::date($raw); + + return $date === null ? [null, 'Bitte geben Sie ein gültiges Datum ein.'] : [$date, null]; + + case FieldType::Period: + if (! is_array($raw)) { + return [null, 'Bitte geben Sie einen Zeitraum an.']; + } + + $from = trim((string) ($raw['von'] ?? '')) === '' ? null : self::date($raw['von']); + $to = trim((string) ($raw['bis'] ?? '')) === '' ? null : self::date($raw['bis']); + + if ((trim((string) ($raw['von'] ?? '')) !== '' && $from === null) || (trim((string) ($raw['bis'] ?? '')) !== '' && $to === null)) { + return [null, 'Bitte geben Sie gültige Daten ein.']; + } + + if ($required && ($from === null || $to === null)) { + return [null, 'Bitte geben Sie Beginn und Ende an.']; + } + + if ($from !== null && $to !== null && $to < $from) { + return [null, 'Das Ende liegt vor dem Beginn.']; + } + + return [['von' => $from, 'bis' => $to], null]; + } + + return [null, "$label ist nicht verfügbar."]; + } + + /** + * Lesbare Darstellung eines bereinigten Wertes, wie sie in der Anfrage gespeichert wird. + * + * @param array $field + */ + public static function display(array $field, mixed $value): string + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + $labels = []; + + foreach ((array) ($field['options'] ?? []) as $option) { + $labels[$option['key']] = $option['label']; + } + + return match ($type) { + FieldType::Select => (string) ($labels[$value] ?? $value), + FieldType::Multiselect => implode(', ', array_map(fn (string $key): string => (string) ($labels[$key] ?? $key), (array) $value)), + FieldType::Boolean => $value === 'ja' ? 'Ja' : 'Nein', + FieldType::Date => Carbon::parse((string) $value)->format('d.m.Y'), + FieldType::Period => self::periodText((array) $value), + default => (string) $value, + }; + } + + /** + * @param array $field + */ + private static function option(array $field, mixed $raw): ?string + { + if (! is_string($raw)) { + return null; + } + + foreach ((array) ($field['options'] ?? []) as $option) { + if (($option['key'] ?? null) === $raw) { + return $raw; + } + } + + return null; + } + + /** + * @param array $field + * @return list + */ + private static function options(array $field, mixed $raw): array + { + if (! is_array($raw)) { + return []; + } + + $values = []; + + foreach ($raw as $item) { + $option = self::option($field, $item); + + if ($option === null) { + return []; + } + + $values[$option] = $option; + } + + return array_values($values); + } + + private static function yesNo(mixed $raw): ?string + { + return match (true) { + $raw === true, $raw === 'ja', $raw === '1', $raw === 'true', $raw === 1 => 'ja', + $raw === false, $raw === 'nein', $raw === '0', $raw === 'false', $raw === 0 => 'nein', + default => null, + }; + } + + private static function date(mixed $raw): ?string + { + if (! is_string($raw) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $raw) !== 1) { + return null; + } + + try { + $date = Carbon::createFromFormat('!Y-m-d', $raw); + } catch (Throwable) { + return null; + } + + if ($date === false || $date->format('Y-m-d') !== $raw || $date->year < 1900 || $date->year > 2200) { + return null; + } + + return $raw; + } + + /** + * @param array $value + */ + private static function periodText(array $value): string + { + $from = isset($value['von']) ? Carbon::parse($value['von'])->format('d.m.Y') : null; + $to = isset($value['bis']) ? Carbon::parse($value['bis'])->format('d.m.Y') : null; + + return match (true) { + $from !== null && $to !== null => "$from bis $to", + $from !== null => "ab $from", + $to !== null => "bis $to", + default => '', + }; + } + + private static function plain(mixed $number): string + { + return rtrim(rtrim(number_format((float) $number, 4, ',', ''), '0'), ','); + } +} diff --git a/app/Domain/Communication/FormEditor.php b/app/Domain/Communication/FormEditor.php new file mode 100644 index 0000000..ea5dfd8 --- /dev/null +++ b/app/Domain/Communication/FormEditor.php @@ -0,0 +1,741 @@ + ['show', 'hide', 'skip'], + 'group' => ['show', 'hide'], + 'field' => ['show', 'hide', 'require'], + ]; + + /** + * @param array $draft + * @param ?int $exceptTemplate die bearbeitete Vorlage: Sie zählt nicht als „auch verwendet in“ + * @return array{issues: list, areas: list>, rules: list>} + */ + 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 $editor + * @return array{issues: list, steps: list>, rules: list>} + */ + public function persist(array $editor): array + { + return DB::transaction(function () use ($editor): array { + $takenFields = InquiryField::query()->pluck('key')->all(); + $takenGroups = InquiryFieldGroup::query()->pluck('key')->all(); + $existingFields = InquiryField::query()->get()->keyBy('key'); + $existingGroups = InquiryFieldGroup::query()->get()->keyBy('key'); + $map = []; + $issues = []; + $steps = []; + $rules = []; + $order = 0; + + foreach (array_values((array) ($editor['areas'] ?? [])) as $area) { + $area = is_array($area) ? $area : []; + $stepKey = Keys::valid($area['key'] ?? null) || preg_match('/^s[a-z0-9]{3,12}$/', (string) ($area['key'] ?? '')) === 1 ? (string) $area['key'] : 's'.Str::lower(Str::random(6)); + $items = []; + $group = null; + $flush = function () use (&$group, &$items): void { + if ($group !== null) { + $items[] = $group; + $group = null; + } + }; + + foreach (array_values((array) ($area['items'] ?? [])) as $block) { + $block = is_array($block) ? $block : []; + $data = is_array($block['data'] ?? null) ? $block['data'] : []; + + switch ((string) ($block['type'] ?? '')) { + case 'issue': + $flush(); + $items[] = ['kind' => 'issue']; + + if ($issues === []) { + $issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string')); + } + + break; + + case 'end': + $flush(); + + break; + + case 'section': + $flush(); + $original = (string) ($data['key'] ?? ''); + $isMissing = (bool) ($data['missing'] ?? false); + $current = isset($existingGroups[$original]) ? $existingGroups[$original] : null; + $key = $current?->key ?? Keys::from((string) ($data['label'] ?? ''), $takenGroups); + $takenGroups[] = $key; + $map[$original] = $key; + $group = ['kind' => 'group', 'group' => $key, '_label' => trim((string) ($data['label'] ?? '')), '_description' => $data['description'] ?? null, '_rows' => [], '_current' => $current, '_missing' => $isMissing, '_new' => $current === null]; + $this->rule($rules, 'group:'.$key, (array) ($data['cond'] ?? []), 'group', $order); + + break; + + case 'field': + $field = $this->saveField($data, $existingFields, $takenFields); + $original = (string) ($data['key'] ?? ''); + $map[$original] = $field->key; + $required = (bool) ($data['required'] ?? false); + + if ($group !== null) { + $group['_rows'][] = ['field' => $field->key, 'required' => $required]; + } else { + $items[] = ['kind' => 'field', 'field' => $field->key, 'required' => $required]; + } + + $this->rule($rules, 'field:'.$field->key, (array) ($data['cond'] ?? []), 'field', $order); + + break; + } + } + + $flush(); + $this->rule($rules, 'step:'.$stepKey, (array) ($area['cond'] ?? []), 'step', $order); + + foreach ($items as $index => $item) { + if (($item['kind'] ?? null) !== 'group') { + continue; + } + + $items[$index] = $this->saveGroup($item, $existingGroups, $takenGroups); + } + + $steps[] = [ + 'key' => $stepKey, + 'title' => mb_substr(trim((string) ($area['title'] ?? '')), 0, 120), + 'intro' => filled($area['intro'] ?? null) ? mb_substr(trim((string) $area['intro']), 0, 600) : null, + 'items' => $items, + ]; + } + + foreach (array_values((array) ($editor['rules'] ?? [])) as $rule) { + $rule = is_array($rule) ? $rule : []; + $target = (string) ($rule['target'] ?? ''); + [$kind, $key] = array_pad(explode(':', $target, 2), 2, ''); + $rules[] = [ + 'effect' => (string) ($rule['effect'] ?? ''), + 'target' => $kind === '' ? $target : $kind.':'.($map[$key] ?? $key), + 'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all', + 'conditions' => $this->conditions((array) ($rule['conditions'] ?? []), $map), + 'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null, + '_pos' => is_numeric($rule['pos'] ?? null) ? (int) $rule['pos'] : 1000 + $order++, + ]; + } + + foreach ($rules as $index => $rule) { + $rules[$index]['conditions'] = $this->conditions((array) $rule['conditions'], $map); + } + + usort($rules, fn (array $a, array $b): int => $a['_pos'] <=> $b['_pos']); + + return [ + 'issues' => $issues, + 'steps' => $steps, + 'rules' => array_map(function (array $rule): array { + unset($rule['_pos']); + + return $rule; + }, $rules), + ]; + }); + } + + /** Beschriftungen der Wirkungen am Element, je Art des Ziels. */ + public const EFFECT_LABELS = [ + 'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'], + 'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'], + 'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'], + ]; + + /** + * Baumansicht für die Formularoberfläche (ADR-62): Ein Teilbereich trägt seine Felder selbst (items), die + * Ende-Markierung der flachen Ansicht entfällt. Die Umwandlung ist verlustfrei: fromTree(toTree(x)) liefert dieselbe + * Struktur, die persist() in denselben Entwurf überführt. + * + * @param array $view Ergebnis von expand() + * @return array{areas: list>, rules: list>} + */ + public static function toTree(array $view): array + { + $areas = []; + + foreach (array_values((array) ($view['areas'] ?? [])) as $area) { + $area = is_array($area) ? $area : []; + $items = []; + $section = null; + + foreach (array_values((array) ($area['items'] ?? [])) as $block) { + $block = is_array($block) ? $block : []; + $data = is_array($block['data'] ?? null) ? $block['data'] : []; + + switch ((string) ($block['type'] ?? '')) { + case 'issue': + $section = null; + $items[] = ['kind' => 'issue', 'issues' => array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'))]; + + break; + + case 'end': + $section = null; + + break; + + case 'section': + $items[] = ['kind' => 'section', ...$data, 'items' => []]; + $section = array_key_last($items); + + break; + + case 'field': + if ($section !== null) { + $items[$section]['items'][] = ['kind' => 'field', ...$data]; + } else { + $items[] = ['kind' => 'field', ...$data]; + } + + break; + } + } + + $areas[] = [...Arr::except($area, ['items']), 'items' => $items]; + } + + return ['areas' => $areas, 'rules' => array_values((array) ($view['rules'] ?? []))]; + } + + /** + * Umkehrung von toTree(): die flache Ansicht, die persist() erwartet. Nach jedem Teilbereich steht eine + * Ende-Markierung, damit folgende Einzelfelder nicht in ihn fallen. + * + * @param array $tree + * @return array{areas: list>, rules: list>} + */ + public static function fromTree(array $tree): array + { + $areas = []; + $field = fn (array $item): array => ['type' => 'field', 'data' => Arr::except($item, ['kind', '_id'])]; + + foreach (array_values((array) ($tree['areas'] ?? [])) as $area) { + $area = is_array($area) ? $area : []; + $blocks = []; + + foreach (array_values((array) ($area['items'] ?? [])) as $item) { + $item = is_array($item) ? $item : []; + + switch ((string) ($item['kind'] ?? '')) { + case 'issue': + $blocks[] = ['type' => 'issue', 'data' => ['issues' => array_values(array_filter((array) ($item['issues'] ?? []), 'is_string'))]]; + + break; + + case 'section': + $blocks[] = ['type' => 'section', 'data' => Arr::except($item, ['kind', '_id', 'items'])]; + + foreach (array_values((array) ($item['items'] ?? [])) as $inner) { + $blocks[] = $field(is_array($inner) ? $inner : []); + } + + $blocks[] = ['type' => 'end', 'data' => []]; + + break; + + case 'field': + $blocks[] = $field($item); + + break; + } + } + + $areas[] = [...Arr::except($area, ['items', '_id']), 'items' => $blocks]; + } + + return ['areas' => $areas, 'rules' => array_values((array) ($tree['rules'] ?? []))]; + } + + /** + * Prüft die Baumansicht vor dem Speichern. Was nur gekürzt oder ignoriert würde, wird hier benannt, damit die + * Verwaltung nichts stillschweigend verliert. + * + * @param array $tree + * @return list + */ + public function validateTree(array $tree): array + { + $errors = []; + $seen = []; + $issueQuestions = 0; + $limit = function (string $where, string $what, mixed $value, int $max) use (&$errors): void { + if (mb_strlen(trim((string) $value)) > $max) { + $errors[] = "$where: $what darf höchstens $max Zeichen lang sein."; + } + }; + + foreach (array_values((array) ($tree['areas'] ?? [])) as $index => $area) { + $area = is_array($area) ? $area : []; + $title = trim((string) ($area['title'] ?? '')); + $where = 'Bereich '.($index + 1).($title !== '' ? ' „'.$title.'“' : ''); + + if ($title === '') { + $errors[] = "$where: Der Titel fehlt."; + } + + $limit($where, 'Der Titel', $title, 120); + $limit($where, 'Die Einleitung', $area['intro'] ?? '', 600); + + $checkField = function (array $field) use (&$errors, &$seen, $where, $limit): void { + $label = trim((string) ($field['label'] ?? '')); + $name = $label !== '' ? '„'.$label.'“' : 'Ein Feld'; + + if ($label === '') { + $errors[] = "$where: Ein Feld hat keine Frage oder Beschriftung."; + } + + $limit($where, "Die Frage $name", $label, 200); + $limit($where, "Der Hilfetext von $name", $field['help'] ?? '', 600); + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + + if ($type === null) { + $errors[] = "$where: Bei $name fehlt die Art der Antwort."; + } elseif ($type->hasOptions()) { + $options = array_filter((array) ($field['options'] ?? []), fn (mixed $option): bool => is_array($option) && trim((string) ($option['label'] ?? '')) !== ''); + + if ($options === []) { + $errors[] = "$where: Bei $name fehlen die Auswahlwerte."; + } + + foreach ($options as $option) { + $limit($where, "Ein Auswahlwert von $name", $option['label'], 120); + } + } + + $key = (string) ($field['key'] ?? ''); + + if ($key !== '' && ! str_starts_with($key, 'tmp_')) { + if (isset($seen[$key])) { + $errors[] = "$where: $name steht mehrfach im Formular."; + } + + $seen[$key] = true; + } + }; + + foreach (array_values((array) ($area['items'] ?? [])) as $item) { + $item = is_array($item) ? $item : []; + + if (($item['kind'] ?? null) === 'issue') { + $issueQuestions++; + } elseif (($item['kind'] ?? null) === 'section') { + $label = trim((string) ($item['label'] ?? '')); + + if ($label === '') { + $errors[] = "$where: Ein Teilbereich hat keine Überschrift."; + } + + $limit($where, 'Die Überschrift eines Teilbereichs', $label, 200); + $limit($where, 'Die Erläuterung eines Teilbereichs', $item['description'] ?? '', 600); + + foreach (array_values((array) ($item['items'] ?? [])) as $inner) { + $checkField(is_array($inner) ? $inner : []); + } + } elseif (($item['kind'] ?? null) === 'field') { + $checkField($item); + } + } + } + + if ($issueQuestions > 1) { + $errors[] = 'Die Frage nach dem Anliegen darf nur einmal im Formular vorkommen.'; + } + + return array_values(array_unique($errors)); + } + + /** + * Auswahllisten für die Formularoberfläche: Feldarten, Verwendungen, Wirkungen, Vergleiche, Anliegen und die Felder + * des Katalogs mit Verwendung in anderen Formularen. + * + * @return array + */ + public function clientConfig(?int $exceptTemplate = null): array + { + $usage = $this->usage($exceptTemplate); + + return [ + 'types' => array_map(fn (FieldType $type): array => ['value' => $type->value, 'label' => $type->label(), 'options' => $type->hasOptions(), 'control' => $type->canControl()], FieldType::cases()), + 'purposes' => array_map(fn (FieldPurpose $purpose): array => ['value' => $purpose->value, 'label' => $purpose->label(), 'types' => array_map(fn (FieldType $type): string => $type->value, $purpose->types())], FieldPurpose::cases()), + 'effects' => self::EFFECT_LABELS, + 'operators' => TemplateCompiler::OPERATORS, + 'issues' => InquiryIssue::tree(), + 'catalog' => InquiryField::query()->offered()->orderBy('name')->get()->map(fn (InquiryField $field): array => [ + 'key' => $field->key, + 'name' => $field->name, + 'label' => $field->label, + 'help' => $field->help, + 'type' => $field->type->value, + 'options' => $field->optionList(), + 'purpose' => $field->purpose?->value, + 'used_in' => implode(', ', $usage['fields'][$field->key] ?? []), + ])->values()->all(), + ]; + } + + /** + * Eine neue Zeile in der Karteikarte der Bedingungen (leer: Standardwerte). + * + * @return array + */ + 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>, groups: array>} + */ + 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 $rule + * @return array + */ + 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>, groups: array>} $usage + * @return array + */ + 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> $rules + * @param array $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 $conditions + * @param array $map + * @return list}> + */ + 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 $data + * @param Collection $existing + * @param list $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 $group Teilbereich mit gesammelten Feldern (_rows) + * @param Collection $existing + * @param list $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; + } +} diff --git a/app/Domain/Communication/FormEvaluator.php b/app/Domain/Communication/FormEvaluator.php new file mode 100644 index 0000000..5da1a0b --- /dev/null +++ b/app/Domain/Communication/FormEvaluator.php @@ -0,0 +1,212 @@ + $form wirksames Formular (FormFactory::effective) + * @param array $values Eingaben des Besuchers, nach Feldkennung + * @return array{steps: array, groups: array, fields: array, required: array, presets: array, issue: ?string, subissue: ?string, issue_active: bool} + */ + public function evaluate(array $form, array $values): array + { + $state = ['steps' => [], 'groups' => [], 'fields' => [], 'required' => [], 'presets' => [], 'issue' => null, 'subissue' => null, 'issue_active' => false]; + $context = []; + $byTarget = []; + + foreach ((array) ($form['rules'] ?? []) as $rule) { + $byTarget[$rule['target']][] = $rule; + } + + foreach ((array) $form['steps'] as $step) { + // Ein Bereich lässt sich wie eine Gruppe anzeigen oder ausblenden; „überspringen“ bleibt für ältere Vorlagen gültig. + $stepRules = $byTarget['step:'.$step['key']] ?? []; + $stepVisible = ! $this->any($stepRules, 'skip', $context) && $this->visible($stepRules, $context); + $state['steps'][$step['key']] = $stepVisible; + + foreach ($step['items'] as $item) { + if ($item['kind'] === 'issue') { + $this->issue($form, $values, $stepVisible, $state, $context); + + continue; + } + + $groupVisible = $stepVisible && ($item['key'] === null || $this->visible($byTarget['group:'.$item['key']] ?? [], $context)); + + if ($item['key'] !== null) { + $state['groups'][$item['key']] = $groupVisible; + } + + foreach ($item['fields'] as $row) { + $key = $row['field']; + $rules = $byTarget["field:$key"] ?? []; + $visible = $groupVisible && $this->visible($rules, $context); + $state['fields'][$key] = $visible; + $state['required'][$key] = $visible && ($row['required'] || $this->any($rules, 'require', $context)); + + if (! $visible) { + continue; + } + + $context[$key] = FieldValue::forRules($form['fields'][$key], $values[$key] ?? null); + + foreach ($rules as $rule) { + if ($rule['effect'] === 'preset' && $this->matches($rule, $context)) { + $state['presets'][$key] ??= (string) $rule['value']; + } + } + } + } + } + + return $state; + } + + /** + * @param array $form + * @param array $values + * @param array $state + * @param array|null> $context + */ + private function issue(array $form, array $values, bool $stepVisible, array &$state, array &$context): void + { + $state['fields']['anliegen'] = false; + $state['fields']['unteranliegen'] = false; + $state['required']['anliegen'] = false; + $state['required']['unteranliegen'] = false; + + if (! $stepVisible) { + return; + } + + $state['issue_active'] = true; + $tops = (array) $form['issues']; + $selected = null; + + if (count($tops) === 1) { + $selected = $tops[0]; + } else { + $state['fields']['anliegen'] = $tops !== []; + $state['required']['anliegen'] = $tops !== []; + $wanted = $values['anliegen'] ?? null; + + foreach ($tops as $top) { + if ($top['key'] === $wanted) { + $selected = $top; + } + } + } + + $context['anliegen'] = $selected['key'] ?? null; + $state['issue'] = $selected['key'] ?? null; + + if ($selected === null) { + return; + } + + $children = (array) $selected['children']; + $child = null; + + if (count($children) === 1) { + $child = $children[0]; + } elseif (count($children) > 1) { + $state['fields']['unteranliegen'] = true; + $state['required']['unteranliegen'] = true; + $wanted = $values['unteranliegen'] ?? null; + + foreach ($children as $candidate) { + if ($candidate['key'] === $wanted) { + $child = $candidate; + } + } + } + + $context['unteranliegen'] = $child['key'] ?? null; + $state['subissue'] = $child['key'] ?? null; + } + + /** + * Sichtbar, wenn keine „Anzeigen“-Regel besteht oder eine zutrifft, und keine „Ausblenden“-Regel zutrifft. + * + * @param list> $rules + * @param array $context + */ + private function visible(array $rules, array $context): bool + { + $show = array_filter($rules, fn (array $rule): bool => $rule['effect'] === 'show'); + + if ($show !== [] && ! $this->any($show, 'show', $context)) { + return false; + } + + return ! $this->any($rules, 'hide', $context); + } + + /** + * @param list> $rules + * @param array $context + */ + private function any(array $rules, string $effect, array $context): bool + { + foreach ($rules as $rule) { + if ($rule['effect'] === $effect && $this->matches($rule, $context)) { + return true; + } + } + + return false; + } + + /** + * @param array $rule + * @param array $context + */ + private function matches(array $rule, array $context): bool + { + $results = []; + + foreach ($rule['conditions'] as $condition) { + $results[] = $this->condition($condition, $context); + } + + if ($results === []) { + return false; + } + + return $rule['match'] === 'any' ? in_array(true, $results, true) : ! in_array(false, $results, true); + } + + /** + * Eine Bedingung auf einem nicht sichtbaren Feld ist nie erfüllt, auch nicht „ist nicht“. + * + * @param array $condition + * @param array $context + */ + private function condition(array $condition, array $context): bool + { + if (! array_key_exists($condition['source'], $context)) { + return false; + } + + $actual = $context[$condition['source']]; + $wanted = (array) $condition['values']; + $hit = is_array($actual) + ? array_intersect($actual, $wanted) !== [] + : ($actual !== null && in_array($actual, $wanted, true)); + + return match ($condition['op']) { + 'eq', 'in' => $hit, + 'neq', 'not_in' => ! $hit, + default => false, + }; + } +} diff --git a/app/Domain/Communication/FormFactory.php b/app/Domain/Communication/FormFactory.php new file mode 100644 index 0000000..3280c59 --- /dev/null +++ b/app/Domain/Communication/FormFactory.php @@ -0,0 +1,179 @@ + $definition aufgelöste Fassung (TemplateCompiler) + * @param array $config Konfiguration des Einstiegs (veröffentlichter Stand oder Entwurf) + * @return array + */ + public function effective(array $definition, array $config): array + { + $allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')); + $allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')); + $tree = []; + + foreach ((array) ($definition['issues'] ?? []) as $issue) { + if ($allowed !== [] && ! in_array($issue['key'], $allowed, true)) { + continue; + } + + $children = (array) $issue['children']; + $chosen = array_values(array_filter($children, fn (array $child): bool => in_array($child['key'], $allowedSub, true))); + $issue['children'] = $chosen !== [] ? $chosen : $children; + $tree[] = $issue; + } + + $form = $definition; + $form['issues'] = $tree; + $form['texts'] = FormTexts::merge((array) ($definition['texts'] ?? []), (array) ($config['texts'] ?? [])); + $form['mode'] = ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact'; + $form['open'] = ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline'; + $form['defaults'] = $this->defaults($form, (array) ($config['defaults'] ?? [])); + $form['controls'] = $this->controls($form); + + return $form; + } + + /** + * @param array $form + * @param array $wanted + * @return array + */ + private function defaults(array $form, array $wanted): array + { + $defaults = []; + $tops = array_column((array) $form['issues'], 'key'); + + if (isset($wanted['anliegen']) && in_array($wanted['anliegen'], $tops, true)) { + $defaults['anliegen'] = $wanted['anliegen']; + + foreach ($form['issues'] as $issue) { + if ($issue['key'] === $wanted['anliegen'] && isset($wanted['unteranliegen']) && in_array($wanted['unteranliegen'], array_column($issue['children'], 'key'), true)) { + $defaults['unteranliegen'] = $wanted['unteranliegen']; + } + } + } + + foreach ((array) $form['fields'] as $key => $field) { + $value = $wanted[$key] ?? null; + + if (! is_string($value) || ! in_array($field['type'], ['select', 'boolean'], true)) { + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + + if (in_array($value, $valid, true)) { + $defaults[$key] = $value; + } + } + + return $defaults; + } + + /** + * Felder, auf deren Änderung das Formular die Regeln neu auswerten lassen muss. + * + * @param array $form + * @return list + */ + private function controls(array $form): array + { + $controls = []; + + foreach ((array) $form['rules'] as $rule) { + foreach ($rule['conditions'] as $condition) { + $controls[$condition['source']] = true; + } + } + + return array_keys($controls); + } + + /** + * Prüft die Konfiguration eines Einstiegs gegen eine Fassung. Leere Liste: gültig. + * + * @param array $definition + * @param array $config + * @return list + */ + public function problems(array $definition, array $config): array + { + $problems = []; + $tops = array_column((array) ($definition['issues'] ?? []), 'key'); + $subs = []; + + foreach ((array) ($definition['issues'] ?? []) as $issue) { + foreach ($issue['children'] as $child) { + $subs[$child['key']] = $issue['key']; + } + } + + $allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')); + $allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')); + + foreach ($allowed as $key) { + if (! in_array($key, $tops, true)) { + $problems[] = "Das Anliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten."; + } + } + + foreach ($allowedSub as $key) { + if (! isset($subs[$key])) { + $problems[] = "Das Unteranliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten."; + } elseif ($allowed !== [] && ! in_array($subs[$key], $allowed, true)) { + $problems[] = "Das Unteranliegen „{$key}“ gehört zu einem Anliegen, das dieser Einstieg nicht zulässt."; + } + } + + if (($definition['has_issue'] ?? false) && $allowed !== [] && array_diff($allowed, $tops) === $allowed) { + $problems[] = 'Keines der zugelassenen Anliegen ist in der Vorlage vorhanden.'; + } + + foreach ((array) ($config['defaults'] ?? []) as $key => $value) { + if ($key === 'anliegen') { + if (! in_array($value, $allowed !== [] ? $allowed : $tops, true)) { + $problems[] = 'Das vorausgewählte Anliegen ist nicht zugelassen oder nicht in der Vorlage.'; + } + + continue; + } + + if ($key === 'unteranliegen') { + if (! isset($subs[$value])) { + $problems[] = 'Das vorausgewählte Unteranliegen ist nicht in der Vorlage.'; + } + + continue; + } + + $field = $definition['fields'][$key] ?? null; + + if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) { + $problems[] = "Die Vorbelegung für „{$key}“ ist in der veröffentlichten Vorlage nicht möglich."; + + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + + if (! in_array($value, $valid, true)) { + $problems[] = "Der vorausgewählte Wert für „{$field['label']}“ gibt es nicht mehr."; + } + } + + if (isset($config['mode']) && ! in_array($config['mode'], ['compact', 'wizard'], true)) { + $problems[] = 'Die Darstellung muss „kompakt“ oder „mehrstufig“ sein.'; + } + + return $problems; + } +} diff --git a/app/Domain/Communication/FormJson.php b/app/Domain/Communication/FormJson.php new file mode 100644 index 0000000..7ce6a0e --- /dev/null +++ b/app/Domain/Communication/FormJson.php @@ -0,0 +1,34 @@ + $value + * @return array + */ + public static function normalize(array $value): array + { + $isList = array_is_list($value); + + foreach ($value as $key => $item) { + if (is_array($item)) { + $value[$key] = self::normalize($item); + } elseif (is_int($item) || is_float($item)) { + $value[$key] = (string) $item; + } elseif (is_bool($item)) { + $value[$key] = $item ? '1' : '0'; + } + } + + if (! $isList) { + ksort($value); + } + + return $value; + } +} diff --git a/app/Domain/Communication/FormPayload.php b/app/Domain/Communication/FormPayload.php new file mode 100644 index 0000000..8a6ff81 --- /dev/null +++ b/app/Domain/Communication/FormPayload.php @@ -0,0 +1,66 @@ + $form wirksames Formular (FormFactory::effective) + * @return array + */ + public static function definition(array $form, FormEvaluator $evaluator): array + { + $fields = []; + + foreach ((array) $form['fields'] as $key => $field) { + $settings = (array) ($field['settings'] ?? []); + $fields[$key] = array_filter([ + 'key' => $key, + 'label' => $field['label'], + 'help' => $field['help'], + 'type' => $field['type'], + 'options' => $field['options'] ?: null, + 'max_length' => $settings['max_length'] ?? null, + 'min' => $settings['min'] ?? null, + 'max' => $settings['max'] ?? null, + ], fn (mixed $value): bool => $value !== null); + } + + return [ + 'mode' => $form['mode'] ?? 'compact', + 'open' => $form['open'] ?? 'inline', + 'texts' => $form['texts'], + 'issues' => $form['issues'], + 'defaults' => (object) ($form['defaults'] ?? []), + 'controls' => $form['controls'] ?? [], + 'steps' => $form['steps'], + 'fields' => $fields, + 'state' => self::state($form, (array) ($form['defaults'] ?? []), $evaluator), + ]; + } + + /** + * @param array $form + * @param array $values + * @return array + */ + public static function state(array $form, array $values, FormEvaluator $evaluator): array + { + $state = $evaluator->evaluate($form, $values); + + return [ + 'steps' => (object) $state['steps'], + 'groups' => (object) $state['groups'], + 'fields' => (object) $state['fields'], + 'required' => (object) $state['required'], + 'presets' => (object) $state['presets'], + 'issue' => $state['issue'], + 'subissue' => $state['subissue'], + ]; + } +} 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/FormTexts.php b/app/Domain/Communication/FormTexts.php new file mode 100644 index 0000000..d45259d --- /dev/null +++ b/app/Domain/Communication/FormTexts.php @@ -0,0 +1,85 @@ + [Bezeichnung in der Verwaltung, Vorgabe, Hilfetext, mehrzeilig] */ + public const FIELDS = [ + 'heading' => ['Überschrift', 'Ihre Anfrage', 'Steht über dem Formular.', false], + 'intro' => ['Beschreibung', '', 'Kurzer Text unter der Überschrift.', true], + 'open_label' => ['Beschriftung der Öffnen-Schaltfläche', 'Anfrage stellen', 'Nur wenn der Einstieg zunächst eine Schaltfläche zeigt.', false], + 'issue_question' => ['Frage nach dem Anliegen', 'Wie können wir Ihnen helfen?', 'Steht über der Auswahl des Anliegens.', false], + 'privacy_note' => ['Hinweis zum Datenschutz', '', 'Steht über der Schaltfläche zum Absenden. Der rechtlich geprüfte Wortlaut wird hier gepflegt; es gibt keine Pflicht-Einwilligungsbox.', true], + 'back_label' => ['Schaltfläche „Zurück“', 'Zurück', null, false], + 'next_label' => ['Schaltfläche „Weiter“', 'Weiter', null, false], + 'summary_title' => ['Überschrift der Zusammenfassung', 'Ihre Angaben im Überblick', 'Letzter Schritt vor dem Absenden im mehrstufigen Dialog.', false], + 'edit_label' => ['Schaltfläche „Ändern“', 'Ändern', 'Steht in der Zusammenfassung neben jedem Schritt.', false], + 'submit_label' => ['Schaltfläche zum Absenden', 'Anfrage senden', null, false], + 'success_title' => ['Bestätigung: Überschrift', 'Vielen Dank für Ihre Anfrage', null, false], + 'success_text' => ['Bestätigung: Text', 'Wir haben Ihre Anfrage erhalten und melden uns bei Ihnen.', null, true], + 'error_text' => ['Meldung bei einem Fehler', 'Ihre Anfrage konnte nicht gesendet werden. Ihre Eingaben bleiben erhalten; bitte versuchen Sie es noch einmal.', null, true], + ]; + + /** + * @return array + */ + public static function defaults(): array + { + $defaults = []; + + foreach (self::FIELDS as $key => $field) { + $defaults[$key] = $field[1]; + } + + return $defaults; + } + + /** + * Setzt Vorgaben und eigene Texte zusammen; leere Eigenwerte fallen auf die Vorgabe zurück. + * + * @param array ...$layers von der schwächsten zur stärksten Schicht + * @return array + */ + public static function merge(array ...$layers): array + { + $texts = self::defaults(); + + foreach ($layers as $layer) { + foreach (array_keys(self::FIELDS) as $key) { + $value = $layer[$key] ?? null; + + if (is_string($value) && trim($value) !== '') { + $texts[$key] = trim($value); + } + } + } + + return $texts; + } + + /** + * Bereinigt eigene Texte aus der Verwaltung: nur bekannte Schlüssel, Länge begrenzt. + * + * @param array $texts + * @return array + */ + public static function clean(array $texts): array + { + $clean = []; + + foreach (self::FIELDS as $key => $field) { + $value = $texts[$key] ?? null; + + if (is_string($value) && trim($value) !== '') { + $clean[$key] = mb_substr(trim($value), 0, $field[3] ? 1500 : 200); + } + } + + return $clean; + } +} diff --git a/app/Domain/Communication/FormToken.php b/app/Domain/Communication/FormToken.php new file mode 100644 index 0000000..13e9e75 --- /dev/null +++ b/app/Domain/Communication/FormToken.php @@ -0,0 +1,55 @@ + $kind === 'form' ? 'form' : 'entry', + 'e' => $entryId, + 'v' => $versionId, + 't' => now()->getTimestamp(), + 'n' => Str::random(32), + ], JSON_THROW_ON_ERROR)); + } + + /** + * @return array{k: string, e: int, v: int, t: int, n: string}|null + */ + public static function read(mixed $token): ?array + { + if (! is_string($token) || $token === '' || strlen($token) > 2000) { + return null; + } + + try { + $data = json_decode(Crypt::decryptString($token), true, 4, JSON_THROW_ON_ERROR); + } catch (DecryptException|\JsonException) { + return null; + } + + if (! is_array($data) || ! isset($data['e'], $data['v'], $data['t'], $data['n']) || ! is_string($data['n'])) { + return null; + } + + return ['k' => ($data['k'] ?? 'entry') === 'form' ? 'form' : 'entry', 'e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']]; + } +} diff --git a/app/Domain/Communication/Inquiry.php b/app/Domain/Communication/Inquiry.php new file mode 100644 index 0000000..bb3cdf6 --- /dev/null +++ b/app/Domain/Communication/Inquiry.php @@ -0,0 +1,65 @@ + 'array', 'status' => InquiryStatus::class, 'notified_at' => 'datetime']; + } + + public function entry(): BelongsTo + { + return $this->belongsTo(InquiryEntry::class, 'entry_id'); + } + + public function templateVersion(): BelongsTo + { + return $this->belongsTo(InquiryTemplateVersion::class, 'template_version_id'); + } + + public function notes(): HasMany + { + return $this->hasMany(InquiryNote::class)->orderByDesc('created_at')->orderByDesc('id'); + } + + /** Lesbare Bezeichnung des Anliegens, mit Unteranliegen. */ + public function issueTitle(): string + { + return trim(implode(' › ', array_filter([$this->issue_label, $this->subissue_label]))); + } + + /** + * Woher die Anfrage kam: der Anfrage-Einstieg (älterer Weg) oder das Formular, das das Widget „Anfrage“ eingebunden hat. + */ + public function channelTitle(): string + { + if ($this->entry !== null) { + return $this->entry->name; + } + + $template = $this->templateVersion?->template; + + return $template !== null ? 'Formular „'.$template->name.'“' : 'Formular gelöscht'; + } + + public function contactTitle(): string + { + return $this->contact_name ?: ($this->contact_email ?: 'Unbekannt'); + } +} diff --git a/app/Domain/Communication/InquiryEntry.php b/app/Domain/Communication/InquiryEntry.php new file mode 100644 index 0000000..eb447ff --- /dev/null +++ b/app/Domain/Communication/InquiryEntry.php @@ -0,0 +1,64 @@ + 'array', 'published_config' => 'array', 'published_at' => 'datetime', 'archived_at' => 'datetime']; + } + + public function template(): BelongsTo + { + return $this->belongsTo(InquiryTemplate::class, 'template_id'); + } + + public function inquiries(): HasMany + { + return $this->hasMany(Inquiry::class, 'entry_id'); + } + + /** Einstiege, die Besuchern ausgeliefert werden können (Vorlage zusätzlich in isLive() prüfen). */ + public function scopeLive(Builder $query): Builder + { + return $query->whereNotNull('published_at')->whereNull('archived_at')->whereNotNull('published_config'); + } + + public function isLive(): bool + { + return $this->published_at !== null && $this->archived_at === null && $this->published_config !== null + && $this->template?->published_version_id !== null && $this->template->archived_at === null; + } + + public function hasUnpublishedChanges(): bool + { + return $this->published_config === null || FormJson::normalize($this->published_config) !== FormJson::normalize((array) $this->config); + } + + /** + * @return array + */ + public static function emptyConfig(): array + { + return [ + 'mode' => 'compact', + 'open' => 'inline', + 'allowed_issues' => [], + 'allowed_subissues' => [], + 'defaults' => [], + 'texts' => [], + ]; + } +} diff --git a/app/Domain/Communication/InquiryField.php b/app/Domain/Communication/InquiryField.php new file mode 100644 index 0000000..345373a --- /dev/null +++ b/app/Domain/Communication/InquiryField.php @@ -0,0 +1,75 @@ + FieldType::class, + 'purpose' => FieldPurpose::class, + 'options' => 'array', + 'settings' => 'array', + 'active' => 'boolean', + 'archived_at' => 'datetime', + ]; + } + + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + /** + * Auswahlwerte als Liste [{key, label}] in der gepflegten Reihenfolge. + * + * @return list + */ + public function optionList(): array + { + if ($this->type === FieldType::Boolean) { + return [['key' => 'ja', 'label' => 'Ja'], ['key' => 'nein', 'label' => 'Nein']]; + } + + if (! $this->type->hasOptions()) { + return []; + } + + $list = []; + + foreach ((array) $this->options as $option) { + if (is_array($option) && Keys::valid($option['key'] ?? null) && filled($option['label'] ?? null)) { + $list[] = ['key' => $option['key'], 'label' => (string) $option['label']]; + } + } + + return $list; + } + + /** + * Die Beschreibung des Feldes, wie sie in eine Fassung übernommen wird. + * + * @return array + */ + public function snapshot(): array + { + return [ + 'key' => $this->key, + 'label' => $this->label, + 'help' => $this->help, + 'type' => $this->type->value, + 'options' => $this->optionList(), + 'settings' => (array) $this->settings, + 'purpose' => $this->purpose?->value, + ]; + } +} diff --git a/app/Domain/Communication/InquiryFieldGroup.php b/app/Domain/Communication/InquiryFieldGroup.php new file mode 100644 index 0000000..fe22141 --- /dev/null +++ b/app/Domain/Communication/InquiryFieldGroup.php @@ -0,0 +1,40 @@ + 'array', 'active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer']; + } + + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + /** + * @return list + */ + public function itemList(): array + { + $list = []; + + foreach ((array) $this->items as $item) { + if (is_array($item) && Keys::valid($item['field'] ?? null)) { + $list[] = ['field' => $item['field'], 'required' => (bool) ($item['required'] ?? false)]; + } + } + + return $list; + } +} diff --git a/app/Domain/Communication/InquiryIssue.php b/app/Domain/Communication/InquiryIssue.php new file mode 100644 index 0000000..c4fa69a --- /dev/null +++ b/app/Domain/Communication/InquiryIssue.php @@ -0,0 +1,69 @@ + 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer']; + } + + public function parent(): BelongsTo + { + return $this->belongsTo(self::class, 'parent_id'); + } + + public function children(): HasMany + { + return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id'); + } + + /** Anliegen, die Besuchern angeboten werden können. */ + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + public function isOffered(): bool + { + return $this->active && $this->archived_at === null; + } + + /** + * Baum aus angebotenen Anliegen mit ihren angebotenen Unteranliegen, wie er in eine Fassung übernommen wird. + * + * @return list}> + */ + public static function tree(): array + { + $all = self::query()->offered()->orderBy('sort_order')->orderBy('id')->get(); + $children = $all->whereNotNull('parent_id')->groupBy('parent_id'); + $tree = []; + + foreach ($all->whereNull('parent_id') as $issue) { + $tree[] = [ + 'key' => $issue->key, + 'label' => $issue->label, + 'description' => $issue->description, + 'children' => ($children[$issue->id] ?? collect())->map(fn (self $child): array => [ + 'key' => $child->key, + 'label' => $child->label, + 'description' => $child->description, + ])->values()->all(), + ]; + } + + return $tree; + } +} diff --git a/app/Domain/Communication/InquiryNote.php b/app/Domain/Communication/InquiryNote.php new file mode 100644 index 0000000..00068d2 --- /dev/null +++ b/app/Domain/Communication/InquiryNote.php @@ -0,0 +1,22 @@ +belongsTo(Inquiry::class); + } + + public function author(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } +} diff --git a/app/Domain/Communication/InquiryService.php b/app/Domain/Communication/InquiryService.php new file mode 100644 index 0000000..a5214ae --- /dev/null +++ b/app/Domain/Communication/InquiryService.php @@ -0,0 +1,344 @@ +, version: InquiryTemplateVersion}|null + */ + public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array + { + $entry->loadMissing('template.publishedVersion'); + + if (! $entry->isLive()) { + return null; + } + + $version = $entry->template->publishedVersion; + + if ($versionId !== null && $versionId !== $version->id) { + $older = InquiryTemplateVersion::query()->where('template_id', $entry->template_id)->find($versionId); + $version = $older ?? $version; + } + + return ['form' => $this->factory->effective($version->definition, (array) $entry->published_config), 'version' => $version]; + } + + /** + * @param array $payload {values: {...}, token: string, website?: string, source?: string} + * @return array{reference: string, created: bool} + * + * @throws SubmissionException + */ + public function submit(InquiryEntry $entry, array $payload): array + { + return $this->accept('entry', $entry->id, $entry->id, fn (?int $version): ?array => $this->deliver($entry, $version), $payload); + } + + /** + * Die Fassung und das wirksame Formular einer veröffentlichten Vorlage für einen Besucher, wie sie das Widget + * „Anfrage“ ausliefert. $reason legt den Anfragegrund fest: ein vorgewähltes Anliegen (und Unteranliegen) und die + * Formularführung. Null, wenn die Vorlage nicht veröffentlicht oder archiviert ist. + * + * @param array{anliegen?: ?string, unteranliegen?: ?string, modus?: ?string} $reason + * @return array{form: array, 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['k'] !== $kind || $token['e'] !== $targetId) { + throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419); + } + + $age = now()->getTimestamp() - $token['t']; + + if ($age > config('communication.token_ttl_hours', 24) * 3600) { + throw new SubmissionException('Das Formular war zu lange geöffnet. Bitte laden Sie die Seite neu.', [], 419); + } + + $existing = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->first(); + + if ($existing !== null) { + return ['reference' => $existing->reference, 'created' => false]; + } + + $delivered = $deliver($token['v']); + + if ($delivered === null) { + throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410); + } + + // Automaten: ausgefülltes Köderfeld oder zu schnelle Absendung. Keine Speicherung, keine Rückmeldung an das Programm. + $website = $payload['website'] ?? null; + + if ((is_string($website) && trim($website) !== '') || $age < (int) config('communication.min_fill_seconds', 3)) { + if (! (is_string($website) && trim($website) !== '')) { + throw new SubmissionException('Bitte nehmen Sie sich einen Moment Zeit und senden Sie noch einmal.', [], 429); + } + + return ['reference' => 'LF-'.now()->format('ymd').'-'.Str::upper(Str::random(5)), 'created' => false]; + } + + $values = $payload['values'] ?? null; + + if (! is_array($values) || strlen((string) json_encode($values)) > (int) config('communication.max_payload_chars', 40000)) { + throw new SubmissionException('Die Eingaben sind ungültig.'); + } + + $form = $delivered['form']; + $result = $this->process($form, $values); + + $source = $payload['source'] ?? null; + $source = is_string($source) && preg_match('#^/[A-Za-z0-9\-_/.]{0,250}$#', $source) === 1 ? $source : null; + + try { + $inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([ + 'reference' => $this->reference(), + 'entry_id' => $entryId, + 'template_version_id' => $delivered['version']->id, + 'submission_token' => hash('sha256', $token['n']), + 'issue_key' => $result['issue']['key'] ?? null, + 'issue_label' => $result['issue']['label'] ?? null, + 'subissue_key' => $result['subissue']['key'] ?? null, + 'subissue_label' => $result['subissue']['label'] ?? null, + 'contact_name' => $result['contact']['name'] ?? null, + 'contact_email' => $result['contact']['email'] ?? null, + 'contact_phone' => $result['contact']['telefon'] ?? null, + 'organisation' => $result['contact']['organisation'] ?? null, + 'message' => $result['contact']['nachricht'] ?? null, + 'answers' => $result['answers'], + 'source_path' => $source, + 'status' => InquiryStatus::Neu->value, + ])); + } catch (UniqueConstraintViolationException) { + // Doppelt abgesendet, zwischen Prüfung und Speicherung: dieselbe Anfrage melden. + $again = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->firstOrFail(); + + return ['reference' => $again->reference, 'created' => false]; + } + + // Erst nach der Speicherung benachrichtigen. Ein Fehler hier verliert die Anfrage nie. + try { + SendInquiryNotification::dispatch($inquiry->id, url('/verwaltung/anfragen/'.$inquiry->id))->afterCommit(); + } catch (Throwable $e) { + report($e); + $inquiry->forceFill(['notification_error' => 'Die Benachrichtigung konnte nicht eingereiht werden: '.Str::limit($e->getMessage(), 300)])->save(); + } + + return ['reference' => $inquiry->reference, 'created' => true]; + } + + /** + * Wertet das Formular für Eingaben aus und prüft sie. Wird auch von der Vorschau verwendet. + * + * @param array $form + * @param array $values + * @return array{answers: list>, contact: array, issue: ?array, subissue: ?array} + * + * @throws SubmissionException + */ + public function process(array $form, array $values): array + { + $known = array_merge(array_keys((array) $form['fields']), ['anliegen', 'unteranliegen']); + + foreach (array_keys($values) as $key) { + if (! is_string($key) || ! in_array($key, $known, true)) { + throw new SubmissionException('Die Eingaben sind ungültig.'); + } + } + + $state = $this->evaluator->evaluate($form, $values); + $errors = []; + + // Anliegen: Auswahl aus dem zugelassenen Rahmen. Ein abweichender Wert ist eine Manipulation, auch wenn das Feld + // nicht sichtbar ist (zum Beispiel weil nur ein Anliegen zugelassen ist). + if ($state['issue_active']) { + foreach (['anliegen', 'unteranliegen'] as $key) { + $raw = $values[$key] ?? null; + $selected = $key === 'anliegen' ? $state['issue'] : $state['subissue']; + $filled = $raw !== null && $raw !== ''; + + if (! $filled && ($state['required'][$key] ?? false)) { + $errors[$key] = 'Bitte treffen Sie eine Auswahl.'; + } elseif ($filled && $raw !== $selected) { + $errors[$key] = 'Bitte wählen Sie einen der angebotenen Werte.'; + } + } + } + + $answers = []; + $contact = []; + $steps = []; + + foreach ((array) $form['steps'] as $step) { + foreach ($step['items'] as $item) { + if ($item['kind'] !== 'group') { + continue; + } + + foreach ($item['fields'] as $row) { + $key = $row['field']; + $steps[$key] = [$step['title'], $item['label']]; + + if (! ($state['fields'][$key] ?? false)) { + continue; + } + + $field = $form['fields'][$key]; + [$value, $error] = FieldValue::check($field, $values[$key] ?? null, (bool) ($state['required'][$key] ?? false)); + + if ($error !== null) { + $errors[$key] = $error; + + continue; + } + + if ($value === null) { + continue; + } + + $display = FieldValue::display($field, $value); + $answers[] = [ + 'key' => $key, + 'label' => $field['label'], + 'type' => $field['type'], + 'value' => $value, + 'display' => $display, + 'step' => $steps[$key][0], + 'group' => $steps[$key][1], + ]; + + if ($field['purpose'] !== null) { + $contact[$field['purpose']] = $display; + } + } + } + } + + if ($errors !== []) { + throw new SubmissionException('Bitte prüfen Sie Ihre Angaben.', $errors); + } + + $issue = $this->issueEntry($form, $state['issue']); + $subissue = $issue === null ? null : $this->subissueEntry($form, $state['issue'], $state['subissue']); + + $name = $contact['name'] ?? trim(($contact['vorname'] ?? '').' '.($contact['nachname'] ?? '')); + + return [ + 'answers' => $answers, + 'contact' => array_filter([ + 'name' => $name, + 'email' => $contact['email'] ?? null, + 'telefon' => $contact['telefon'] ?? null, + 'organisation' => $contact['organisation'] ?? null, + 'nachricht' => $contact['nachricht'] ?? null, + ], fn (?string $value): bool => $value !== null && $value !== ''), + 'issue' => $issue, + 'subissue' => $subissue, + ]; + } + + /** + * @param array $form + * @return ?array{key: string, label: string} + */ + private function issueEntry(array $form, ?string $key): ?array + { + foreach ((array) $form['issues'] as $issue) { + if ($issue['key'] === $key) { + return ['key' => $issue['key'], 'label' => $issue['label']]; + } + } + + return null; + } + + /** + * @param array $form + * @return ?array{key: string, label: string} + */ + private function subissueEntry(array $form, ?string $issue, ?string $key): ?array + { + foreach ((array) $form['issues'] as $top) { + if ($top['key'] !== $issue) { + continue; + } + + foreach ($top['children'] as $child) { + if ($child['key'] === $key) { + return ['key' => $child['key'], 'label' => $child['label']]; + } + } + } + + return null; + } + + private function reference(): string + { + do { + $reference = 'LF-'.now()->format('ymd').'-'.Str::upper(substr(str_replace(['0', 'O', '1', 'I', 'L'], '', Str::upper(Str::random(12))), 0, 5)); + } while (strlen($reference) < 12 || Inquiry::query()->where('reference', $reference)->exists()); + + return $reference; + } +} diff --git a/app/Domain/Communication/InquiryStatus.php b/app/Domain/Communication/InquiryStatus.php new file mode 100644 index 0000000..4badd04 --- /dev/null +++ b/app/Domain/Communication/InquiryStatus.php @@ -0,0 +1,45 @@ + 'Neu', + self::InBearbeitung => 'In Bearbeitung', + self::RueckfrageOffen => 'Rückfrage offen', + self::Erledigt => 'Erledigt', + }; + } + + public function color(): string + { + return match ($this) { + self::Neu => 'warning', + self::InBearbeitung => 'info', + self::RueckfrageOffen => 'danger', + self::Erledigt => 'success', + }; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/InquiryTemplate.php b/app/Domain/Communication/InquiryTemplate.php new file mode 100644 index 0000000..ee2531a --- /dev/null +++ b/app/Domain/Communication/InquiryTemplate.php @@ -0,0 +1,61 @@ + 'array', 'archived_at' => 'datetime']; + } + + public function versions(): HasMany + { + return $this->hasMany(InquiryTemplateVersion::class, 'template_id')->orderByDesc('version'); + } + + public function publishedVersion(): BelongsTo + { + return $this->belongsTo(InquiryTemplateVersion::class, 'published_version_id'); + } + + public function entries(): HasMany + { + return $this->hasMany(InquiryEntry::class, 'template_id'); + } + + public function isPublished(): bool + { + return $this->published_version_id !== null; + } + + /** Ob der Entwurf von der veröffentlichten Fassung abweicht. */ + public function hasUnpublishedChanges(): bool + { + $version = $this->publishedVersion; + + return $version === null || FormJson::normalize($version->source) !== FormJson::normalize((array) $this->draft); + } + + /** + * @return array + */ + public static function emptyDraft(): array + { + return [ + 'texts' => [], + 'issues' => [], + 'steps' => [], + 'rules' => [], + ]; + } +} diff --git a/app/Domain/Communication/InquiryTemplateVersion.php b/app/Domain/Communication/InquiryTemplateVersion.php new file mode 100644 index 0000000..f6a09cb --- /dev/null +++ b/app/Domain/Communication/InquiryTemplateVersion.php @@ -0,0 +1,34 @@ + 'array', 'source' => 'array', 'published_at' => 'datetime', 'version' => 'integer']; + } + + public function template(): BelongsTo + { + return $this->belongsTo(InquiryTemplate::class, 'template_id'); + } + + protected static function booted(): void + { + // Nur die Bemerkung darf nachträglich ergänzt werden; Löschen ist ausgeschlossen. + static::updating(fn (self $version): bool => array_diff(array_keys($version->getDirty()), ['note']) === []); + static::deleting(fn (): bool => false); + } +} diff --git a/app/Domain/Communication/Keys.php b/app/Domain/Communication/Keys.php new file mode 100644 index 0000000..b7f5750 --- /dev/null +++ b/app/Domain/Communication/Keys.php @@ -0,0 +1,89 @@ + $taken + */ + public static function from(string $label, array $taken = []): string + { + $base = Str::slug($label, '_', 'de'); + $base = preg_replace('/^[^a-z]+/', '', $base) ?? ''; + $base = substr($base, 0, 50); + + if (strlen($base) < 2) { + $base = 'eintrag'; + } + + $taken = array_merge($taken, self::RESERVED); + $key = $base; + $n = 2; + + while (in_array($key, $taken, true)) { + $key = $base.'_'.$n++; + } + + return $key; + } + + /** + * Ergänzt fehlende oder doppelte Kennungen von Auswahlwerten. Bestehende, gültige Kennungen bleiben unverändert, + * damit gespeicherte Antworten und Bedingungen gültig bleiben, auch wenn eine Bezeichnung umbenannt wird. + * + * @param array $options + * @return list + */ + public static function withKeys(array $options): array + { + $result = []; + $taken = []; + + foreach ($options as $option) { + $key = is_array($option) ? ($option['key'] ?? null) : null; + + if (self::valid($key) && ! in_array($key, $taken, true)) { + $taken[] = $key; + } + } + + foreach ($options as $option) { + $option = is_array($option) ? $option : []; + $label = trim((string) ($option['label'] ?? '')); + + if ($label === '') { + continue; + } + + $key = $option['key'] ?? null; + + if (! self::valid($key) || in_array($key, array_column($result, 'key'), true)) { + $key = self::from($label, array_merge($taken, array_column($result, 'key'))); + $taken[] = $key; + } + + $result[] = ['key' => $key, 'label' => mb_substr($label, 0, 120)]; + } + + return $result; + } +} diff --git a/app/Domain/Communication/Publisher.php b/app/Domain/Communication/Publisher.php new file mode 100644 index 0000000..773b378 --- /dev/null +++ b/app/Domain/Communication/Publisher.php @@ -0,0 +1,144 @@ + $definition + * @return list}> + */ + public function affected(InquiryTemplate $template, ?array $definition = null): array + { + $result = []; + + foreach ($template->entries()->whereNull('archived_at')->orderBy('name')->get() as $entry) { + $problems = $definition !== null && $entry->published_config !== null + ? $this->factory->problems($definition, (array) $entry->published_config) + : []; + + $result[] = ['entry' => $entry, 'problems' => $problems]; + } + + return $result; + } + + /** + * Veröffentlicht den Entwurf der Vorlage als neue Fassung. + * + * @throws ValidationException + */ + public function publishTemplate(InquiryTemplate $template, ?User $by = null, ?string $note = null): InquiryTemplateVersion + { + $compiled = $this->compiler->compile((array) $template->draft); + + if ($compiled['definition'] === null) { + throw ValidationException::withMessages(['draft' => $compiled['errors']]); + } + + $blocking = []; + foreach ($this->affected($template, $compiled['definition']) as $row) { + if ($row['entry']->published_config !== null && $row['problems'] !== []) { + $blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zur neuen Fassung: '.implode(' ', $row['problems']); + } + } + + if ($blocking !== []) { + throw ValidationException::withMessages(['draft' => $blocking]); + } + + return DB::transaction(function () use ($template, $compiled, $by, $note): InquiryTemplateVersion { + $template = InquiryTemplate::query()->lockForUpdate()->findOrFail($template->id); + $next = (int) InquiryTemplateVersion::query()->where('template_id', $template->id)->max('version') + 1; + + $version = InquiryTemplateVersion::query()->create([ + 'template_id' => $template->id, + 'version' => $next, + 'definition' => $compiled['definition'], + 'source' => (array) $template->draft, + 'note' => $note !== null && trim($note) !== '' ? mb_substr(trim($note), 0, 300) : null, + 'published_by' => $by?->id, + 'published_at' => now(), + ]); + + $template->forceFill(['published_version_id' => $version->id])->save(); + + return $version; + }); + } + + /** + * Setzt eine frühere Fassung wieder in Kraft (Rückkehr zu einer gültigen Konfiguration). Betroffene Einstiege + * müssen zur Fassung passen, sonst wird abgelehnt. + * + * @throws ValidationException + */ + public function restoreVersion(InquiryTemplate $template, InquiryTemplateVersion $version): void + { + abort_unless($version->template_id === $template->id, 404); + + $blocking = []; + foreach ($this->affected($template, (array) $version->definition) as $row) { + if ($row['entry']->published_config !== null && $row['problems'] !== []) { + $blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zu dieser Fassung: '.implode(' ', $row['problems']); + } + } + + if ($blocking !== []) { + throw ValidationException::withMessages(['draft' => $blocking]); + } + + $template->forceFill(['published_version_id' => $version->id])->save(); + } + + /** + * Veröffentlicht die Konfiguration eines Einstiegs. + * + * @throws ValidationException + */ + public function publishEntry(InquiryEntry $entry): void + { + $template = $entry->template()->with('publishedVersion')->firstOrFail(); + + if ($template->publishedVersion === null) { + throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist noch nicht veröffentlicht. Ein Einstieg kann nur eine veröffentlichte Vorlage verwenden.']]); + } + + if ($template->archived_at !== null) { + throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist archiviert.']]); + } + + $problems = $this->factory->problems((array) $template->publishedVersion->definition, (array) $entry->config); + + if ($problems !== []) { + throw ValidationException::withMessages(['config' => $problems]); + } + + $entry->forceFill([ + 'published_config' => $entry->config, + 'published_at' => $entry->published_at ?? now(), + 'archived_at' => null, + ])->save(); + } + + /** Nimmt einen Einstieg aus dem öffentlichen Angebot; die Konfiguration bleibt erhalten. */ + public function withdrawEntry(InquiryEntry $entry): void + { + $entry->forceFill(['published_config' => null, 'published_at' => null])->save(); + } +} diff --git a/app/Domain/Communication/SubmissionException.php b/app/Domain/Communication/SubmissionException.php new file mode 100644 index 0000000..2b84358 --- /dev/null +++ b/app/Domain/Communication/SubmissionException.php @@ -0,0 +1,19 @@ + Meldung. Der Code entspricht dem HTTP-Status. + */ +final class SubmissionException extends RuntimeException +{ + /** + * @param array $fields + */ + public function __construct(string $message, public readonly array $fields = [], int $code = 422) + { + parent::__construct($message, $code); + } +} diff --git a/app/Domain/Communication/TemplateCompiler.php b/app/Domain/Communication/TemplateCompiler.php new file mode 100644 index 0000000..ad1c4fc --- /dev/null +++ b/app/Domain/Communication/TemplateCompiler.php @@ -0,0 +1,452 @@ + 'Anzeigen, wenn …', + 'hide' => 'Ausblenden, wenn …', + 'require' => 'Pflichtfeld, wenn …', + 'skip' => 'Schritt überspringen, wenn …', + 'preset' => 'Vorbelegen, wenn …', + ]; + + public const OPERATORS = [ + 'eq' => 'ist', + 'neq' => 'ist nicht', + 'in' => 'ist eines von', + 'not_in' => 'ist keines von', + ]; + + /** + * @param array $draft + * @return array{definition: ?array, errors: list} + */ + public function compile(array $draft): array + { + $errors = []; + + $fieldsByKey = InquiryField::query()->offered()->get()->keyBy('key'); + $groupsByKey = InquiryFieldGroup::query()->offered()->get()->keyBy('key'); + $tree = $this->issueTree((array) ($draft['issues'] ?? [])); + + $steps = []; + $fields = []; + $usedFields = []; + $usedGroups = []; + $hasIssue = false; + $position = []; + $order = 0; + $stepKeys = []; + + foreach (array_values((array) ($draft['steps'] ?? [])) as $index => $step) { + $number = $index + 1; + $step = is_array($step) ? $step : []; + $key = (string) ($step['key'] ?? ''); + $title = trim((string) ($step['title'] ?? '')); + + if (! Keys::valid($key) && ! preg_match('/^s[a-z0-9]{3,12}$/', $key)) { + $key = 's'.substr(md5($number.'|'.$title), 0, 6); + } + + if (in_array($key, $stepKeys, true)) { + $errors[] = "Schritt $number: Die Kennung des Schritts kommt doppelt vor."; + } + + $stepKeys[] = $key; + + if ($title === '') { + $title = "Schritt $number"; + } + + $position["step:$key"] = $order++; + $items = []; + + foreach (array_values((array) ($step['items'] ?? [])) as $item) { + $item = is_array($item) ? $item : []; + $kind = (string) ($item['kind'] ?? ''); + + if ($kind === 'issue') { + if ($hasIssue) { + $errors[] = "Schritt $number („{$title}“): Die Auswahl des Anliegens darf nur einmal vorkommen."; + + continue; + } + + $hasIssue = true; + $position['field:anliegen'] = $order++; + $position['field:unteranliegen'] = $order++; + $items[] = ['kind' => 'issue']; + + continue; + } + + if ($kind === 'group') { + $groupKey = (string) ($item['group'] ?? ''); + $group = $groupsByKey[$groupKey] ?? null; + + if ($group === null) { + $errors[] = "Schritt $number („{$title}“): Eine Feldgruppe ist nicht mehr verfügbar (gelöscht, deaktiviert oder archiviert)."; + + continue; + } + + if (isset($usedGroups[$groupKey])) { + $errors[] = "Die Feldgruppe „{$group->name}“ ist mehrfach eingebunden."; + + continue; + } + + $usedGroups[$groupKey] = true; + $position["group:$groupKey"] = $order++; + $rows = []; + + foreach ($group->itemList() as $row) { + $field = $fieldsByKey[$row['field']] ?? null; + + if ($field === null) { + $errors[] = "Die Feldgruppe „{$group->name}“ verwendet ein Feld, das nicht mehr verfügbar ist."; + + continue; + } + + if (isset($usedFields[$field->key])) { + $errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor."; + + continue; + } + + $usedFields[$field->key] = true; + $fields[$field->key] = $field->snapshot(); + $position['field:'.$field->key] = $order++; + $rows[] = ['field' => $field->key, 'required' => $row['required']]; + } + + $items[] = [ + 'kind' => 'group', + 'key' => $group->key, + 'label' => $group->label ?: $group->name, + 'description' => $group->description, + 'fields' => $rows, + ]; + + continue; + } + + if ($kind === 'field') { + $field = $fieldsByKey[(string) ($item['field'] ?? '')] ?? null; + + if ($field === null) { + $errors[] = "Schritt $number („{$title}“): Ein Einzelfeld ist nicht mehr verfügbar."; + + continue; + } + + if (isset($usedFields[$field->key])) { + $errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor."; + + continue; + } + + $usedFields[$field->key] = true; + $fields[$field->key] = $field->snapshot(); + $position['field:'.$field->key] = $order++; + $items[] = [ + 'kind' => 'group', + 'key' => null, + 'label' => null, + 'description' => null, + 'fields' => [['field' => $field->key, 'required' => (bool) ($item['required'] ?? false)]], + ]; + + continue; + } + + $errors[] = "Schritt $number („{$title}“): Ein Baustein hat keinen gültigen Typ."; + } + + if ($items === []) { + $errors[] = "Schritt $number („{$title}“) enthält nichts."; + } + + $steps[] = [ + 'key' => $key, + 'title' => mb_substr($title, 0, 120), + 'intro' => $this->text($step['intro'] ?? null, 600), + 'items' => $items, + ]; + } + + if ($steps === []) { + $errors[] = 'Die Vorlage hat noch keinen Schritt.'; + } + + $purposes = []; + foreach ($fields as $field) { + if ($field['purpose'] !== null) { + $purposes[$field['purpose']][] = $field['key']; + } + } + + if (! isset($purposes[FieldPurpose::Email->value])) { + $errors[] = 'Die Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“, sonst lässt sich eine Anfrage nicht beantworten.'; + } + + foreach ($purposes as $purpose => $keys) { + if (count($keys) > 1) { + $errors[] = 'Die Verwendung „'.FieldPurpose::from($purpose)->label().'“ ist mehreren Feldern zugeordnet.'; + } + } + + if ($hasIssue && $tree === []) { + $errors[] = 'Die Auswahl des Anliegens hat kein verfügbares Anliegen. Bitte Anliegen anlegen oder aktivieren.'; + } + + $rules = $this->rules((array) ($draft['rules'] ?? []), $fields, $tree, $hasIssue, $position, $stepKeys, $usedGroups, $errors); + + $definition = [ + 'v' => 1, + 'texts' => FormTexts::merge(FormTexts::clean((array) ($draft['texts'] ?? []))), + 'has_issue' => $hasIssue, + 'issues' => $hasIssue ? $tree : [], + 'fields' => $fields, + 'steps' => $steps, + 'rules' => $rules, + ]; + + return ['definition' => $errors === [] ? $definition : null, 'errors' => array_values(array_unique($errors))]; + } + + /** + * Vollständige Auflösung ohne Fehlerfreiheit: für die Vorschau eines unfertigen Entwurfs. + * + * @param array $draft + * @return array{definition: ?array, errors: list} + */ + public function preview(array $draft): array + { + return $this->compile($draft); + } + + /** + * @param list $only + * @return list}> + */ + private function issueTree(array $only): array + { + $tree = InquiryIssue::tree(); + + if ($only === []) { + return $tree; + } + + return array_values(array_filter($tree, fn (array $issue): bool => in_array($issue['key'], $only, true))); + } + + /** + * @param array $rules + * @param array> $fields + * @param list> $tree + * @param array $position + * @param list $stepKeys + * @param array $usedGroups + * @param list $errors + * @return list> + */ + private function rules(array $rules, array $fields, array $tree, bool $hasIssue, array $position, array $stepKeys, array $usedGroups, array &$errors): array + { + $normalized = []; + $issueKeys = array_column($tree, 'key'); + $subKeys = []; + foreach ($tree as $issue) { + foreach ($issue['children'] as $child) { + $subKeys[] = $child['key']; + } + } + + foreach (array_values($rules) as $index => $rule) { + $number = $index + 1; + $rule = is_array($rule) ? $rule : []; + $effect = (string) ($rule['effect'] ?? ''); + $target = (string) ($rule['target'] ?? ''); + + if (! isset(self::EFFECTS[$effect])) { + $errors[] = "Regel $number: Die Wirkung ist ungültig."; + + continue; + } + + [$targetKind] = array_pad(explode(':', $target, 2), 2, ''); + + if (! isset($position[$target])) { + $errors[] = "Regel $number: Das Ziel „{$target}“ gibt es in dieser Vorlage nicht."; + + continue; + } + + $kindOk = match ($effect) { + 'show', 'hide' => in_array($targetKind, ['step', 'group', 'field'], true), + 'require', 'preset' => $targetKind === 'field', + 'skip' => $targetKind === 'step', + default => false, + }; + + if (! $kindOk) { + $errors[] = "Regel $number: Die Wirkung „".self::EFFECTS[$effect].'“ passt nicht zum Ziel.'; + + continue; + } + + if (in_array($target, ['field:anliegen', 'field:unteranliegen'], true)) { + $errors[] = "Regel $number: Die Auswahl des Anliegens lässt sich nicht durch eine Regel steuern."; + + continue; + } + + $presetValue = null; + if ($effect === 'preset') { + $field = $fields[substr($target, 6)] ?? null; + $presetValue = $rule['value'] ?? null; + + if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) { + $errors[] = "Regel $number: Vorbelegt werden können nur Einfachauswahl- und Ja/Nein-Felder."; + + continue; + } + + $valid = array_column($field['options'] ?: [['key' => 'ja'], ['key' => 'nein']], 'key'); + if ($field['type'] === 'boolean') { + $valid = ['ja', 'nein']; + } + + if (! is_string($presetValue) || ! in_array($presetValue, $valid, true)) { + $errors[] = "Regel $number: Der Wert zum Vorbelegen ist kein Auswahlwert des Feldes."; + + continue; + } + } + + $match = ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all'; + $conditions = []; + + foreach (array_values((array) ($rule['conditions'] ?? [])) as $c => $condition) { + $condition = is_array($condition) ? $condition : []; + $source = (string) ($condition['source'] ?? ''); + $op = (string) ($condition['op'] ?? 'eq'); + $values = array_values(array_filter((array) ($condition['values'] ?? []), fn (mixed $v): bool => is_string($v) && $v !== '')); + + if (! isset(self::OPERATORS[$op])) { + $errors[] = "Regel $number, Bedingung ".($c + 1).': Der Vergleich ist ungültig.'; + + continue; + } + + if (in_array($op, ['eq', 'neq'], true)) { + $values = array_slice($values, 0, 1); + } + + if ($values === []) { + $errors[] = "Regel $number, Bedingung ".($c + 1).': Es fehlt ein Vergleichswert.'; + + continue; + } + + $sourceKey = "field:$source"; + + if ($source === 'anliegen' || $source === 'unteranliegen') { + if (! $hasIssue) { + $errors[] = "Regel $number: Die Vorlage hat keine Auswahl des Anliegens."; + + continue; + } + + $valid = $source === 'anliegen' ? $issueKeys : $subKeys; + } else { + $field = $fields[$source] ?? null; + + if ($field === null || ! isset($position[$sourceKey])) { + $errors[] = "Regel $number: Die Bedingung bezieht sich auf ein Feld, das es in der Vorlage nicht gibt."; + + continue; + } + + if (! FieldType::from($field['type'])->canControl()) { + $errors[] = "Regel $number: Bedingungen sind nur für Auswahlfelder und Ja/Nein-Felder möglich („{$field['label']}“)."; + + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + } + + if (array_diff($values, $valid) !== []) { + $errors[] = "Regel $number: Ein Vergleichswert ist kein Auswahlwert von „{$source}“."; + + continue; + } + + if ($position[$sourceKey] >= $position[$target]) { + $errors[] = "Regel $number: Die Bedingung „{$source}“ muss in der Vorlage vor ihrem Ziel stehen, sonst kann sie noch nicht ausgewertet werden."; + + continue; + } + + $conditions[] = ['source' => $source, 'op' => $op, 'values' => $values]; + } + + if ($conditions === [] || count($conditions) !== count((array) ($rule['conditions'] ?? []))) { + if ($conditions === []) { + $errors[] = "Regel $number hat keine gültige Bedingung."; + } + + continue; + } + + $normalized[] = [ + 'effect' => $effect, + 'target' => $target, + 'match' => $match, + 'conditions' => $conditions, + 'value' => $presetValue, + ]; + } + + // Widersprüche: gleiche Bedingung zeigt und blendet dasselbe Ziel aus. + $seen = []; + foreach ($normalized as $rule) { + if (! in_array($rule['effect'], ['show', 'hide'], true)) { + continue; + } + + $signature = json_encode([$rule['target'], $rule['match'], $rule['conditions']]); + $opposite = $rule['effect'] === 'show' ? 'hide' : 'show'; + + if (isset($seen[$opposite][$signature])) { + $errors[] = 'Widerspruch: Das Ziel „'.$rule['target'].'“ wird unter derselben Bedingung angezeigt und ausgeblendet.'; + } + + $seen[$rule['effect']][$signature] = true; + } + + return $normalized; + } + + private function text(mixed $value, int $max): ?string + { + if (! is_string($value) || trim($value) === '') { + return null; + } + + return mb_substr(trim($value), 0, $max); + } +} diff --git a/app/Domain/Communication/TemplateDraft.php b/app/Domain/Communication/TemplateDraft.php new file mode 100644 index 0000000..9314146 --- /dev/null +++ b/app/Domain/Communication/TemplateDraft.php @@ -0,0 +1,75 @@ + $draft + * @return array + */ + public static function clean(array $draft): array + { + $steps = []; + + foreach (array_values((array) ($draft['steps'] ?? [])) as $step) { + $step = is_array($step) ? $step : []; + $items = []; + + foreach (array_values((array) ($step['items'] ?? [])) as $item) { + $item = is_array($item) ? $item : []; + $kind = (string) ($item['kind'] ?? ''); + + $items[] = match ($kind) { + 'issue' => ['kind' => 'issue'], + 'group' => ['kind' => 'group', 'group' => (string) ($item['group'] ?? '')], + 'field' => ['kind' => 'field', 'field' => (string) ($item['field'] ?? ''), 'required' => (bool) ($item['required'] ?? false)], + default => ['kind' => $kind], + }; + } + + $steps[] = [ + 'key' => (string) ($step['key'] ?? ''), + 'title' => mb_substr(trim((string) ($step['title'] ?? '')), 0, 120), + 'intro' => filled($step['intro'] ?? null) ? mb_substr(trim((string) $step['intro']), 0, 600) : null, + 'items' => $items, + ]; + } + + $rules = []; + + foreach (array_values((array) ($draft['rules'] ?? [])) as $rule) { + $rule = is_array($rule) ? $rule : []; + $conditions = []; + + foreach (array_values((array) ($rule['conditions'] ?? [])) as $condition) { + $condition = is_array($condition) ? $condition : []; + $conditions[] = [ + 'source' => (string) ($condition['source'] ?? ''), + 'op' => (string) ($condition['op'] ?? 'eq'), + 'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')), + ]; + } + + $rules[] = [ + 'effect' => (string) ($rule['effect'] ?? ''), + 'target' => (string) ($rule['target'] ?? ''), + 'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all', + 'conditions' => $conditions, + 'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null, + ]; + } + + return [ + 'texts' => FormTexts::clean((array) ($draft['texts'] ?? [])), + 'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')), + 'steps' => $steps, + 'rules' => $rules, + ]; + } +} diff --git a/app/Filament/Pages/KommunikationEinstellungen.php b/app/Filament/Pages/KommunikationEinstellungen.php new file mode 100644 index 0000000..29c240b --- /dev/null +++ b/app/Filament/Pages/KommunikationEinstellungen.php @@ -0,0 +1,191 @@ +|null */ + public ?array $data = []; + + public static function canAccess(): bool + { + return CommunicationAccess::inbox(); + } + + public function getTitle(): string|Htmlable + { + return 'Kommunikation: Einstellungen'; + } + + public function getSubheading(): string|Htmlable|null + { + return 'Wer bei einer neuen Anfrage benachrichtigt wird und wie lange Anfragen aufbewahrt werden.'; + } + + public function mount(): void + { + $settings = CommunicationSettings::current(); + + $this->form->fill([ + 'recipients' => implode("\n", (array) $settings->recipients), + 'retention_months' => $settings->retention_months, + ]); + } + + public function form(Schema $schema): Schema + { + return $schema + ->components([ + Section::make('Benachrichtigung')->schema([ + Textarea::make('recipients')->label('Empfänger der internen Benachrichtigung')->rows(4) + ->helperText('Eine E-Mail-Adresse je Zeile. Die Benachrichtigung nennt nur Kennzeichen und Anliegen, nie Kontaktdaten oder Antworten. Ohne Empfänger werden Anfragen trotzdem gespeichert; der Posteingang weist dann auf die fehlende Benachrichtigung hin.') + ->rule(fn (): \Closure => function (string $attribute, mixed $value, \Closure $fail): void { + foreach (self::lines((string) $value) as $address) { + if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) { + $fail('„'.$address.'“ ist keine gültige E-Mail-Adresse.'); + + return; + } + } + + if (count(self::lines((string) $value)) > 10) { + $fail('Bitte höchstens zehn Empfänger.'); + } + }), + ]), + Section::make('Weitere Bausteine')->description('Anliegen und der gemeinsame Feldkatalog gehören zu den Formularen. Im Formular-Editor müssen sie nicht geöffnet werden; hier lassen sie sich einsehen und ordnen.') + ->visible(fn (): bool => CommunicationAccess::configure()) + ->collapsed() + ->schema([ + Actions::make([ + Action::make('issues')->label('Anliegen')->url(InquiryIssueResource::getUrl('index'))->color('gray'), + Action::make('fields')->label('Feldkatalog')->url(InquiryFieldResource::getUrl('index'))->color('gray'), + Action::make('groups')->label('Feldgruppen')->url(InquiryFieldGroupResource::getUrl('index'))->color('gray'), + Action::make('entries')->label('Anfrage-Einstiege (ältere Seiten)')->url(InquiryEntryResource::getUrl('index'))->color('gray'), + ]), + ]), + Section::make('Aufbewahrung')->schema([ + TextInput::make('retention_months')->label('Anfragen löschen nach … Monaten')->numeric()->minValue(1)->maxValue(120) + ->helperText('Leer: Anfragen werden nicht automatisch gelöscht. Der Befehl „php artisan communication:purge“ löscht Anfragen, die älter sind. Einzelne Anfragen lassen sich jederzeit im Posteingang löschen. Die Dauer ist mit dem Datenschutzkonzept abzustimmen.'), + ]), + ]) + ->statePath('data'); + } + + public function content(Schema $schema): Schema + { + return $schema->components([ + Form::make([EmbeddedSchema::make('form')]) + ->id('form') + ->livewireSubmitHandler('save') + ->footer([Actions::make([Action::make('save')->label('Einstellungen speichern')->submit('save')->keyBindings(['mod+s'])])]), + ]); + } + + public function save(): void + { + $data = $this->form->getState(); + + CommunicationSettings::current()->update([ + 'recipients' => self::lines((string) ($data['recipients'] ?? '')), + 'retention_months' => filled($data['retention_months'] ?? null) ? (int) $data['retention_months'] : null, + ]); + + Notification::make()->title('Die Einstellungen sind gespeichert.')->success()->send(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('test') + ->label('Testnachricht senden') + ->icon('heroicon-o-envelope') + ->color('gray') + ->requiresConfirmation() + ->modalDescription('Sendet eine Testnachricht an die gespeicherten Empfänger. Sie enthält keine Anfragedaten.') + ->action(function (): void { + $recipients = CommunicationSettings::current()->recipientList(); + + if ($recipients === []) { + Notification::make()->title('Es sind noch keine Empfänger gespeichert.')->warning()->send(); + + return; + } + + try { + Mail::to($recipients)->send(new CommunicationTestMail); + } catch (Throwable $e) { + report($e); + Notification::make()->title('Der Versand ist fehlgeschlagen.')->body($e->getMessage())->danger()->send(); + + return; + } + + Notification::make()->title('Die Testnachricht ist abgesendet.')->body('Der Mailserver hat sie angenommen. Ob sie ankommt, zeigt dein Postfach.')->success()->send(); + }), + Action::make('example') + ->label('Beispielkonfiguration anlegen') + ->icon('heroicon-o-sparkles') + ->color('gray') + ->visible(fn (): bool => ExampleConfiguration::isEmpty()) + ->requiresConfirmation() + ->modalHeading('Beispielkonfiguration anlegen?') + ->modalDescription('Legt Anliegen, Felder, Feldgruppen, vier Anfragevorlagen und fünf Anfrage-Einstiege (Allgemeiner Kontakt, Kurse & Workshops, Schul-AG, Programme & Materialien, Kooperation) an und veröffentlicht sie. Alles lässt sich danach ändern. Das geht nur, solange die Kommunikationsverwaltung noch leer ist.') + ->action(function (): void { + try { + app(ExampleConfiguration::class)->install(CommunicationAccess::user()); + } catch (RuntimeException $e) { + Notification::make()->title($e->getMessage())->danger()->send(); + + return; + } + + Notification::make()->title('Die Beispielkonfiguration ist angelegt und veröffentlicht.')->success()->send(); + $this->redirect(static::getUrl()); + }), + ]; + } + + /** + * @return list + */ + private static function lines(string $text): array + { + return array_values(array_unique(array_filter(array_map('trim', preg_split('/[\r\n,;]+/', $text) ?: []), fn (string $line): bool => $line !== ''))); + } +} diff --git a/app/Filament/Resources/Communication/CommunicationResource.php b/app/Filament/Resources/Communication/CommunicationResource.php new file mode 100644 index 0000000..34d5c31 --- /dev/null +++ b/app/Filament/Resources/Communication/CommunicationResource.php @@ -0,0 +1,46 @@ +components([ + TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120) + ->helperText('So heißt der Einstieg in der Auswahl im CMS, zum Beispiel „Kurse & Workshops“.'), + Select::make('template_id')->label('Anfragevorlage')->required()->live() + ->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all()) + ->helperText('Die Formularstruktur kommt aus der veröffentlichten Fassung dieser Vorlage und folgt jeder neu veröffentlichten Fassung.'), + Section::make('Angebotene Anliegen')->description('Der Rahmen, in dem Besucher wählen. Ist nur ein Anliegen zugelassen, müssen sie es nicht bestätigen.')->schema([ + Select::make('config.allowed_issues')->label('Zugelassene Anliegen')->multiple() + ->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all()) + ->helperText('Leer: alle Anliegen der Vorlage.'), + Select::make('config.allowed_subissues')->label('Zugelassene Unteranliegen')->multiple() + ->options(function (): array { + $options = []; + + foreach (InquiryIssue::tree() as $issue) { + foreach ($issue['children'] as $child) { + $options[$child['key']] = $issue['label'].' › '.$child['label']; + } + } + + return $options; + }) + ->helperText('Leer: alle Unteranliegen der zugelassenen Anliegen.'), + Repeater::make('config.preselect') + ->label('Vorauswahl') + ->helperText('Zum Beispiel das Kursformat „Schul-AG“. Besucher können die Auswahl ändern.') + ->schema([ + Select::make('field')->label('Angabe')->required()->live()->searchable()->distinct() + ->options(fn (): array => ['anliegen' => 'Anliegen', 'unteranliegen' => 'Unteranliegen'] + InquiryField::query()->offered()->whereIn('type', ['select', 'boolean'])->orderBy('name')->pluck('name', 'key')->all()), + Select::make('value')->label('Wert')->required() + ->options(function (Get $get): array { + $field = (string) $get('field'); + + if ($field === 'anliegen') { + return InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all(); + } + + if ($field === 'unteranliegen') { + return InquiryIssue::query()->offered()->whereNotNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all(); + } + + $model = InquiryField::query()->where('key', $field)->first(); + + return $model === null ? [] : collect($model->optionList())->pluck('label', 'key')->all(); + }), + ]) + ->addActionLabel('Vorauswahl hinzufügen') + ->itemLabel(fn (array $state): ?string => ($state['field'] ?? null) ? ($state['field'] === 'anliegen' ? 'Anliegen' : ($state['field'] === 'unteranliegen' ? 'Unteranliegen' : InquiryField::query()->where('key', $state['field'])->value('name'))) : null), + ]), + Section::make('Darstellung')->schema([ + Select::make('config.mode')->label('Formularart')->required()->default('compact') + ->options(['compact' => 'Kompaktformular: alle Fragen auf einer Seite', 'wizard' => 'Mehrstufiger Dialog: Schritt für Schritt mit Zusammenfassung']) + ->helperText('Beides verwendet dieselbe Vorlage, dieselben Bedingungen und dieselbe Prüfung.'), + Select::make('config.open')->label('Beim Aufruf der Seite')->required()->default('inline') + ->options(['inline' => 'Formular direkt anzeigen', 'button' => 'Zunächst nur eine Schaltfläche zeigen, die das Formular öffnet']), + ]), + Section::make('Texte dieses Einstiegs') + ->description('Überschreibt einzelne Texte der Vorlage. Leer lassen: es gilt der Text der Vorlage. Die Texte werden ausschließlich hier und in der Vorlage gepflegt, nie im CMS.') + ->collapsed() + ->schema(self::textFields()), + Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryEntry $record): string => (string) $record?->key) + ->visible(fn (?InquiryEntry $record): bool => $record !== null), + ]); + } + + /** + * @return list + */ + private static function textFields(): array + { + $fields = []; + + foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) { + $field = $multiline + ? Textarea::make("config.texts.$key")->rows(2)->maxLength(1500) + : TextInput::make("config.texts.$key")->maxLength(200); + + $fields[] = $field->label($label)->placeholder('Text der Vorlage'.($default !== '' ? ': '.$default : ''))->helperText($help); + } + + return $fields; + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('name')->label('Bezeichnung')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryEntries::route('/'), + 'edit' => EditInquiryEntry::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Entries/Pages/EditInquiryEntry.php b/app/Filament/Resources/Communication/Entries/Pages/EditInquiryEntry.php new file mode 100644 index 0000000..94d7148 --- /dev/null +++ b/app/Filament/Resources/Communication/Entries/Pages/EditInquiryEntry.php @@ -0,0 +1,147 @@ +getRecord(); + + if ($entry->archived_at !== null) { + return 'Archiviert.'; + } + + if ($entry->published_at === null) { + return 'Entwurf. Im CMS lässt sich dieser Einstieg erst nach „Veröffentlichen“ auswählen.'; + } + + if (! $entry->isLive()) { + return 'Veröffentlicht, wird aber nicht ausgeliefert: Die Anfragevorlage hat keine gültige Fassung.'; + } + + return 'Veröffentlicht seit '.$entry->published_at->format('d.m.Y').'.'.($entry->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : ''); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('preview') + ->label('Vorschau') + ->icon('heroicon-o-eye') + ->color('gray') + ->tooltip('Zeigt den zuletzt gespeicherten Entwurf des Einstiegs mit der gültigen Fassung der Vorlage. Es wird nichts gesendet.') + ->url(fn (): string => route('communication.preview.entry', $this->getRecord())) + ->openUrlInNewTab(), + Action::make('publish') + ->label('Veröffentlichen') + ->color('primary') + ->visible(fn (): bool => $this->getRecord()->archived_at === null) + ->requiresConfirmation() + ->modalHeading('Anfrage-Einstieg veröffentlichen') + ->modalDescription('Speichert den Entwurf und macht ihn wirksam. Alle Seiten, die diesen Einstieg einbinden, zeigen danach den neuen Stand.') + ->action(function (): void { + $this->save(shouldRedirect: false, shouldSendSavedNotification: false); + + try { + app(Publisher::class)->publishEntry($this->getRecord()); + } catch (ValidationException $e) { + Notification::make()->title('Der Einstieg lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['config'] ?? []))))->danger()->persistent()->send(); + + return; + } + + Notification::make()->title('Der Einstieg ist veröffentlicht.')->success()->send(); + $this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()])); + }), + Action::make('withdraw') + ->label('Zurückziehen') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->published_at !== null) + ->requiresConfirmation() + ->modalDescription('Der Einstieg wird nicht mehr ausgeliefert; Seiten, die ihn einbinden, zeigen kein Formular. Die Konfiguration bleibt als Entwurf erhalten.') + ->action(function (): void { + app(Publisher::class)->withdrawEntry($this->getRecord()); + Notification::make()->title('Der Einstieg ist zurückgezogen.')->success()->send(); + $this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()])); + }), + ...$this->archiveActions(), + ]; + } + + protected function archiveNote(): string + { + return 'Der Einstieg wird archiviert und nicht mehr ausgeliefert. Eingegangene Anfragen bleiben unverändert.'; + } + + protected function archiveAttributes(): array + { + return ['archived_at' => now(), 'published_config' => null, 'published_at' => null]; + } + + protected function indexUrl(): string + { + return InquiryEntryResource::getUrl('index'); + } + + protected function mutateFormDataBeforeFill(array $data): array + { + $config = array_merge(InquiryEntry::emptyConfig(), (array) ($data['config'] ?? [])); + $preselect = []; + + foreach ((array) ($config['defaults'] ?? []) as $field => $value) { + $preselect[] = ['field' => $field, 'value' => $value]; + } + + $config['preselect'] = $preselect; + $data['config'] = $config; + + return $data; + } + + protected function mutateFormDataBeforeSave(array $data): array + { + $config = (array) ($data['config'] ?? []); + $defaults = []; + + foreach (array_values((array) ($config['preselect'] ?? [])) as $row) { + if (is_array($row) && filled($row['field'] ?? null) && filled($row['value'] ?? null)) { + $defaults[(string) $row['field']] = (string) $row['value']; + } + } + + $data['config'] = [ + 'mode' => ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact', + 'open' => ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline', + 'allowed_issues' => array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')), + 'allowed_subissues' => array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')), + 'defaults' => $defaults, + 'texts' => FormTexts::clean((array) ($config['texts'] ?? [])), + ]; + + return $data; + } + + protected function getRedirectUrl(): ?string + { + return null; + } +} diff --git a/app/Filament/Resources/Communication/Entries/Pages/ListInquiryEntries.php b/app/Filament/Resources/Communication/Entries/Pages/ListInquiryEntries.php new file mode 100644 index 0000000..6840f3f --- /dev/null +++ b/app/Filament/Resources/Communication/Entries/Pages/ListInquiryEntries.php @@ -0,0 +1,112 @@ +label('Einstieg anlegen') + ->modalHeading('Neuer Anfrage-Einstieg') + ->modalDescription('Zugelassene Anliegen, Vorauswahl und Texte legst du danach fest.') + ->modalSubmitActionLabel('Einstieg anlegen') + ->schema([ + TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120), + Select::make('template_id')->label('Anfragevorlage')->required() + ->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all()), + ]) + ->action(function (array $data): void { + $entry = InquiryEntry::query()->create([ + 'key' => Keys::from($data['name'], InquiryEntry::query()->pluck('key')->all()), + 'name' => $data['name'], + 'template_id' => $data['template_id'], + 'config' => InquiryEntry::emptyConfig(), + ]); + + Notification::make()->title('Der Einstieg ist angelegt.')->success()->send(); + $this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $entry])); + }), + ]; + } + + protected function catalogRows(): array + { + $rows = []; + + foreach (InquiryEntry::query()->with('template.publishedVersion')->orderBy('name')->get() as $entry) { + $url = InquiryEntryResource::getUrl('edit', ['record' => $entry]); + $archived = $entry->archived_at !== null; + $live = $entry->isLive(); + $config = (array) ($entry->published_config ?? $entry->config); + $mode = ($config['mode'] ?? 'compact') === 'wizard' ? 'Mehrstufiger Dialog' : 'Kompaktformular'; + + $rows[] = [ + 'schluessel' => 'e'.$entry->id, + 'titel' => $entry->name, + 'meta' => 'Anfrage-Einstieg · '.$mode.' · Vorlage „'.$entry->template->name.'“', + 'text' => '', + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + $archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($live + ? ['label' => 'Veröffentlicht', 'ton' => 'gut'] + : ($entry->published_at !== null ? ['label' => 'Veröffentlicht, aber Vorlage nicht gültig', 'ton' => 'achtung'] : ['label' => 'Entwurf', 'ton' => 'offen'])), + $entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null, + ])), + 'zustand' => [$archived ? 'archiviert' : ($live ? 'veroeffentlicht' : 'entwurf'), ...($entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['aenderungen'] : [])], + 'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Zustand', + 'veroeffentlicht' => 'Veröffentlicht', + 'entwurf' => 'Entwurf', + 'aenderungen' => 'Mit unveröffentlichten Änderungen', + 'archiviert' => 'Archiviert', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung'; + } + + protected function einheit(): array + { + return ['Anfrage-Einstieg', 'Anfrage-Einstiege']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Anfrage-Einstiege', 'text' => 'Mit „Einstieg anlegen“ oben entsteht der erste Einstieg. Dazu braucht es eine veröffentlichte Anfragevorlage.']; + } +} diff --git a/app/Filament/Resources/Communication/Fields/InquiryFieldResource.php b/app/Filament/Resources/Communication/Fields/InquiryFieldResource.php new file mode 100644 index 0000000..c1a8ef3 --- /dev/null +++ b/app/Filament/Resources/Communication/Fields/InquiryFieldResource.php @@ -0,0 +1,126 @@ + + */ + public static function optionsFields(): array + { + return [ + Repeater::make('options') + ->label('Auswahlwerte') + ->schema([ + Hidden::make('key'), + TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120), + ]) + ->minItems(1) + ->reorderableWithButtons() + ->addActionLabel('Auswahlwert hinzufügen') + ->itemLabel(fn (array $state): ?string => $state['label'] ?? null) + ->helperText('Reihenfolge wie hier. Jeder Wert erhält eine feste interne Kennung; eine Umbenennung ändert sie nicht und beschädigt keine Anfragen.') + ->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false) + ->required(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false), + ]; + } + + public static function form(Schema $schema): Schema + { + return $schema->components([ + Section::make('Feld')->schema([ + TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120) + ->helperText('Nur für die Verwaltung, zum Beispiel „Postleitzahl (Einrichtung)“.'), + TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200) + ->helperText('So heißt das Feld im Formular.'), + Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600) + ->helperText('Steht unter der Beschriftung.'), + Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live() + ->disabled(fn (?InquiryField $record): bool => $record !== null) + ->dehydrated(fn (?InquiryField $record): bool => $record === null) + ->helperText('Nach dem Anlegen nicht mehr änderbar, weil Bedingungen und Gruppen darauf aufbauen.'), + ...self::optionsFields(), + TextInput::make('settings.max_length')->label('Höchste Textlänge')->numeric()->minValue(1)->maxValue(8000) + ->visible(fn (Get $get): bool => in_array($get('type'), ['text', 'textarea'], true)) + ->helperText('Leer: Vorgabe (200 Zeichen einzeilig, 4000 mehrzeilig).'), + TextInput::make('settings.min')->label('Kleinster Wert')->numeric() + ->visible(fn (Get $get): bool => $get('type') === 'number'), + TextInput::make('settings.max')->label('Größter Wert')->numeric() + ->visible(fn (Get $get): bool => $get('type') === 'number'), + Select::make('purpose')->label('Verwendung in der Anfrageübersicht')->options(FieldPurpose::options())->placeholder('Keine besondere Verwendung') + ->helperText('Welche Angabe der Posteingang als Name, E-Mail-Adresse oder Nachricht der Anfrage zeigt. Jede Vorlage braucht ein Feld „E-Mail-Adresse für Rückfragen“.') + ->rule(fn (Get $get): Closure => function (string $attribute, mixed $value, Closure $fail) use ($get): void { + $type = FieldType::tryFrom((string) $get('type')); + + if ($value !== null && $type !== null && ! in_array($type, FieldPurpose::from($value)->types(), true)) { + $fail('Diese Verwendung passt nicht zum Feldtyp „'.$type->label().'“.'); + } + }), + Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryField $record): string => (string) $record?->key) + ->visible(fn (?InquiryField $record): bool => $record !== null) + ->helperText('Ändert sich nie.'), + Toggle::make('active')->label('Zur Verwendung anbieten') + ->helperText('Ausgeschaltet kann das Feld in keiner neuen Fassung einer Vorlage verwendet werden; bestehende Fassungen und Anfragen bleiben unverändert.'), + ]), + ]); + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('name')->label('Bezeichnung')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryFields::route('/'), + 'edit' => EditInquiryField::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Fields/Pages/EditInquiryField.php b/app/Filament/Resources/Communication/Fields/Pages/EditInquiryField.php new file mode 100644 index 0000000..4789ff4 --- /dev/null +++ b/app/Filament/Resources/Communication/Fields/Pages/EditInquiryField.php @@ -0,0 +1,55 @@ +archiveActions(); + } + + protected function archiveNote(): string + { + return 'Das Feld kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.'; + } + + protected function indexUrl(): string + { + return InquiryFieldResource::getUrl('index'); + } + + protected function mutateFormDataBeforeSave(array $data): array + { + /** @var InquiryField $record */ + $record = $this->getRecord(); + $type = $record->type; + + $data['options'] = $type->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null; + + $settings = array_filter((array) ($data['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== ''); + $data['settings'] = match ($type) { + FieldType::Text, FieldType::Textarea => array_intersect_key($settings, ['max_length' => true]), + FieldType::Number => array_intersect_key($settings, ['min' => true, 'max' => true]), + default => [], + }; + + return $data; + } + + protected function getRedirectUrl(): ?string + { + return InquiryFieldResource::getUrl('index'); + } +} diff --git a/app/Filament/Resources/Communication/Fields/Pages/ListInquiryFields.php b/app/Filament/Resources/Communication/Fields/Pages/ListInquiryFields.php new file mode 100644 index 0000000..221fabb --- /dev/null +++ b/app/Filament/Resources/Communication/Fields/Pages/ListInquiryFields.php @@ -0,0 +1,117 @@ +label('Feld anlegen') + ->modalHeading('Neues Feld') + ->modalDescription('Weitere Angaben wie Hilfetext, Grenzen oder die Verwendung in der Anfrageübersicht legst du danach fest.') + ->modalSubmitActionLabel('Feld anlegen') + ->schema([ + TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120), + TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200), + Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live(), + ...InquiryFieldResource::optionsFields(), + ]) + ->action(function (array $data): void { + $field = InquiryField::query()->create([ + 'key' => Keys::from($data['name'], InquiryField::query()->pluck('key')->all()), + 'name' => $data['name'], + 'label' => $data['label'], + 'type' => $data['type'], + 'options' => FieldType::from($data['type'])->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null, + ]); + + Notification::make()->title('Das Feld ist angelegt.')->success()->send(); + $this->redirect(InquiryFieldResource::getUrl('edit', ['record' => $field])); + }), + ]; + } + + protected function catalogRows(): array + { + $usage = []; + foreach (InquiryFieldGroup::query()->get() as $group) { + foreach ($group->itemList() as $item) { + $usage[$item['field']] = ($usage[$item['field']] ?? 0) + 1; + } + } + + $rows = []; + + foreach (InquiryField::query()->orderBy('name')->get() as $field) { + $url = InquiryFieldResource::getUrl('edit', ['record' => $field]); + $state = $field->archived_at !== null ? 'archiviert' : ($field->active ? 'aktiv' : 'inaktiv'); + $used = $usage[$field->key] ?? 0; + $rows[] = [ + 'schluessel' => 'f'.$field->id, + 'titel' => $field->name, + 'meta' => $field->type->label().' · '.$field->key, + 'text' => $field->label, + 'suchtext' => $field->key.' '.$field->label, + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + match ($state) { + 'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'], + 'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'], + default => ['label' => 'Archiviert', 'ton' => 'leise'], + }, + ['label' => $used === 0 ? 'In keiner Feldgruppe' : ($used === 1 ? 'In 1 Feldgruppe' : "In $used Feldgruppen"), 'ton' => 'neutral'], + $field->purpose !== null ? ['label' => $field->purpose->label(), 'ton' => 'neutral'] : null, + ])), + 'zustand' => [$state, 'typ_'.$field->type->value], + 'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert']; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung, Beschriftung oder Kennung'; + } + + protected function einheit(): array + { + return ['Feld', 'Felder']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Felder', 'text' => 'Mit „Feld anlegen“ oben entsteht das erste Feld, zum Beispiel „E-Mail-Adresse“.']; + } +} diff --git a/app/Filament/Resources/Communication/Groups/InquiryFieldGroupResource.php b/app/Filament/Resources/Communication/Groups/InquiryFieldGroupResource.php new file mode 100644 index 0000000..e431d07 --- /dev/null +++ b/app/Filament/Resources/Communication/Groups/InquiryFieldGroupResource.php @@ -0,0 +1,86 @@ +components([ + TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120) + ->helperText('Nur für die Verwaltung, zum Beispiel „Kindergruppe“.'), + TextInput::make('label')->label('Überschrift im Formular (optional)')->maxLength(200) + ->helperText('Leer: die fachliche Bezeichnung.'), + Textarea::make('description')->label('Erläuterung im Formular (optional)')->rows(2)->maxLength(600), + Repeater::make('items') + ->label('Felder der Gruppe') + ->schema([ + Select::make('field')->label('Feld')->required()->searchable()->distinct() + ->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->get()->mapWithKeys( + fn (InquiryField $field): array => [$field->key => $field->name.' ('.$field->type->label().')'] + )->all()), + Toggle::make('required')->label('Pflichtfeld')->default(false) + ->helperText('Eine Vorlage kann ein Feld zusätzlich unter einer Bedingung zur Pflicht machen.'), + ]) + ->minItems(1) + ->reorderableWithButtons() + ->addActionLabel('Feld hinzufügen') + ->itemLabel(fn (array $state): ?string => InquiryField::query()->where('key', $state['field'] ?? '')->value('name')) + ->helperText('Die Reihenfolge hier ist die Reihenfolge im Formular.'), + Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryFieldGroup $record): string => (string) $record?->key) + ->visible(fn (?InquiryFieldGroup $record): bool => $record !== null), + Toggle::make('active')->label('Zur Verwendung anbieten'), + ]); + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('name')->label('Bezeichnung')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryFieldGroups::route('/'), + 'edit' => EditInquiryFieldGroup::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Groups/Pages/EditInquiryFieldGroup.php b/app/Filament/Resources/Communication/Groups/Pages/EditInquiryFieldGroup.php new file mode 100644 index 0000000..b3544fc --- /dev/null +++ b/app/Filament/Resources/Communication/Groups/Pages/EditInquiryFieldGroup.php @@ -0,0 +1,34 @@ +archiveActions(); + } + + protected function archiveNote(): string + { + return 'Die Gruppe kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.'; + } + + protected function indexUrl(): string + { + return InquiryFieldGroupResource::getUrl('index'); + } + + protected function getRedirectUrl(): ?string + { + return InquiryFieldGroupResource::getUrl('index'); + } +} diff --git a/app/Filament/Resources/Communication/Groups/Pages/ListInquiryFieldGroups.php b/app/Filament/Resources/Communication/Groups/Pages/ListInquiryFieldGroups.php new file mode 100644 index 0000000..9e47977 --- /dev/null +++ b/app/Filament/Resources/Communication/Groups/Pages/ListInquiryFieldGroups.php @@ -0,0 +1,139 @@ +label('Feldgruppe anlegen') + ->modalHeading('Neue Feldgruppe') + ->modalDescription('Die Felder legst du danach auf der Seite der Gruppe fest.') + ->modalSubmitActionLabel('Feldgruppe anlegen') + ->schema([TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)]) + ->action(function (array $data): void { + $group = InquiryFieldGroup::query()->create([ + 'key' => Keys::from($data['name'], InquiryFieldGroup::query()->pluck('key')->all()), + 'name' => $data['name'], + 'items' => [], + 'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10, + ]); + + Notification::make()->title('Die Feldgruppe ist angelegt.')->success()->send(); + $this->redirect(InquiryFieldGroupResource::getUrl('edit', ['record' => $group])); + }), + ]; + } + + public function moveGroup(int $id, string $direction): void + { + $group = InquiryFieldGroup::query()->findOrFail($id); + $all = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get()->values(); + $index = $all->search(fn (InquiryFieldGroup $item): bool => $item->id === $group->id); + $target = $direction === 'up' ? $index - 1 : $index + 1; + + if ($index === false || $target < 0 || $target >= $all->count()) { + return; + } + + $order = $all->all(); + [$order[$index], $order[$target]] = [$order[$target], $order[$index]]; + + foreach ($order as $position => $item) { + $item->forceFill(['sort_order' => ($position + 1) * 10])->save(); + } + } + + protected function catalogRows(): array + { + $templates = InquiryTemplate::query()->get(['id', 'draft']); + $names = InquiryField::query()->pluck('name', 'key'); + $groups = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get(); + $rows = []; + + foreach ($groups as $i => $group) { + $url = InquiryFieldGroupResource::getUrl('edit', ['record' => $group]); + $state = $group->archived_at !== null ? 'archiviert' : ($group->active ? 'aktiv' : 'inaktiv'); + $used = $templates->filter(function (InquiryTemplate $template) use ($group): bool { + foreach ((array) ($template->draft['steps'] ?? []) as $step) { + foreach ((array) ($step['items'] ?? []) as $item) { + if (($item['group'] ?? null) === $group->key) { + return true; + } + } + } + + return false; + })->count(); + $fieldNames = array_map(fn (array $item): string => (string) ($names[$item['field']] ?? $item['field']), $group->itemList()); + + $rows[] = [ + 'schluessel' => 'g'.$group->id, + 'titel' => $group->name, + 'meta' => 'Feldgruppe · '.count($fieldNames).' '.(count($fieldNames) === 1 ? 'Feld' : 'Felder'), + 'text' => implode(', ', $fieldNames), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => [ + match ($state) { + 'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'], + 'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'], + default => ['label' => 'Archiviert', 'ton' => 'leise'], + }, + ['label' => $used === 0 ? 'In keiner Vorlage' : ($used === 1 ? 'In 1 Vorlage' : "In $used Vorlagen"), 'ton' => 'neutral'], + ], + 'zustand' => [$state], + 'aktionen' => [ + ['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'], + ...($i > 0 ? [['label' => 'Nach oben', 'wire' => "moveGroup({$group->id}, 'up')"]] : []), + ...($i < $groups->count() - 1 ? [['label' => 'Nach unten', 'wire' => "moveGroup({$group->id}, 'down')"]] : []), + ], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert']; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung oder Feldname'; + } + + protected function einheit(): array + { + return ['Feldgruppe', 'Feldgruppen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Feldgruppen', 'text' => 'Mit „Feldgruppe anlegen“ oben entsteht die erste Gruppe, zum Beispiel „Kontaktinformationen“.']; + } +} diff --git a/app/Filament/Resources/Communication/Inquiries/InquiryResource.php b/app/Filament/Resources/Communication/Inquiries/InquiryResource.php new file mode 100644 index 0000000..c3d8de5 --- /dev/null +++ b/app/Filament/Resources/Communication/Inquiries/InquiryResource.php @@ -0,0 +1,144 @@ +where('status', 'neu')->count(); + + return $new > 0 ? (string) $new : null; + } + + public static function getNavigationBadgeTooltip(): ?string + { + return 'Neue Anfragen'; + } + + public static function infolist(Schema $schema): Schema + { + return $schema->components([ + Section::make('Ansprechpartner')->columns(2)->schema([ + TextEntry::make('contact_name')->label('Name')->placeholder('Nicht angegeben'), + TextEntry::make('organisation')->label('Organisation')->placeholder('Nicht angegeben'), + TextEntry::make('contact_email')->label('E-Mail-Adresse')->placeholder('Nicht angegeben')->copyable(), + TextEntry::make('contact_phone')->label('Telefon')->placeholder('Nicht angegeben'), + ]), + Section::make('Anliegen')->columns(2)->schema([ + TextEntry::make('issue')->label('Anliegen')->state(fn (Inquiry $record): string => $record->issueTitle() ?: 'Nicht erfragt'), + TextEntry::make('status')->label('Bearbeitungsstatus')->badge() + ->formatStateUsing(fn ($state): string => $state->label()) + ->color(fn ($state): string => $state->color()), + TextEntry::make('channel')->label('Eingegangen über')->state(fn (Inquiry $record): string => $record->channelTitle()), + TextEntry::make('source_path')->label('Quellseite')->placeholder('Unbekannt'), + TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i'), + TextEntry::make('reference')->label('Kennzeichen')->copyable(), + TextEntry::make('version')->label('Formularfassung') + ->state(fn (Inquiry $record): string => 'Vorlage „'.($record->templateVersion->template->name ?? '').'“, Fassung '.($record->templateVersion->version ?? '')), + TextEntry::make('notification')->label('Benachrichtigung') + ->state(fn (Inquiry $record): string => $record->notified_at !== null ? 'Gesendet am '.$record->notified_at->format('d.m.Y H:i') : ($record->notification_error ?: 'Noch nicht gesendet')) + ->color(fn (Inquiry $record): ?string => $record->notified_at === null && $record->notification_error !== null ? 'danger' : null), + ]), + Section::make('Antworten')->schema([ + ViewEntry::make('answers')->hiddenLabel()->view('filament.communication.answers'), + ]), + Section::make('Nachricht')->visible(fn (Inquiry $record): bool => filled($record->message))->schema([ + TextEntry::make('message')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']), + ]), + Section::make('Interne Notizen')->schema([ + RepeatableEntry::make('notes')->hiddenLabel()->placeholder('Noch keine Notizen.')->schema([ + TextEntry::make('body')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']), + TextEntry::make('meta')->hiddenLabel()->color('gray') + ->state(fn ($record): string => ($record->author->name ?? 'Unbekannt').' · '.$record->created_at->format('d.m.Y H:i')), + ]), + ]), + ]); + } + + public static function form(Schema $schema): Schema + { + return $schema; + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('reference')->label('Kennzeichen')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiries::route('/'), + 'view' => ViewInquiry::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php b/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php new file mode 100644 index 0000000..ee4dcbf --- /dev/null +++ b/app/Filament/Resources/Communication/Inquiries/Pages/ListInquiries.php @@ -0,0 +1,128 @@ +suche = ''; + $this->zustand = 'alle'; + $this->anliegen = 'alle'; + $this->sortierung = 'neu'; + $this->bestandGrenze = Bestand::SCHRITT; + } + + public function bestand(): array + { + $b = $this->baseBestand(); + $issues = Inquiry::query()->whereNotNull('issue_key')->select('issue_key', 'issue_label')->distinct()->orderBy('issue_label')->pluck('issue_label', 'issue_key')->all(); + + $b['filter'][] = ['eigenschaft' => 'anliegen', 'label' => 'Anliegen', 'vorgabe' => 'alle', 'optionen' => ['alle' => 'Alle Anliegen'] + $issues]; + $b['sortierung'] = ['eigenschaft' => 'sortierung', 'label' => 'Sortierung', 'optionen' => ['neu' => 'Neueste zuerst', 'alt' => 'Älteste zuerst', 'name' => 'Name', 'status' => 'Status']]; + + return $b; + } + + protected function catalogRows(): array + { + $query = Inquiry::query()->with(['entry', 'templateVersion.template']); + + if ($this->anliegen !== 'alle') { + $query->where('issue_key', $this->anliegen); + } + + $inquiries = match ($this->sortierung) { + 'alt' => $query->orderBy('created_at')->orderBy('id')->get(), + 'name' => $query->get()->sortBy(fn (Inquiry $i): string => mb_strtolower($i->contactTitle()), SORT_NATURAL)->values(), + 'status' => $query->get()->sortBy(fn (Inquiry $i): string => array_search($i->status, InquiryStatus::cases(), true).'-'.(PHP_INT_MAX - $i->created_at->getTimestamp()))->values(), + default => $query->orderByDesc('created_at')->orderByDesc('id')->get(), + }; + + $rows = []; + + foreach ($inquiries as $inquiry) { + $url = InquiryResource::getUrl('view', ['record' => $inquiry]); + $failed = $inquiry->notified_at === null && $inquiry->notification_error !== null; + $rows[] = [ + 'schluessel' => 'q'.$inquiry->id, + 'titel' => $inquiry->contactTitle().($inquiry->organisation ? ' · '.$inquiry->organisation : ''), + 'meta' => $inquiry->created_at->format('d.m.Y H:i').' · '.($inquiry->issueTitle() ?: 'Ohne Anliegen').' · '.$inquiry->channelTitle(), + 'text' => Str::limit((string) $inquiry->message, 180), + 'suchtext' => implode(' ', array_filter([$inquiry->contact_email, $inquiry->reference, $inquiry->contact_phone])), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + ['label' => $inquiry->status->label(), 'ton' => match ($inquiry->status) { + InquiryStatus::Neu => 'offen', + InquiryStatus::RueckfrageOffen => 'achtung', + InquiryStatus::Erledigt => 'gut', + default => 'neutral', + }], + $failed ? ['label' => 'Benachrichtigung fehlgeschlagen', 'ton' => 'achtung'] : null, + ])), + 'zustand' => array_values(array_filter([$inquiry->status->value, $inquiry->status !== InquiryStatus::Erledigt ? 'offen' : null, $failed ? 'mailfehler' : null])), + 'aktionen' => [['label' => 'Öffnen', 'href' => $url]], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Status', + 'offen' => 'Nicht erledigt', + ...InquiryStatus::options(), + 'mailfehler' => 'Benachrichtigung fehlgeschlagen', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Name, E-Mail, Organisation, Nachricht oder Kennzeichen'; + } + + protected function einheit(): array + { + return ['Anfrage', 'Anfragen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Anfragen', 'text' => 'Sobald jemand über einen Anfrage-Einstieg eine Anfrage sendet, erscheint sie hier.']; + } +} diff --git a/app/Filament/Resources/Communication/Inquiries/Pages/ViewInquiry.php b/app/Filament/Resources/Communication/Inquiries/Pages/ViewInquiry.php new file mode 100644 index 0000000..57f5193 --- /dev/null +++ b/app/Filament/Resources/Communication/Inquiries/Pages/ViewInquiry.php @@ -0,0 +1,106 @@ +getRecord(); + + return $inquiry->contactTitle(); + } + + public function getSubheading(): string|Htmlable|null + { + /** @var Inquiry $inquiry */ + $inquiry = $this->getRecord(); + + return 'Anfrage '.$inquiry->reference.' vom '.$inquiry->created_at->format('d.m.Y H:i'); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('status') + ->label('Status ändern') + ->icon('heroicon-o-arrow-path') + ->modalHeading('Bearbeitungsstatus') + ->modalSubmitActionLabel('Status speichern') + ->fillForm(fn (): array => ['status' => $this->getRecord()->status->value]) + ->schema([Select::make('status')->label('Neuer Status')->options(InquiryStatus::options())->required()]) + ->action(function (array $data): void { + $this->getRecord()->forceFill(['status' => $data['status']])->save(); + Notification::make()->title('Der Status ist geändert.')->success()->send(); + $this->refreshFormData(['status']); + }), + Action::make('note') + ->label('Notiz hinzufügen') + ->icon('heroicon-o-pencil-square') + ->color('gray') + ->modalHeading('Interne Notiz') + ->modalDescription('Nur für das Team sichtbar, nie für den Anfragenden.') + ->modalSubmitActionLabel('Notiz speichern') + ->schema([Textarea::make('body')->label('Notiz')->required()->rows(4)->maxLength(4000)]) + ->action(function (array $data): void { + InquiryNote::query()->create([ + 'inquiry_id' => $this->getRecord()->id, + 'user_id' => CommunicationAccess::user()?->id, + 'body' => $data['body'], + ]); + + $this->getRecord()->load('notes'); + Notification::make()->title('Die Notiz ist gespeichert.')->success()->send(); + $this->redirect(InquiryResource::getUrl('view', ['record' => $this->getRecord()])); + }), + Action::make('resend') + ->label('Benachrichtigung erneut senden') + ->icon('heroicon-o-envelope') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->notified_at === null) + ->requiresConfirmation() + ->modalDescription('Sendet die interne Benachrichtigung an die in den Einstellungen hinterlegten Empfänger noch einmal.') + ->action(function (): void { + SendInquiryNotification::dispatchSync($this->getRecord()->id, InquiryResource::getUrl('view', ['record' => $this->getRecord()])); + $inquiry = $this->getRecord()->fresh(); + + if ($inquiry->notified_at !== null) { + Notification::make()->title('Die Benachrichtigung ist gesendet.')->success()->send(); + } else { + Notification::make()->title('Die Benachrichtigung ist weiterhin fehlgeschlagen.')->body((string) $inquiry->notification_error)->danger()->send(); + } + + $this->redirect(InquiryResource::getUrl('view', ['record' => $inquiry])); + }), + Action::make('erase') + ->label('Anfrage löschen') + ->icon('heroicon-o-trash') + ->color('danger') + ->visible(fn (): bool => CommunicationAccess::erase()) + ->requiresConfirmation() + ->modalHeading('Anfrage endgültig löschen?') + ->modalDescription('Die Anfrage mit allen Antworten und Notizen wird unwiderruflich gelöscht, zum Beispiel auf Wunsch der betroffenen Person. Das lässt sich nicht rückgängig machen.') + ->action(function (): void { + $this->getRecord()->delete(); + Notification::make()->title('Die Anfrage ist gelöscht.')->success()->send(); + $this->redirect(InquiryResource::getUrl('index')); + }), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Issues/InquiryIssueResource.php b/app/Filament/Resources/Communication/Issues/InquiryIssueResource.php new file mode 100644 index 0000000..c0224c6 --- /dev/null +++ b/app/Filament/Resources/Communication/Issues/InquiryIssueResource.php @@ -0,0 +1,72 @@ +components([ + TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120) + ->helperText('So sieht es der Besucher. Die Bezeichnung darf sich ändern; die fachliche Identität bleibt.'), + Textarea::make('description')->label('Beschreibung (optional)')->rows(3)->maxLength(300) + ->helperText('Ein Satz unter der Bezeichnung in der Auswahl.'), + Placeholder::make('hierarchy')->label('Einordnung')->content( + fn (?InquiryIssue $record): string => $record?->parent !== null ? 'Unteranliegen von „'.$record->parent->label.'“' : 'Anliegen auf oberster Ebene' + ), + Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryIssue $record): string => (string) $record?->key) + ->helperText('Wird beim Anlegen vergeben und ändert sich nie. Bereits eingegangene Anfragen und Bedingungen beziehen sich darauf.'), + Toggle::make('active')->label('Besuchern anbieten') + ->helperText('Ausgeschaltet erscheint das Anliegen in keiner neuen Fassung einer Vorlage; bestehende Fassungen und Anfragen bleiben unverändert.'), + ]); + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('label')->label('Bezeichnung')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryIssues::route('/'), + 'edit' => EditInquiryIssue::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Issues/Pages/EditInquiryIssue.php b/app/Filament/Resources/Communication/Issues/Pages/EditInquiryIssue.php new file mode 100644 index 0000000..360a75f --- /dev/null +++ b/app/Filament/Resources/Communication/Issues/Pages/EditInquiryIssue.php @@ -0,0 +1,52 @@ +label('Archivieren') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->archived_at === null) + ->requiresConfirmation() + ->modalDescription('Das Anliegen wird in neuen Fassungen von Vorlagen nicht mehr angeboten. Bereits eingegangene Anfragen und veröffentlichte Fassungen bleiben unverändert.') + ->action(function (): void { + /** @var InquiryIssue $issue */ + $issue = $this->getRecord(); + $issue->forceFill(['archived_at' => now(), 'active' => false])->save(); + + foreach ($issue->children as $child) { + $child->forceFill(['archived_at' => $child->archived_at ?? now(), 'active' => false])->save(); + } + + Notification::make()->title('Archiviert.')->success()->send(); + $this->redirect(InquiryIssueResource::getUrl('index')); + }), + Action::make('restore') + ->label('Wiederherstellen') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->archived_at !== null) + ->action(function (): void { + $this->getRecord()->forceFill(['archived_at' => null])->save(); + Notification::make()->title('Wiederhergestellt. Das Anliegen ist weiterhin deaktiviert, bis es eingeschaltet wird.')->success()->send(); + $this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $this->getRecord()])); + }), + ]; + } + + protected function getRedirectUrl(): ?string + { + return InquiryIssueResource::getUrl('index'); + } +} diff --git a/app/Filament/Resources/Communication/Issues/Pages/ListInquiryIssues.php b/app/Filament/Resources/Communication/Issues/Pages/ListInquiryIssues.php new file mode 100644 index 0000000..afe59e4 --- /dev/null +++ b/app/Filament/Resources/Communication/Issues/Pages/ListInquiryIssues.php @@ -0,0 +1,143 @@ +label('Anliegen anlegen') + ->modalHeading('Neues Anliegen') + ->modalDescription('Bezeichnung und Einordnung genügen. Die interne Kennung wird einmalig vergeben.') + ->modalSubmitActionLabel('Anliegen anlegen') + ->schema([ + Select::make('parent_id')->label('Einordnung') + ->options(fn (): array => InquiryIssue::query()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'id')->all()) + ->placeholder('Anliegen auf oberster Ebene') + ->helperText('Alternativ als Unteranliegen eines bestehenden Anliegens.'), + TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120), + Textarea::make('description')->label('Beschreibung (optional)')->rows(2)->maxLength(300), + ]) + ->action(function (array $data): void { + $issue = InquiryIssue::query()->create([ + 'parent_id' => $data['parent_id'] ?? null, + 'key' => Keys::from($data['label'], InquiryIssue::query()->pluck('key')->all()), + 'label' => $data['label'], + 'description' => $data['description'] ?? null, + 'sort_order' => ((int) InquiryIssue::query()->where('parent_id', $data['parent_id'] ?? null)->max('sort_order')) + 10, + ]); + + Notification::make()->title('Das Anliegen ist angelegt.')->success()->send(); + $this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $issue])); + }), + ]; + } + + /** Ein Anliegen vor oder hinter seinem Nachbarn derselben Ebene einordnen. */ + public function moveIssue(int $id, string $direction): void + { + $issue = InquiryIssue::query()->findOrFail($id); + $siblings = InquiryIssue::query()->where('parent_id', $issue->parent_id)->orderBy('sort_order')->orderBy('id')->get()->values(); + $index = $siblings->search(fn (InquiryIssue $item): bool => $item->id === $issue->id); + $target = $direction === 'up' ? $index - 1 : $index + 1; + + if ($index === false || $target < 0 || $target >= $siblings->count()) { + return; + } + + $order = $siblings->all(); + [$order[$index], $order[$target]] = [$order[$target], $order[$index]]; + + foreach ($order as $position => $item) { + $item->forceFill(['sort_order' => ($position + 1) * 10])->save(); + } + } + + protected function catalogRows(): array + { + $all = InquiryIssue::query()->orderBy('sort_order')->orderBy('id')->get(); + $children = $all->whereNotNull('parent_id')->groupBy('parent_id'); + $rows = []; + $tops = $all->whereNull('parent_id')->values(); + + $row = function (InquiryIssue $issue, ?InquiryIssue $parent, int $position, int $count) use (&$rows): void { + $url = InquiryIssueResource::getUrl('edit', ['record' => $issue]); + $state = $issue->archived_at !== null ? 'archiviert' : ($issue->active ? 'aktiv' : 'inaktiv'); + $rows[] = [ + 'schluessel' => 'i'.$issue->id, + 'titel' => ($parent !== null ? '↳ ' : '').$issue->label, + 'meta' => $parent !== null ? 'Unteranliegen von „'.$parent->label.'“' : 'Anliegen', + 'text' => (string) ($issue->description ?? ''), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => [ + match ($state) { + 'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'], + 'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'], + default => ['label' => 'Archiviert', 'ton' => 'leise'], + }, + ], + 'zustand' => [$state], + 'aktionen' => [ + ['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'], + ...($position > 0 ? [['label' => 'Nach oben', 'wire' => "moveIssue({$issue->id}, 'up')"]] : []), + ...($position < $count - 1 ? [['label' => 'Nach unten', 'wire' => "moveIssue({$issue->id}, 'down')"]] : []), + ], + ]; + }; + + foreach ($tops as $i => $top) { + $row($top, null, $i, $tops->count()); + $kids = ($children[$top->id] ?? collect())->values(); + + foreach ($kids as $j => $child) { + $row($child, $top, $j, $kids->count()); + } + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert']; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung oder Beschreibung'; + } + + protected function einheit(): array + { + return ['Anliegen', 'Anliegen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Anliegen', 'text' => 'Mit „Anliegen anlegen“ oben entsteht das erste Anliegen, zum Beispiel „Kurse & Workshops“. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.']; + } +} diff --git a/app/Filament/Resources/Communication/Templates/InquiryTemplateResource.php b/app/Filament/Resources/Communication/Templates/InquiryTemplateResource.php new file mode 100644 index 0000000..a685da4 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/InquiryTemplateResource.php @@ -0,0 +1,57 @@ +components(TemplateEditor::schema($schema->getRecord()?->getKey())); + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('name')->label('Bezeichnung')]); + } + + public static function getRelations(): array + { + return [VersionsRelationManager::class]; + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryTemplates::route('/'), + 'edit' => EditInquiryTemplate::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Communication/Templates/Pages/EditInquiryTemplate.php b/app/Filament/Resources/Communication/Templates/Pages/EditInquiryTemplate.php new file mode 100644 index 0000000..110cace --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/Pages/EditInquiryTemplate.php @@ -0,0 +1,204 @@ +getRecord(); + + if ($template->archived_at !== null) { + return 'Archiviert.'; + } + + if (! $template->isPublished()) { + return 'Noch nicht veröffentlicht. Besucher sehen dieses Formular erst nach „Veröffentlichen“.'; + } + + $version = $template->publishedVersion; + + return 'Gültig ist Fassung '.$version->version.' (veröffentlicht am '.$version->published_at->format('d.m.Y').').' + .($template->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : ' Der Entwurf entspricht der gültigen Fassung.'); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('preview') + ->label('Vorschau') + ->icon('heroicon-o-eye') + ->color('gray') + ->tooltip('Zeigt den zuletzt gespeicherten Entwurf als Besucher mit allen Bedingungen. Es wird nichts gesendet.') + ->url(fn (): string => route('communication.preview.template', $this->getRecord())) + ->openUrlInNewTab(), + Action::make('check') + ->label('Konfiguration prüfen') + ->color('gray') + ->action(function (): void { + $this->save(shouldRedirect: false, shouldSendSavedNotification: false); + $result = app(TemplateCompiler::class)->compile(TemplateDraft::clean((array) $this->getRecord()->draft)); + + if ($result['errors'] === []) { + Notification::make()->title('Die Konfiguration ist in Ordnung.')->body('Der Entwurf wurde gespeichert und lässt sich veröffentlichen.')->success()->send(); + + return; + } + + Notification::make()->title('Die Konfiguration hat Probleme')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $result['errors'])))->danger()->persistent()->send(); + }), + Action::make('publish') + ->label('Veröffentlichen') + ->color('primary') + ->visible(fn (): bool => $this->getRecord()->archived_at === null) + ->modalHeading('Formular veröffentlichen') + ->modalSubmitActionLabel('Jetzt veröffentlichen') + ->modalWidth('2xl') + ->schema(fn (): array => [ + Text::make($this->affectedText()), + Textarea::make('note')->label('Bemerkung zur Fassung (optional)')->rows(2)->maxLength(300), + ]) + ->action(function (array $data): void { + $this->save(shouldRedirect: false, shouldSendSavedNotification: false); + + try { + $version = app(Publisher::class)->publishTemplate($this->getRecord(), auth('staff')->user() instanceof User ? auth('staff')->user() : null, $data['note'] ?? null); + } catch (ValidationException $e) { + Notification::make()->title('Das Formular lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send(); + + return; + } + + Notification::make()->title('Fassung '.$version->version.' ist veröffentlicht.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getRecord()])); + }), + ...$this->archiveActions(), + ]; + } + + /** Einstiege, die diese Vorlage verwenden und von einer neuen Fassung betroffen sind. */ + private function affectedText(): string + { + $rows = app(Publisher::class)->affected($this->getRecord()); + + if ($rows === []) { + return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.'; + } + + $names = array_map(fn (array $row): string => $row['entry']->name.($row['entry']->published_config !== null ? ' (veröffentlicht)' : ' (Entwurf)'), $rows); + + return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist, und für diese Anfrage-Einstiege (ältere Seiten): '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.'; + } + + protected function archiveNote(): string + { + return 'Das Formular wird archiviert. Seiten, die es einbinden, bieten es dann nicht mehr an (auch Anfrage-Einstiege liefern nichts mehr aus). Eingegangene Anfragen bleiben unverändert.'; + } + + protected function archiveAttributes(): array + { + return ['archived_at' => now()]; + } + + protected function indexUrl(): string + { + return InquiryTemplateResource::getUrl('index'); + } + + protected function archiveBlocked(): ?string + { + $live = $this->getRecord()->entries()->live()->count(); + + return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit diesem Formular. Bitte zuerst zurückziehen oder auf ein anderes Formular umstellen." : null; + } + + protected function mutateFormDataBeforeFill(array $data): array + { + $tree = FormEditor::toTree(app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey())); + + // Die Formularansicht führt den Baum im Browser und übergibt ihn als Text; die weiteren Regeln bleiben eine Liste. + $data['editor'] = ['rules' => $tree['rules']]; + $data['editor_json'] = json_encode(['areas' => $tree['areas']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + + return $data; + } + + protected function mutateFormDataBeforeSave(array $data): array + { + $editor = app(FormEditor::class); + $tree = json_decode((string) ($data['editor_json'] ?? ''), true); + + if (! is_array($tree)) { + $this->failEditor(['Der Aufbau konnte nicht gelesen werden. Bitte lade die Seite neu und versuche es noch einmal.']); + } + + $errors = $editor->validateTree($tree); + + if ($errors !== []) { + $this->failEditor($errors); + } + + // Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf. + $view = FormEditor::fromTree($tree); + $view['rules'] = (array) ($data['editor']['rules'] ?? []); + $saved = $editor->persist($view); + unset($data['editor'], $data['editor_json']); + + $data['draft'] = TemplateDraft::clean([ + 'texts' => (array) ($data['draft']['texts'] ?? []), + 'issues' => $saved['issues'], + 'steps' => $saved['steps'], + 'rules' => $saved['rules'], + ]); + + return $data; + } + + /** + * @param list $messages + * @return never + */ + private function failEditor(array $messages): void + { + Notification::make()->title('Das Formular ist noch nicht vollständig')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $messages)))->danger()->persistent()->send(); + + throw ValidationException::withMessages(['data.editor_json' => $messages]); + } + + protected function afterSave(): void + { + // Neue Felder und Teilbereiche tragen jetzt ihre festen Kennungen. Ohne neues Laden würde ein zweites Speichern sie doppelt anlegen. + $this->fillForm(); + } + + protected function getRedirectUrl(): ?string + { + return null; + } +} diff --git a/app/Filament/Resources/Communication/Templates/Pages/ListInquiryTemplates.php b/app/Filament/Resources/Communication/Templates/Pages/ListInquiryTemplates.php new file mode 100644 index 0000000..40b8de4 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/Pages/ListInquiryTemplates.php @@ -0,0 +1,114 @@ +label('Formular anlegen') + ->modalHeading('Neues Formular') + ->modalDescription('Der Aufbau entsteht danach im Editor des Formulars.') + ->modalSubmitActionLabel('Formular anlegen') + ->schema([ + TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120), + Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400), + ]) + ->action(function (array $data): void { + $draft = InquiryTemplate::emptyDraft(); + $draft['steps'] = [['key' => 's'.Str::lower(Str::random(6)), 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]]; + + $template = InquiryTemplate::query()->create([ + 'key' => Keys::from($data['name'], InquiryTemplate::query()->pluck('key')->all()), + 'name' => $data['name'], + 'description' => $data['description'] ?? null, + 'draft' => $draft, + ]); + + Notification::make()->title('Das Formular ist angelegt.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template])); + }), + ]; + } + + protected function catalogRows(): array + { + $rows = []; + + foreach (InquiryTemplate::query()->with('publishedVersion')->withCount('entries')->orderBy('name')->get() as $template) { + $url = InquiryTemplateResource::getUrl('edit', ['record' => $template]); + $archived = $template->archived_at !== null; + $published = $template->isPublished(); + $changes = $published && $template->hasUnpublishedChanges(); + $steps = count((array) ($template->draft['steps'] ?? [])); + + $rows[] = [ + 'schluessel' => 't'.$template->id, + 'titel' => $template->name, + 'meta' => 'Formular · '.$steps.' '.($steps === 1 ? 'Bereich' : 'Bereiche').($template->entries_count > 0 ? ' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege').' (ältere Seiten)' : ''), + 'text' => (string) ($template->description ?? ''), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + $archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($published + ? ['label' => 'Fassung '.$template->publishedVersion->version.' gültig', 'ton' => 'gut'] + : ['label' => 'Noch nicht veröffentlicht', 'ton' => 'offen']), + $changes ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null, + ])), + 'zustand' => [$archived ? 'archiviert' : ($published ? 'veroeffentlicht' : 'entwurf'), ...($changes ? ['aenderungen'] : [])], + 'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Zustand', + 'veroeffentlicht' => 'Veröffentlicht', + 'entwurf' => 'Noch nicht veröffentlicht', + 'aenderungen' => 'Mit unveröffentlichten Änderungen', + 'archiviert' => 'Archiviert', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung oder Beschreibung'; + } + + protected function einheit(): array + { + return ['Formular', 'Formulare']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Formulare', 'text' => 'Mit „Formular anlegen“ oben entsteht das erste Formular. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.']; + } +} diff --git a/app/Filament/Resources/Communication/Templates/RelationManagers/VersionsRelationManager.php b/app/Filament/Resources/Communication/Templates/RelationManagers/VersionsRelationManager.php new file mode 100644 index 0000000..15a038c --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/RelationManagers/VersionsRelationManager.php @@ -0,0 +1,81 @@ +getOwnerRecord(); + + return $table + ->heading('Fassungen') + ->emptyStateHeading('Noch keine Fassung veröffentlicht') + ->emptyStateDescription('Mit „Veröffentlichen“ entsteht die erste Fassung.') + ->columns([ + TextColumn::make('version')->label('Fassung')->prefix('Nr. '), + TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i'), + TextColumn::make('published_by')->label('Von')->state(fn (InquiryTemplateVersion $record): string => (string) User::query()->whereKey($record->published_by)->value('name')), + TextColumn::make('note')->label('Bemerkung')->placeholder('–'), + TextColumn::make('state')->label('Zustand')->badge() + ->color(fn (string $state): string => $state === 'Gültig' ? 'success' : 'gray') + ->state(fn (InquiryTemplateVersion $record): string => $record->id === $this->getOwnerRecord()->published_version_id ? 'Gültig' : 'Früher'), + TextColumn::make('inquiries')->label('Anfragen')->state(fn (InquiryTemplateVersion $record): int => Inquiry::query()->where('template_version_id', $record->id)->count()), + ]) + ->recordActions([ + Action::make('restore') + ->label('Wieder in Kraft setzen') + ->visible(fn (InquiryTemplateVersion $record): bool => $record->id !== $template->fresh()->published_version_id) + ->requiresConfirmation() + ->modalDescription('Besucher sehen danach wieder diese Fassung. Der Entwurf bleibt unverändert. Eingegangene Anfragen bleiben ihrer damaligen Fassung zugeordnet.') + ->action(function (InquiryTemplateVersion $record): void { + try { + app(Publisher::class)->restoreVersion($this->getOwnerRecord(), $record); + } catch (ValidationException $e) { + Notification::make()->title('Nicht möglich')->body(implode(' ', $e->errors()['draft'] ?? []))->danger()->send(); + + return; + } + + Notification::make()->title('Fassung '.$record->version.' ist wieder gültig.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()])); + }), + Action::make('load') + ->label('Als Entwurf laden') + ->color('gray') + ->requiresConfirmation() + ->modalDescription('Der aktuelle Entwurf wird durch den Stand dieser Fassung ersetzt. Veröffentlicht wird dadurch nichts.') + ->action(function (InquiryTemplateVersion $record): void { + $this->getOwnerRecord()->forceFill(['draft' => $record->source])->save(); + Notification::make()->title('Der Entwurf entspricht jetzt Fassung '.$record->version.'.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()])); + }), + ]) + ->defaultSort('version', 'desc') + ->paginated(false); + } +} diff --git a/app/Filament/Support/ArchivesCommunicationRecords.php b/app/Filament/Support/ArchivesCommunicationRecords.php new file mode 100644 index 0000000..acd4796 --- /dev/null +++ b/app/Filament/Support/ArchivesCommunicationRecords.php @@ -0,0 +1,66 @@ + + */ + protected function archiveAttributes(): array + { + return ['archived_at' => now(), 'active' => false]; + } + + /** Grund, warum das Archivieren gerade nicht möglich ist; null: möglich. */ + protected function archiveBlocked(): ?string + { + return null; + } + + /** + * @return list + */ + protected function archiveActions(): array + { + return [ + Action::make('archive') + ->label('Archivieren') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->archived_at === null) + ->requiresConfirmation() + ->modalDescription(fn (): string => $this->archiveNote()) + ->action(function (): void { + if (($reason = $this->archiveBlocked()) !== null) { + Notification::make()->title($reason)->danger()->send(); + + return; + } + + $this->getRecord()->forceFill($this->archiveAttributes())->save(); + Notification::make()->title('Archiviert.')->success()->send(); + $this->redirect($this->indexUrl()); + }), + Action::make('restore') + ->label('Wiederherstellen') + ->color('gray') + ->visible(fn (): bool => $this->getRecord()->archived_at !== null) + ->action(function (): void { + $this->getRecord()->forceFill(['archived_at' => null])->save(); + Notification::make()->title('Wiederhergestellt.')->success()->send(); + $this->redirect($this->indexUrl()); + }), + ]; + } +} diff --git a/app/Filament/Support/TemplateEditor.php b/app/Filament/Support/TemplateEditor.php new file mode 100644 index 0000000..6ab6afe --- /dev/null +++ b/app/Filament/Support/TemplateEditor.php @@ -0,0 +1,295 @@ + + */ + public static function schema(?int $templateId = null): array + { + return [ + TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120) + ->helperText('So heißt das Formular in der Verwaltung und in der Auswahl des Widgets „Anfrage“.'), + Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400), + Tabs::make('vorlage')->persistTabInQueryString('bereich')->columnSpanFull()->tabs([ + Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure($templateId)), + Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()), + Tab::make('Weitere Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()), + ]), + ]; + } + + /** + * Der Aufbau ist eine eigene Formularansicht (resources/views/filament/communication/form-editor.blade.php). Sie führt + * den Baum aus Bereichen, Teilbereichen und Feldern im Browser und übergibt ihn beim Speichern als Text (editor_json); + * FormEditor prüft und speichert ihn. + * + * @return list + */ + private static function structure(?int $templateId): array + { + return [ + ViewField::make('editor_json') + ->hiddenLabel() + ->view('filament.communication.form-editor') + ->viewData(['config' => app(FormEditor::class)->clientConfig($templateId)]) + ->columnSpanFull(), + ]; + } + + /** + * @return list + */ + private static function rules(): array + { + return [ + Section::make()->schema([ + Text::make('Hier stehen Regeln, die sich nicht an ein einzelnes Feld oder einen Bereich heften lassen: weitere Regeln für dasselbe Ziel und Vorbelegungen. Bedingungen für ein Feld oder einen Bereich legst du direkt am Element an. Eine Bedingung darf nur auf Felder verweisen, die im Formular weiter oben stehen.'), + Repeater::make('editor.rules') + ->label('Weitere Regeln') + ->schema([ + Hidden::make('pos'), + Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS), + Select::make('target')->label('Ziel')->required()->live()->searchable() + ->options(fn ($livewire, Get $get): array => self::targets(self::flat($livewire), (string) $get('effect'))), + Select::make('value')->label('Vorbelegen mit')->live() + ->options(fn (Get $get): array => str_starts_with((string) $get('target'), 'field:') ? self::fieldValues(substr((string) $get('target'), 6)) : []) + ->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'), + Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')->required(), + Repeater::make('conditions') + ->label('Bedingungen') + ->schema([ + Select::make('source')->label('Wenn …')->required()->live()->searchable() + ->options(fn ($livewire): array => self::sources(self::flat($livewire))), + Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(), + Select::make('values')->label('Wert')->required()->multiple() + ->options(fn ($livewire, Get $get): array => self::sourceValues(self::flat($livewire), (string) $get('source'))), + ]) + ->minItems(1) + ->addActionLabel('Bedingung hinzufügen'), + ]) + ->collapsible() + ->addActionLabel('Regel hinzufügen') + ->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], self::flat($livewire)) : '')), + ]), + ]; + } + + /** + * @return list + */ + private static function texts(): array + { + $fields = []; + + foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) { + $field = $multiline + ? Textarea::make("draft.texts.$key")->rows(2)->maxLength(1500) + : TextInput::make("draft.texts.$key")->maxLength(200); + + $fields[] = $field->label($label)->placeholder($default !== '' ? $default : 'Kein Text')->helperText($help); + } + + return [ + Section::make('Texte des Formulars') + ->description('Alle Texte des Formulars werden hier gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext.') + ->schema($fields), + ]; + } + + /** + * Der aktuelle Aufbau in der flachen Ansicht (Bereiche, Felder, Teilbereiche, Ende-Markierungen), aus dem Text der Formularansicht. + * + * @return array + */ + private static function flat(mixed $livewire): array + { + $tree = json_decode((string) ($livewire->data['editor_json'] ?? ''), true); + + return FormEditor::fromTree(is_array($tree) ? $tree : []); + } + + /** + * Inhalt des Formulars in Reihenfolge: Bereiche, Teilbereiche, Felder, und ob die Frage nach dem Anliegen vorkommt. + * + * @param array $editor + * @return array{steps: array, groups: array, fields: array, hasIssue: bool, issues: list} + */ + private static function inventory(array $editor): array + { + $steps = []; + $groups = []; + $fields = []; + $hasIssue = false; + $issues = []; + + foreach (array_values((array) ($editor['areas'] ?? [])) as $area) { + $key = (string) ($area['key'] ?? ''); + + if ($key !== '') { + $steps[$key] = (string) (($area['title'] ?? '') ?: 'Bereich'); + } + + foreach (array_values((array) ($area['items'] ?? [])) as $block) { + $data = (array) ($block['data'] ?? []); + $type = $block['type'] ?? null; + + if ($type === 'issue') { + $hasIssue = true; + $issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string')); + } elseif ($type === 'section' && filled($data['key'] ?? null)) { + $groups[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Teilbereich'); + } elseif ($type === 'field' && filled($data['key'] ?? null)) { + $fields[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Feld'); + } + } + } + + return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue, 'issues' => $issues]; + } + + /** + * @param array $editor + * @return array + */ + private static function targets(array $editor, string $effect): array + { + $inventory = self::inventory($editor); + $steps = []; + foreach ($inventory['steps'] as $key => $title) { + $steps["step:$key"] = 'Bereich: '.$title; + } + $groups = []; + foreach ($inventory['groups'] as $key => $name) { + $groups["group:$key"] = 'Teilbereich: '.$name; + } + $fields = []; + foreach ($inventory['fields'] as $key => $name) { + $fields["field:$key"] = 'Feld: '.$name; + } + + return match ($effect) { + 'skip' => $steps, + 'require', 'preset' => $fields, + default => ['Bereiche' => $steps, 'Teilbereiche' => $groups, 'Felder' => $fields], + }; + } + + /** + * @param array $editor + */ + private static function targetName(string $target, array $editor = []): string + { + [$kind, $key] = array_pad(explode(':', $target, 2), 2, ''); + $inventory = self::inventory($editor); + + return match ($kind) { + 'step' => (string) ($inventory['steps'][$key] ?? $key), + 'field' => (string) ($inventory['fields'][$key] ?? InquiryField::query()->where('key', $key)->value('name') ?? $key), + 'group' => (string) ($inventory['groups'][$key] ?? $key), + default => $key, + }; + } + + /** + * Felder, auf deren Wert sich eine Bedingung stützen darf: gespeicherte Auswahlfelder und Ja/Nein-Felder. Mit + * Zustandspfad der Bedingung nur Felder, die im Formular davor stehen (sonst lehnt die Prüfung die Regel ab). + * + * @param array $editor + * @return array + */ + private static function sources(array $editor): array + { + $catalog = InquiryField::query()->get()->keyBy('key'); + $sources = []; + + foreach ((array) ($editor['areas'] ?? []) as $area) { + foreach ((array) ($area['items'] ?? []) as $block) { + $data = (array) ($block['data'] ?? []); + $key = (string) ($data['key'] ?? ''); + + if (($block['type'] ?? null) === 'issue') { + $sources['anliegen'] = 'Anliegen'; + $sources['unteranliegen'] = 'Unteranliegen'; + } elseif (($block['type'] ?? null) === 'field' && isset($catalog[$key]) && $catalog[$key]->type->canControl()) { + $sources[$key] = (string) (($data['label'] ?? '') ?: $catalog[$key]->label); + } + } + } + + return $sources; + } + + /** + * @param array $editor + * @return array + */ + private static function sourceValues(array $editor, string $source): array + { + if ($source === 'anliegen' || $source === 'unteranliegen') { + $only = self::inventory($editor)['issues']; + $options = []; + + foreach (InquiryIssue::tree() as $issue) { + if ($only !== [] && ! in_array($issue['key'], $only, true)) { + continue; + } + + if ($source === 'anliegen') { + $options[$issue['key']] = $issue['label']; + + continue; + } + + foreach ($issue['children'] as $child) { + $options[$child['key']] = $issue['label'].' › '.$child['label']; + } + } + + return $options; + } + + return self::fieldValues($source); + } + + /** + * @return array + */ + private static function fieldValues(string $key): array + { + $field = InquiryField::query()->where('key', $key)->first(); + + if ($field === null || ! in_array($field->type, [FieldType::Select, FieldType::Multiselect, FieldType::Boolean], true)) { + return []; + } + + return collect($field->optionList())->pluck('label', 'key')->all(); + } +} diff --git a/app/Http/Controllers/InquiryFormController.php b/app/Http/Controllers/InquiryFormController.php new file mode 100644 index 0000000..04031e3 --- /dev/null +++ b/app/Http/Controllers/InquiryFormController.php @@ -0,0 +1,133 @@ +service->deliver($entry); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + return $this->json([ + ...FormPayload::definition($delivered['form'], $this->evaluator), + 'token' => FormToken::issue($entry->id, $delivered['version']->id), + 'csrf' => csrf_token(), + ]); + } + + public function state(Request $request, InquiryEntry $entry): JsonResponse + { + $delivered = $this->service->deliver($entry); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + $values = $request->input('values'); + + if (! is_array($values) || strlen((string) json_encode($values)) > 40000) { + return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422); + } + + return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator)); + } + + public function submit(Request $request, InquiryEntry $entry): JsonResponse + { + try { + $result = $this->service->submit($entry, [ + 'token' => $request->input('token'), + 'values' => $request->input('values'), + 'website' => $request->input('website'), + 'source' => $request->input('source'), + ]); + } catch (SubmissionException $e) { + return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422); + } + + return $this->json(['reference' => $result['reference']], 201); + } + + /** + * Widget „Anfrage“ (ADR-61): das veröffentlichte Formular einer Vorlage für den gewählten Anfragegrund. Der Grund + * (Anliegen, Unteranliegen, Formularführung) steht in der Adresse, damit Zustand und Absendung ohne weitere + * Angaben dasselbe Formular meinen. + */ + public function formDefinition(Request $request, InquiryTemplate $template): JsonResponse + { + $delivered = $this->service->deliverForm($template, FormReason::clean($request->query())); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + return $this->json([ + ...FormPayload::definition($delivered['form'], $this->evaluator), + 'token' => FormToken::issue($template->id, $delivered['version']->id, 'form'), + 'csrf' => csrf_token(), + ]); + } + + public function formState(Request $request, InquiryTemplate $template): JsonResponse + { + $delivered = $this->service->deliverForm($template, FormReason::clean($request->query())); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + $values = $request->input('values'); + + if (! is_array($values) || strlen((string) json_encode($values)) > 40000) { + return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422); + } + + return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator)); + } + + public function formSubmit(Request $request, InquiryTemplate $template): JsonResponse + { + try { + $result = $this->service->submitForm($template, FormReason::clean($request->query()), [ + 'token' => $request->input('token'), + 'values' => $request->input('values'), + 'website' => $request->input('website'), + 'source' => $request->input('source'), + ]); + } catch (SubmissionException $e) { + return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422); + } + + return $this->json(['reference' => $result['reference']], 201); + } + + /** + * @param array $data + */ + private function json(array $data, int $status = 200): JsonResponse + { + return response()->json($data, $status)->header('Cache-Control', 'no-store, private'); + } +} diff --git a/app/Http/Controllers/InquiryPreviewController.php b/app/Http/Controllers/InquiryPreviewController.php new file mode 100644 index 0000000..28d9738 --- /dev/null +++ b/app/Http/Controllers/InquiryPreviewController.php @@ -0,0 +1,141 @@ +authorizeStaff(); + + $mode = $request->query('modus') === 'wizard' ? 'wizard' : 'compact'; + $result = $this->compiler->compile(TemplateDraft::clean((array) $template->draft)); + + return view('communication.preview', [ + 'title' => 'Vorschau: Vorlage „'.$template->name.'“', + 'note' => 'Entwurf der Vorlage mit allen angebotenen Anliegen. Es wird nichts gesendet.', + 'errors' => $result['errors'], + 'mode' => $mode, + 'switchUrl' => route('communication.preview.template', ['template' => $template, 'modus' => $mode === 'wizard' ? 'compact' : 'wizard']), + 'definitionUrl' => route('communication.preview.template.definition', ['template' => $template, 'modus' => $mode]), + 'stateUrl' => route('communication.preview.template.state', ['template' => $template, 'modus' => $mode]), + ]); + } + + public function templateDefinition(Request $request, InquiryTemplate $template): JsonResponse + { + $this->authorizeStaff(); + + $form = $this->templateForm($request, $template); + + return $form === null ? $this->unavailable() : $this->json([...FormPayload::definition($form, $this->evaluator), 'token' => 'vorschau', 'csrf' => csrf_token()]); + } + + public function templateState(Request $request, InquiryTemplate $template): JsonResponse + { + $this->authorizeStaff(); + + $form = $this->templateForm($request, $template); + + return $form === null ? $this->unavailable() : $this->json(FormPayload::state($form, (array) $request->input('values', []), $this->evaluator)); + } + + public function entry(InquiryEntry $entry): View + { + $this->authorizeStaff(); + + $problem = $this->entryForm($entry) === null ? 'Die Anfragevorlage dieses Einstiegs hat noch keine gültige Fassung.' : null; + + return view('communication.preview', [ + 'title' => 'Vorschau: Einstieg „'.$entry->name.'“', + 'note' => 'Gespeicherter Entwurf des Einstiegs mit der gültigen Fassung der Vorlage. Es wird nichts gesendet.', + 'errors' => $problem === null ? [] : [$problem], + 'mode' => null, + 'switchUrl' => null, + 'definitionUrl' => route('communication.preview.entry.definition', $entry), + 'stateUrl' => route('communication.preview.entry.state', $entry), + ]); + } + + public function entryDefinition(InquiryEntry $entry): JsonResponse + { + $this->authorizeStaff(); + + $form = $this->entryForm($entry); + + return $form === null ? $this->unavailable() : $this->json([...FormPayload::definition($form, $this->evaluator), 'token' => 'vorschau', 'csrf' => csrf_token()]); + } + + public function entryState(Request $request, InquiryEntry $entry): JsonResponse + { + $this->authorizeStaff(); + + $form = $this->entryForm($entry); + + return $form === null ? $this->unavailable() : $this->json(FormPayload::state($form, (array) $request->input('values', []), $this->evaluator)); + } + + /** + * @return array|null + */ + private function templateForm(Request $request, InquiryTemplate $template): ?array + { + $result = $this->compiler->compile(TemplateDraft::clean((array) $template->draft)); + + if ($result['definition'] === null) { + return null; + } + + return $this->factory->effective($result['definition'], ['mode' => $request->query('modus') === 'wizard' ? 'wizard' : 'compact']); + } + + /** + * @return array|null + */ + private function entryForm(InquiryEntry $entry): ?array + { + $version = $entry->template->publishedVersion; + + return $version === null ? null : $this->factory->effective((array) $version->definition, (array) $entry->config); + } + + private function authorizeStaff(): void + { + abort_unless(CommunicationAccess::configure(auth('staff')->user()), 403); + } + + private function unavailable(): JsonResponse + { + return $this->json(['message' => 'Für diese Vorschau fehlt eine gültige Konfiguration.'], 404); + } + + /** + * @param array $data + */ + private function json(array $data, int $status = 200): JsonResponse + { + return response()->json($data, $status)->header('Cache-Control', 'no-store, private'); + } +} diff --git a/app/Jobs/SendInquiryNotification.php b/app/Jobs/SendInquiryNotification.php new file mode 100644 index 0000000..203c0ea --- /dev/null +++ b/app/Jobs/SendInquiryNotification.php @@ -0,0 +1,57 @@ +find($this->inquiryId); + + if ($inquiry === null) { + return; + } + + $recipients = CommunicationSettings::current()->recipientList(); + + if ($recipients === []) { + $inquiry->forceFill(['notification_error' => 'Es sind keine Empfänger für Benachrichtigungen hinterlegt (Kommunikation → Einstellungen).'])->save(); + + return; + } + + try { + Mail::to($recipients)->send(new InquiryReceived($inquiry, $this->adminUrl)); + } catch (Throwable $e) { + report($e); + $inquiry->forceFill(['notification_error' => 'Der E-Mail-Versand ist fehlgeschlagen: '.Str::limit($e->getMessage(), 400)])->save(); + + return; + } + + $inquiry->forceFill(['notified_at' => now(), 'notification_error' => null])->save(); + } +} diff --git a/app/Mail/CommunicationTestMail.php b/app/Mail/CommunicationTestMail.php new file mode 100644 index 0000000..624c6a9 --- /dev/null +++ b/app/Mail/CommunicationTestMail.php @@ -0,0 +1,23 @@ +inquiry->reference); + } + + public function content(): Content + { + return new Content( + text: 'mail.inquiry-received', + with: [ + 'reference' => $this->inquiry->reference, + 'issue' => $this->inquiry->issueTitle(), + 'received' => $this->inquiry->created_at?->timezone(config('app.timezone'))->format('d.m.Y H:i'), + 'url' => $this->adminUrl ?? url('/verwaltung/anfragen/'.$this->inquiry->id), + ], + ); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8403dd0..af9b6eb 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -16,7 +16,10 @@ use App\Models\User; use App\Policies\UserPolicy; use Filament\Auth\Http\Responses\Contracts\LoginResponse as LoginResponseContract; +use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; @@ -40,6 +43,13 @@ public function boot(): void 'livewire.temporary_file_upload.max_upload_time' => 60, ]); + // Anfrageformulare (ADR-60): begrenzte Absendungen und Auswertungen je Adresse. + RateLimiter::for('inquiry-submit', fn (Request $request): array => [ + Limit::perMinute((int) config('communication.submit_per_minute', 5))->by('inq-m|'.$request->ip()), + Limit::perHour((int) config('communication.submit_per_hour', 20))->by('inq-h|'.$request->ip()), + ]); + RateLimiter::for('inquiry-state', fn (Request $request): Limit => Limit::perMinute((int) config('communication.state_per_minute', 120))->by('inq-s|'.$request->ip())); + $this->app->bind(LoginResponseContract::class, StaffLoginResponse::class); Gate::policy(Page::class, PagePolicy::class); Gate::policy(NavigationItem::class, NavigationItemPolicy::class); diff --git a/config/cms.php b/config/cms.php index 94256f0..6966645 100644 --- a/config/cms.php +++ b/config/cms.php @@ -8,6 +8,7 @@ use App\Domain\Cms\Widgets\Types\HeadingWidget; use App\Domain\Cms\Widgets\Types\HeroWidget; use App\Domain\Cms\Widgets\Types\ImageTextWidget; +use App\Domain\Cms\Widgets\Types\InquiryWidget; use App\Domain\Cms\Widgets\Types\MediaCardWidget; use App\Domain\Cms\Widgets\Types\NoticeWidget; use App\Domain\Cms\Widgets\Types\ProgramCardWidget; @@ -38,6 +39,7 @@ CallToActionWidget::class, FaqWidget::class, ShopProductsWidget::class, + InquiryWidget::class, ], /* diff --git a/config/communication.php b/config/communication.php new file mode 100644 index 0000000..dddc45f --- /dev/null +++ b/config/communication.php @@ -0,0 +1,21 @@ + 24, + + /* Kürzeste Zeit zwischen Auslieferung und Absenden; schneller sendende Programme gelten als Automaten. */ + 'min_fill_seconds' => (int) env('INQUIRY_MIN_FILL_SECONDS', 3), + + /* Absendungen je Minute und Adresse beziehungsweise Auswertungen je Minute. */ + 'submit_per_minute' => 5, + 'submit_per_hour' => 20, + 'state_per_minute' => 120, + + /* Größte Menge an Eingaben (Zeichen), die ein Besucher senden darf. */ + 'max_payload_chars' => 40000, + +]; diff --git a/database/migrations/2026_12_03_100000_create_communication_tables.php b/database/migrations/2026_12_03_100000_create_communication_tables.php new file mode 100644 index 0000000..81cf4bb --- /dev/null +++ b/database/migrations/2026_12_03_100000_create_communication_tables.php @@ -0,0 +1,141 @@ +id(); + $table->foreignId('parent_id')->nullable()->constrained('inquiry_issues')->restrictOnDelete(); + $table->string('key', 60)->unique(); + $table->string('label', 120); + $table->text('description')->nullable(); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_fields', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->string('label', 200); + $table->text('help')->nullable(); + $table->string('type', 20); + $table->json('options')->nullable(); + $table->json('settings')->nullable(); + $table->string('purpose', 20)->nullable(); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_field_groups', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->string('label', 200)->nullable(); + $table->text('description')->nullable(); + $table->json('items'); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_templates', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->text('description')->nullable(); + $table->json('draft'); + $table->unsignedBigInteger('published_version_id')->nullable()->index(); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_template_versions', function (Blueprint $table): void { + $table->id(); + $table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete(); + $table->unsignedInteger('version'); + $table->json('definition'); + $table->json('source'); + $table->string('note', 300)->nullable(); + $table->foreignId('published_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamp('published_at'); + $table->unique(['template_id', 'version']); + }); + + Schema::create('inquiry_entries', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete(); + $table->json('config'); + $table->json('published_config')->nullable(); + $table->timestamp('published_at')->nullable(); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiries', function (Blueprint $table): void { + $table->id(); + $table->string('reference', 20)->unique(); + $table->foreignId('entry_id')->nullable()->constrained('inquiry_entries')->restrictOnDelete(); + $table->foreignId('template_version_id')->constrained('inquiry_template_versions')->restrictOnDelete(); + $table->string('submission_token', 64)->unique(); + $table->string('issue_key', 60)->nullable(); + $table->string('issue_label', 120)->nullable(); + $table->string('subissue_key', 60)->nullable(); + $table->string('subissue_label', 120)->nullable(); + $table->string('contact_name', 200)->nullable(); + $table->string('contact_email', 200)->nullable(); + $table->string('contact_phone', 60)->nullable(); + $table->string('organisation', 200)->nullable(); + $table->text('message')->nullable(); + $table->json('answers'); + $table->string('source_path', 300)->nullable(); + $table->string('status', 20)->default('neu')->index(); + $table->timestamp('notified_at')->nullable(); + $table->text('notification_error')->nullable(); + $table->timestamps(); + $table->index('created_at'); + }); + + Schema::create('inquiry_notes', function (Blueprint $table): void { + $table->id(); + $table->foreignId('inquiry_id')->constrained('inquiries')->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->text('body'); + $table->timestamps(); + }); + + Schema::create('communication_settings', function (Blueprint $table): void { + $table->id(); + $table->json('recipients'); + $table->unsignedSmallInteger('retention_months')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('communication_settings'); + Schema::dropIfExists('inquiry_notes'); + Schema::dropIfExists('inquiries'); + Schema::dropIfExists('inquiry_entries'); + Schema::dropIfExists('inquiry_template_versions'); + Schema::dropIfExists('inquiry_templates'); + Schema::dropIfExists('inquiry_field_groups'); + Schema::dropIfExists('inquiry_fields'); + Schema::dropIfExists('inquiry_issues'); + } +}; diff --git a/docs/architektur/12_Entscheidungsprotokoll_ADR.md b/docs/architektur/12_Entscheidungsprotokoll_ADR.md index c7bd731..c456a1a 100644 --- a/docs/architektur/12_Entscheidungsprotokoll_ADR.md +++ b/docs/architektur/12_Entscheidungsprotokoll_ADR.md @@ -885,3 +885,61 @@ ## ADR-59 – Hinweiszeile: kompakter Hinweis mit optional aufklappbarer Kurzdar - **Gestaltung:** Schriftgrößen XS, S (Vorgabe), M, L; S, M und L sind `--text-small`, `--text-body` und `--text-lede` des Designsystems. **XS (13 px) gibt es im Designsystem nicht** und ist die einzige neue Größe (`--notice-fs` in `lf-hinweiszeile.css`), nur für Randbemerkungen. Symbol von 1 bis 3,5 rem, unabhängig von der Schrift; Fläche (Grün, Gelb, Creme), Rahmen und Akzentlinie nur mit Tokens. Auf einer Fläche gilt immer die helle Wertegruppe, auf dunklen und grünen Abschnitten ohne Fläche steht das Symbol auf einer weißen Scheibe (wie bei den Karten). **Folgen.** Keine Migration. Neue Widget-Art; eine einmal gespeicherte Kennung `notice` bleibt (Rückfall: ein Code-Stand ohne das Widget kennt den Baustein nicht und zeigt ihn nicht an; die übrige Seite bleibt unverändert; gespeicherte Revisionen enthalten ihn weiterhin). **Quelle.** Entwicklungsauftrag von Lars vom 27.11.2026; ADR-30, ADR-38, ADR-50. + + +## ADR-60 – Zentrale Kommunikationsverwaltung: Anfragevorlagen, Anfrage-Einstiege und ein schlankes CMS-Widget + +**Status am 27.11.2026:** Umgesetzt auf `feature/kommunikation-grundlage` und `develop`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Beschreibung und Betrieb: `docs/architektur/kommunikationsverwaltung.md`. +**Kontext.** Lara & Felix braucht mehrere Kontaktanlässe (allgemeine Fragen, Kursanfragen, Materialien, Kooperationen), später auch für eine übergeordnete Dachmarke. Ein Formular je Seite oder ein Formularbaukasten im CMS würde Felder, Bedingungen und Empfänger über viele Seiten verteilen. Es gab bisher weder ein Kontaktformular noch einen Posteingang (belegt: im Repository kein Kontakt- oder Anfragemodell; vorhanden waren Filament-Verwaltung, Widget-Registry, Warteschlange `database`, Postausgang `OrderConfirmed`). +**Entscheidung (Auftrag von Lars, 27.11.2026).** +- **Eine führende Quelle: die Verwaltungsgruppe „Kommunikation“.** Anliegen und Unteranliegen, Feldkatalog, Feldgruppen, Anfragevorlagen, Anfrage-Einstiege, Empfänger und Posteingang werden dort gepflegt. Das CMS wählt nur einen veröffentlichten Anfrage-Einstieg aus. Im CMS gibt es keine Formularinhalte, Regeln, Texte oder Empfänger. +- **Neue Widget-Art `inquiry` („Anfrage“), Version 1.** Gespeichert wird allein `refs.entry` (Kennung des Einstiegs). Formular, Bedingungen, Token und Annahme liefert der Server zur Laufzeit (`/anfrage/{einstieg}`); die gespeicherte Seite enthält keinen Formularstand. Dadurch gilt eine zentrale Veröffentlichung sofort auf allen Seiten, ohne Seitenrevisionen anzufassen. +- **Entwurf und Fassungen.** Eine Anfragevorlage hat einen bearbeitbaren Entwurf und unveränderliche, vollständig aufgelöste Fassungen (Bezeichnungen, Auswahlwerte, Regeln, Schritte sind hineinkopiert). Wirksam ist nur die bewusst veröffentlichte Fassung; eine frühere lässt sich wieder in Kraft setzen oder als Entwurf laden. Eine Anfrage bleibt für immer der Fassung zugeordnet, die der Besucher sah, und speichert Bezeichnungen und Werte als Schnappschuss. Ein Anfrage-Einstieg hat ebenfalls Entwurf und veröffentlichten Stand und folgt der gültigen Fassung seiner Vorlage; vor dem Veröffentlichen einer Vorlage sind die betroffenen Einstiege sichtbar, und passt ein veröffentlichter Einstieg nicht zur neuen Fassung, wird sie abgelehnt. +- **Regeln sind Daten, keine Skripte.** Wirkungen: anzeigen, ausblenden, Pflicht, Schritt überspringen, vorbelegen. Bedingungen: ist / ist nicht / ist eines von / ist keines von, über Anliegen, Unteranliegen sowie Auswahl- und Ja/Nein-Felder, mit „alle“ oder „mindestens eine“. Die Verwaltung bietet nur Auswahllisten an, die sich aus dem Aufbau der Vorlage ableiten. **Eine Bedingung darf nur auf Felder vor ihrem Ziel verweisen**; so gibt es keine Zirkelbezüge, und die Auswertung ist ein einziger Durchlauf. +- **Eine Auswertung für alle.** Ein PHP-Auswerter (`FormEvaluator`) bedient Besucher, Vorschau und Anfrageservice. Der Browser fragt nach jeder Änderung einer steuernden Auswahl den Zustand beim Server ab (`/anfrage/{einstieg}/zustand`) und baut Sichtbarkeit und Pflicht daraus auf; es gibt keine zweite Regelauswertung in JavaScript. Werte ausgeblendeter Fragen bleiben im Browser erhalten (kein Datenverlust beim Zurückwechseln), werden aber nie gesendet; der Server verwirft sie ohnehin. +- **Zwei Darstellungen, eine Beschreibung.** Kompaktformular und mehrstufiger Dialog (Fortschritt, Zurück/Weiter, Zusammenfassung vor dem Absenden, Sprung zurück zu einem Schritt) bauen aus derselben Beschreibung. Übersprungene Schritte entfallen. +- **Zentraler Anfrageservice** (`InquiryService`): Token prüfen, gültige Fassung bestimmen, Bedingungen auswerten, serverseitig validieren (Typen, Auswahlwerte, Grenzen, unbekannte Schlüssel), in einer Transaktion speichern, erst danach benachrichtigen. Doppeltes Absenden ergibt dieselbe Anfrage (Einmalkennung im verschlüsselten Formular-Token). Schutz: CSRF der bestehenden Web-Gruppe, Köderfeld, Mindestdauer, Ratenbegrenzung je Adresse, Größenbegrenzung. Eine Erfolgsmeldung erscheint erst nach dem Speichern. +- **Benachrichtigung.** Warteschlangen-Aufgabe `SendInquiryNotification` an die in der Verwaltung gepflegten Empfänger (nie aus Besucher- oder CMS-Eingaben). Die Nachricht nennt nur Kennzeichen, Anliegen und den Weg zur Anfrage, keine Kontaktdaten und keine Antworten. Ein Versandfehler verliert keine Anfrage: er wird an der Anfrage vermerkt (`notification_error`), im Posteingang angezeigt und lässt sich dort wiederholen. +- **Posteingang** unter „Kommunikation → Anfragen“: Liste mit Suche, Filter (Status, Anliegen, Benachrichtigungsfehler) und Sortierung; Detail mit lesbaren Antworten, Quellseite, Einstieg, Fassung, Status von Hand (Neu, In Bearbeitung, Rückfrage offen, Erledigt) und internen Notizen. Zugriff: Kundenbetreuung und Systemverwaltung (personenbezogene Daten). Löschen einer Anfrage nur durch die Systemverwaltung. Konfiguration: Redaktion und Systemverwaltung. Keine neue Rolle. +- **Datenschutz.** Keine Namen oder Gesundheits- und Entwicklungsdaten einzelner Kinder im Standardformular (Hinweise an den Feldern); keine Weitergabe an Dritte, keine KI-Dienste. **Keine pauschale Pflicht-Einwilligungsbox.** Der Datenschutzhinweis ist ein pflegbarer Text je Vorlage oder Einstieg; Rechtsgrundlage, Wortlaut und Aufbewahrungsdauer sind mit dem Datenschutzkonzept abzugleichen (offen). +- **Anliegen sind zweistufig** (Anliegen, Unteranliegen). Tiefere Auswahlen wie das Kursformat sind **Auswahlfelder** mit bedingter Anzeige, kein dritter Baumzweig; das hält die Auswertung einfach. Der Auftrag verlangte keine Beschränkung auf genau drei Ebenen, aber keine Baum-Engine. +**Alternativen.** Formularfelder und Texte im CMS-Widget (verworfen: verteilte Pflege, Rechte, Versionierung doppelt). Livewire auf öffentlichen Seiten (verworfen: öffentliche Seiten laufen ohne Livewire, ADR-32). Regelauswertung zusätzlich in JavaScript (verworfen: zwei Auslegungen). Freie JSON-Eingabe oder Ausdrücke (verworfen: Sicherheit, Bedienbarkeit). Generische Workflow- oder Formular-Engine (verworfen: Auftrag). KI-Assistent (nicht Teil des Auftrags). +**Folgen.** Eine additive Migration `2026_12_03_100000_create_communication_tables` mit neun neuen Tabellen (`inquiry_issues`, `inquiry_fields`, `inquiry_field_groups`, `inquiry_templates`, `inquiry_template_versions`, `inquiries`, `inquiry_entries`, `inquiry_notes`, `communication_settings`); nichts Bestehendes wird verändert. Neue Widget-Art `inquiry`; eine einmal gespeicherte Kennung bleibt (Rückfall: ein Code-Stand ohne das Widget zeigt den Baustein nicht, die übrige Seite bleibt unverändert). Es entstehen keine Beispieldaten durch Migration; eine Beispielkonfiguration legt ein Betreiber mit „Kommunikation → Einstellungen → Beispielkonfiguration anlegen“ an (nur in einer leeren Verwaltung). Der Befehl `communication:purge` löscht Anfragen nach der gewählten Aufbewahrungsdauer; ein Zeitplaner ist nicht eingerichtet (offen). +**Ausblick (nicht umgesetzt, nur nicht verbaut).** Ein KI-Assistent könnte dieselben Vorlagen und Felder nutzen und am Ende denselben Anfrageservice aufrufen (kein zweiter Service, keine zweite Datenhaltung, Absenden erst nach ausdrücklicher Bestätigung, klassisches Formular bleibt). Eine Dachmarke braucht eigene Anfragevorlagen und Einstiege, keine Mehrmandantenfähigkeit. Anmeldung, Termine, Plätze und Zahlung sind ausdrücklich ausgeschlossen. Anfragen können später manuell weiterbearbeitet werden; eine automatische Weitergabe oder Trainervermittlung ist nicht vorgesehen und braucht einen eigenen rechtlichen Prozess. +**Quelle.** Entwicklungsauftrag von Lars vom 27.11.2026; ADR-30, ADR-32, ADR-38. + + +## ADR-61 – Kommunikation: Formular-Editor an einem Ort und Anfragegründe im CMS-Widget + +**Status am 27.11.2026:** Umgesetzt auf `feature/kommunikation-ux` und `develop`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Ergänzt ADR-60, ersetzt es nicht. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` (Abschnitt 12). +**Kontext.** Die Engine aus ADR-60 funktioniert, die Bedienung war zu technisch: Für ein Formular mussten Anliegen, Feldkatalog, Feldgruppen, Anfragevorlage und Anfrage-Einstieg getrennt bedient werden, und das CMS-Widget wählte nur einen vorher angelegten Einstieg. Der Auftrag vom 27.11.2026 verlangt weniger Bedienaufwand und eine bessere CMS-Einbindung, ausdrücklich ohne Umbau der Engine, ohne neues Datenmodell und ohne Änderung der Anfrageverarbeitung, soweit nicht zwingend. +**Entscheidung.** +- **Navigation:** Anfragen, Formulare & Befragungen, Einstellungen. Anliegen, Feldkatalog, Feldgruppen und Anfrage-Einstiege bleiben als Objekte, Seiten und Adressen erhalten (Verweise, ältere Seiten, Tests), stehen aber nicht mehr in der Hauptnavigation; „Einstellungen“ verweist darauf. +- **Formular-Editor** (`FormEditor`, `TemplateEditor`): ein Formular wird an einer Stelle bearbeitet. Ansicht: Bereiche (im mehrstufigen Dialog je ein Schritt), darin Felder, Teilbereiche (Überschrift im Fluss, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“) und die Frage nach dem Anliegen. Felder entstehen direkt im Bereich oder werden aus dem Katalog übernommen. Es gibt keine zweite Datenhaltung: Der Editor schreibt neue und geänderte Felder und Teilbereiche in dieselben Katalogtabellen und liefert denselben Entwurf (`steps`, `rules`) wie bisher; beim Öffnen wird er in die flache Ansicht übersetzt. Ein Test belegt, dass jedes Beispielformular unverändert öffnet und wieder genau denselben Entwurf und denselben Katalog ergibt. +- **Gemeinsame Felder:** Ein Feld oder Teilbereich, der in mehreren Formularen vorkommt, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare („gilt dort mit der nächsten Veröffentlichung“). Bestehende Fassungen sind unveränderlich. Die Art eines vorhandenen Feldes ist nicht änderbar (Bedingungen und Antworten bauen darauf auf); eine andere Art ist ein neues Feld. Auswahlwerte behalten ihre Kennung bei Umbenennung. +- **Bedingungen am Element:** Feld, Teilbereich und Bereich tragen ihre Bedingung selbst (Wirkung, „alle/mindestens eine“, Vergleiche, alles als Auswahl). Beim Speichern entstehen daraus dieselben Regeln der Engine. Was sich nicht an ein Element heften lässt (weitere Regeln desselben Ziels, Vorbelegungen), bleibt unter „Weitere Regeln“ erhalten und wird nie verworfen. Zur Auswahl stehen nur Felder, die im Formular weiter oben stehen (die Prüfung verlangt es ohnehin). Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. +- **Kleine Erweiterung der Engine:** `show` und `hide` wirken auch auf Bereiche (bisher nur `skip`), damit „Bereich nur anzeigen, wenn …“ ohne umgekehrte Bedingungen ausdrückbar ist. `skip` bleibt gültig. +- **Widget „Anfrage“ ohne Anfrage-Einstieg:** Das Widget speichert Anfragegründe (`data.reasons`: Kennung, Bezeichnung, Beschreibung, Formular, optional vorgewähltes Anliegen und Unteranliegen), die Frage der Auswahl und die Beschriftung des Buttons sowie Einstellungen: **Formularführung** (`mode`: langes Formular oder mehrstufiger Dialog) und **Präsentation** (`open`: im Abschnitt oder als Dialog) unabhängig voneinander; Gestaltung: Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten folgt der Containerbreite; es gibt keine Einstellung je Bildschirmgröße. +- **Genau ein Formular je Grund:** Der Besucher wählt einen Grund; erst dann lädt der Browser das Formular dieses Grundes (`/anfrage/formular/{vorlage}?anliegen=…&unteranliegen=…&modus=…`, Zustand und Absenden ebenso). Je Grund gibt es höchstens eine Formularinstanz; ein Wechsel blendet nur um, Eingaben bleiben. Bei einem einzigen Grund entfällt die Auswahl. Eine Vorauswahl über die Adresse (`?grund=Kennung`) wählt den Grund und öffnet bei „Dialog“ den Dialog. +- **Der Grund ist Vorauswahl und Darstellung, keine Berechtigung.** Alles, was ein Grund wählen kann, bietet das veröffentlichte Formular ohnehin an. Deshalb steht der Grund in der Adresse und nicht in einer signierten Konfiguration; die Auslieferung bleibt zustandslos. Aus dem Grund entsteht dieselbe Konfiguration wie bei einem Einstieg (`FormReason`, `FormFactory::effective`). Auslieferbar ist jede veröffentlichte, nicht archivierte Vorlage; die Veröffentlichung ist die bewusste Handlung. +- **Anfrageverarbeitung unverändert:** Dieselbe Auswertung, Prüfung, Doppelsende- und Köderfeld-Abwehr, Ratenbegrenzung und Benachrichtigung. Das Formular-Token erhält die Art des Ziels (`entry` oder `form`) und ist nicht zwischen beiden austauschbar. Eine Anfrage über das Widget hat keine Einstiegskennung (`entry_id` war bereits optional) und verweist über ihre Fassung auf die Vorlage; der Posteingang zeigt „Formular …“. Keine Migration. +- **Dialog:** natives `dialog`-Element (`showModal`): Esc und „Schließen“ behalten die Eingaben, der Fokus kehrt zum Button zurück, die Seite dahinter ist fixiert, auf dem Smartphone füllt der Dialog den Bildschirm, die Aktionen bleiben unten erreichbar. In den Vorschau-Iframes des Seiteneditors (nur Stile, kleine feste Fläche) steht der Dialog als gerahmtes Beispiel; Seitenvorschau und Geräteansicht öffnen den echten Dialog. +- **Ältere Seiten:** Eine Seite mit `refs.entry` und ohne Anfragegründe wird weiter dargestellt; der Anfrage-Einstieg bleibt als Objekt erhalten. +**Alternativen.** Signierte Widget-Konfiguration in der Seite (verworfen: Der Grund ist keine Berechtigung; mehr bewegliche Teile ohne Gewinn). Neue Tabellen für Widget-Konfigurationen (ausgeschlossen: kein neues Datenmodell). Verschachtelte Teilbereiche mit eigenen Feldlisten im Editor (verworfen: sechs Ebenen Formularstruktur, schwer bedienbar; die flache Liste mit „Ende des Teilbereichs“ bildet dasselbe ab). Feldänderungen je Formular als Kopie (verworfen: zweite Wahrheit; der Hinweis auf gemeinsame Verwendung genügt, Fassungen sind unveränderlich). +**Folgen.** Keine Migration. Zwei bestehende Tests wurden bewusst geändert (Widget-Vertrag: Anfragegründe statt Einstieg). Rückfall: ein Code-Stand ohne ADR-61 kennt `data.reasons` nicht und zeigt ein so gespeichertes Widget nicht an (die Seite bleibt gültig); Formulare und Anfragen bleiben unverändert, im Katalog angelegte Felder bleiben bestehen. +**Quelle.** Entwicklungsauftrag von Lars (UX-Überarbeitung der Kommunikationsverwaltung und des CMS-Kontakt-Widgets) vom 27.11.2026; ADR-60. + +## ADR-62 – Kommunikation: Formularansicht mit Ziehen und Ablegen statt Builder-Liste + +**Status am 28.11.2026:** Umgesetzt auf `feature/formular-editor-umbau`; praktische Abnahme durch den Betreiber auf `luf-test` offen. Ändert die Darstellung aus ADR-61, nicht die Daten. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` (Abschnitt 13). +**Kontext.** Der Aufbau eines Formulars bestand aus verschachtelten Filament-Listen (Repeater und Builder mit aufklappbaren Blöcken). Bei einem Formular mit wenigen Feldern wirkte das riesig und unübersichtlich; ein Teilbereich sah aus wie ein geschlossener Block, dem man nichts zuordnen konnte (die Felder darunter gehörten nur über die Reihenfolge dazu). Der Betreiber verlangte eine formularähnliche Darstellung: links die Frage, daneben der Feldtyp, Hilfetext und Bedingungen über Symbole in einem Pop-up, Bereiche und Teilbereiche deutlich als Einheit, Ziehen und Ablegen für Felder und Teilbereiche. +**Entscheidung.** +- **Eigene Formularansicht** (`filament/communication/form-editor*.blade.php`, Alpine): Bereich = Karte mit Nummer, Titel und Symbolen (Einleitung, Bedingung, weitere Einstellungen, Entfernen); darin Felder als Zeilen (Griff, Frage, Art der Antwort, Pflicht, Symbole für Hilfetext, Auswahlwerte, Bedingung, weitere Einstellungen, Entfernen) und Teilbereiche als eingerahmte Einheit mit eigener Feldliste. Hilfetext, Auswahlwerte, Bedingung, Verwendung in der Anfrageübersicht, Verschieben nach … und der Katalog öffnen in einem Pop-up (natives `dialog`); gesetzte Angaben sind am Symbol markiert, die Bedingung steht als Satz unter dem Element. +- **Ziehen und Ablegen** mit SortableJS, das Filament mitliefert (`window.Sortable`, keine neue Abhängigkeit): Bereiche untereinander, Felder an jede Stelle eines Bereichs oder Teilbereichs, Teilbereiche zwischen Bereiche. Ein Teilbereich nimmt nur Felder auf. Ohne Maus: am Griff Pfeil hoch oder runter (am Rand verlässt ein Feld den Teilbereich) und „Verschieben nach …“ im Pop-up „Weitere Einstellungen“. +- **Rückgängig** nimmt Änderungen am Aufbau bis zum Speichern zurück (Hinzufügen, Entfernen, Verschieben). Entfernen fragt deshalb nicht nach. +- **Daten unverändert:** Der Browser führt den Baum (Bereiche → Felder und Teilbereiche → Felder) und übergibt ihn beim Speichern als Text. `FormEditor::validateTree` prüft ihn serverseitig (Titel, Frage, Auswahlwerte, Längen, Dopplungen, höchstens eine Frage nach dem Anliegen) und nennt Fehlendes, statt still zu kürzen; `FormEditor::fromTree` überführt ihn in dieselbe flache Ansicht wie bisher, aus der `persist` Katalog und Entwurf schreibt. Die Umwandlung `toTree`/`fromTree` ist verlustfrei; ein Test führt jedes Beispielformular durch den Baum und erhält denselben Entwurf und Katalog. Keine Migration, keine Änderung an Engine, Katalog und Anfrageverarbeitung. +- **Fehlende Angaben** sind rot umrandet und gezählt; das Speichern lehnt ein unvollständiges Formular mit den Gründen ab und legt nichts an. +- **Weitere Regeln** (Vorbelegungen, zusätzliche Regeln desselben Ziels) bleiben unverändert als Liste im Register „Weitere Regeln“; sie lesen den Aufbau aus dem Baumtext und werden kurz nach Änderungen mit dem Server abgeglichen. +**Alternativen.** Filament-Builder mit besseren Blocktiteln (verworfen: bleibt eine aufklappbare Endlosliste ohne sichtbare Zugehörigkeit). Neue Datenstruktur mit verschachtelten Teilbereichen im Entwurf (ausgeschlossen: kein neues Datenmodell; die Zugehörigkeit steht schon als Feldgruppe im Katalog). Eigenes Ziehen ohne Bibliothek (verworfen: Berührung, Animation und Randfälle liefert SortableJS). +**Folgen.** Keine Migration. Die Livewire-Tests des Editors wurden bewusst auf den Baumtext umgestellt (der Builder entfällt). Rückfall auf ADR-61: Der Entwurf bleibt gültig; die ältere Ansicht liest ihn wieder. Das Ziehen bietet auf Berührungsbildschirmen SortableJS-Standardverhalten, wurde dort aber nicht geprüft. +**Quelle.** Rückmeldung von Lars vom 28.11.2026 zur Bedienung des Formular-Editors; ADR-61. diff --git a/docs/architektur/cms-widget-registry.md b/docs/architektur/cms-widget-registry.md index 50ef27e..556ab72 100644 --- a/docs/architektur/cms-widget-registry.md +++ b/docs/architektur/cms-widget-registry.md @@ -136,6 +136,16 @@ ## 4. Registrierte Widget-Arten - Das Kit lädt das Einstiegsbild immer sofort; hier nur beim ersten Widget der Seite, alle anderen verzögert. - Kit-CSS ergänzt: Überschriften erben Farbe (globale h1–h3-Regeln), Unterstreichung als Block, Fläche `clear` übernimmt die Farben dunkler Abschnitte, Strahlen-Akzent aus `components/brand/rays.blade.php`, Fokusfarbe aus den Tokens. +### Anfrage (`inquiry`, Version 1, ADR-60, ADR-61) + +Kontaktformular mit Auswahl des **Anfragegrundes**. `data.reasons` (bis zu 8): `key` (entsteht beim Speichern, stabil), `label`, `description`, `template` (Kennung eines veröffentlichten Formulars), optional `issue` und `subissue` (vorgewähltes Anliegen); dazu `question` und `open_label`. Einstellungen (`settings`): `mode` (compact, wizard), `open` (inline, modal), `picker` (cards, select), `width`, `spacing`, `columns`, `button`; Formularführung und Präsentation sind unabhängig. Das Widget kennt weder Felder noch Texte, Regeln oder Empfänger; diese werden unter „Kommunikation → Formulare & Befragungen“ gepflegt. Seiten der ersten Fassung (`refs.entry`, kein Grund) werden weiter dargestellt. + +- Prüfung: nur die Existenz des Formulars (`reasons.*.template`), damit eine später zurückgezogene Vorlage eine Seite nicht unspeicherbar macht. Öffentlich erscheint ein Grund nur, solange sein Formular veröffentlicht und nicht archiviert ist; ohne verfügbaren Grund bleibt das Widget leer, die Vorschau nennt den Grund. +- Darstellung: `data-config` mit Gründen und Adressen (`/anfrage/formular/{vorlage}?anliegen=…&modus=…`); `resources/js/inquiry-widget.js` zeigt die Auswahl, lädt erst nach der Wahl das Formular des Grundes und hält je Grund eine Instanz. Dialog als natives `dialog`. Vorauswahl über `?grund=Kennung`. +- Vorschau-Iframes im Seiteneditor laden nur Stile: Die Widget-Ansicht lädt dort `resources/js/inquiry-embed.js` (eigener Vite-Einstieg); der Dialog steht dort als gerahmtes Beispiel. +- Platz: 3 oder 4 Rastereinheiten; Breite, Abstände und Feldanordnung sind Einstellungen, Umbrüche folgen der Containerbreite. +- Sprungmarke: Ein Abschnitt mit Sprungmarke lässt sich mit Links wie `/kontakt?grund=kurse_workshops#anfrage` ansteuern. + ## 5. Neues Widget hinzufügen 1. Klasse unter `app/Domain/Cms/Widgets/Types/` anlegen, von `WidgetType` ableiten. Pflicht: `key()`, `label()`, `description()`, `dataRules()`, `dataFields()`. Je nach Bedarf: `variants()`, Layoutvertrag `supportedUnits()`/`preferredUnits()`/`heights()`/`stages()`/`narrowBehavior()` (Abschnitt 12), `settings()`/`settingLabels()` (Bezeichnung und Erklärung für das (i))/`settingGroups()`/`settingHiddenWhen()`/`optionIcons()`, `mediaSchema()` für den Reiter „Medien“, `refRules()`, `refFields()`, `clean()` (Links mit `SafeUrl`, Text mit `RichText::sanitize`, Bilder mit `ImageRefFields::clean`), `resolve()`, `mediaPaths()`, `summary()`, `schematic()`, `icon()`. diff --git a/docs/architektur/kommunikationsverwaltung.md b/docs/architektur/kommunikationsverwaltung.md new file mode 100644 index 0000000..1aed50d --- /dev/null +++ b/docs/architektur/kommunikationsverwaltung.md @@ -0,0 +1,162 @@ +# Kommunikationsverwaltung: Anfragevorlagen, Anfrage-Einstiege und Posteingang + +Stand: 27.11.2026. Entscheidung: ADR-60 im [Entscheidungsprotokoll](12_Entscheidungsprotokoll_ADR.md). Auftrag: Entwicklungsauftrag von Lars vom 27.11.2026 („Zentrale Kommunikationsverwaltung mit dynamischem Anfrage-Widget“). + +Leitprinzip: **Eine zentrale Kommunikationsverwaltung für alle Inhalte und Prozesse. Ein schlankes CMS-Widget für die Platzierung. Ein gemeinsamer Anfrageservice für alle Anfragen.** + +## 1. Bestandsanalyse (Schritt 1 des Auftrags) + +Belegt im Repository vor der Umsetzung: + +| Thema | Befund | +|---|---| +| Kontakt- oder Anfragemodelle | keine (kein Modell, keine Tabelle, kein Formular) | +| E-Mail und Warteschlange | Laravel-Mail; `MAIL_MAILER=log` in der Vorgabe, auf Servern über `/etc/luf/*.env`; Warteschlange `database`; ein Postausgang (`OrderConfirmed`), direkt gesendet | +| Verwaltung | Filament 5, Gruppen „Inhalte“, „Katalog“, „Verkauf“, „Stammdaten“; Listen über `ListsCatalog` und die gemeinsame Bestandsliste; Rechte über `StaffRole` | +| CMS | Widget-Registry (ADR-30, `config/cms.php`), Abschnitte mit Plätzen (ADR-38), Revisionen, Vorschau; öffentliche Seiten ohne Livewire, Skripte über Vite | +| Rechte | `User::hasStaffRole()`, mehrere Rollen je Konto; Rollen Redakteur, Katalogverwalter, Kundenbetreuung, Systemverwalter u. a. | +| Sitzung und CSRF | Web-Gruppe mit Sitzung und CSRF auch auf öffentlichen Routen (Warenkorb, Anmeldung); ADR-32 (sitzungsfreie Seiten) ist Entwurf und nicht umgesetzt | + +Die im Auftrag genannten Unterlagen `docs/00_LUF_Projektkompass.md` und `docs/01_LUF_Zielbild_und_Fachkonzept_v1.1.md` gibt es unter diesen Pfaden im Repository nicht. Herangezogen wurden stattdessen `docs/architektur/01_Zielbild_und_Faehigkeiten.md`, `cms-widget-registry.md`, `designsystem.md`, `website-cms-marketing-zielarchitektur.md`, `docs/fachkonzept/*`, `docs/prinzipien/*` und `12_Entscheidungsprotokoll_ADR.md`. Inhalte der fehlenden Dokumente wurden nicht erfunden. + +Abweichungen und Einordnung: Die Produkt- und Lizenzarchitektur bleibt unverändert; es entsteht kein Bezug zu Konten, Lizenzen oder Kauf. Das Startseiten-Redaktionskonzept liegt nicht vor; die Besucherführung nach §21 (Links „Über Kursangebote informieren“ und „Hier unverbindlich anfragen“) wird als Redaktionsschritt beschrieben (Abschnitt 9), nicht per Migration in bestehende Seiten geschrieben. + +## 2. Bausteine + +| Baustein | Ort | +|---|---| +| Modelle und Logik | `app/Domain/Communication/` | +| Verwaltung | `app/Filament/Resources/Communication/` (Anliegen, Felder, Gruppen, Vorlagen, Einstiege, Anfragen), Seite `KommunikationEinstellungen`, `app/Filament/Support/TemplateEditor.php` | +| Öffentliche Schnittstelle | `InquiryFormController` (`/anfrage/{einstieg}`, `/zustand`, `/senden`), `InquiryPreviewController` (`/redaktion/anfrage/…`) | +| Darstellung | `resources/js/inquiry-form.js`, `resources/css/components/lf-anfrage.css`, Komponente `x-inquiry.mount` | +| CMS | Widget `inquiry` (`app/Domain/Cms/Widgets/Types/InquiryWidget.php`, `resources/views/widgets/inquiry.blade.php`) | +| Benachrichtigung | `SendInquiryNotification`, `InquiryReceived`, `CommunicationTestMail` | +| Beispiele | `ExampleConfiguration` (nur auf Wunsch aus „Einstellungen“) | + +Wiederverwendet: Filament-Formularkomponenten, gemeinsame Bestandsliste (`ListsCatalog`, `ShowsBestand`), Widget-Registry, Warteschlange, Mail, Rechte über `StaffRole`, Designtokens (`tokens.css`). + +## 3. Datenmodell + +Alle Tabellen sind neu (Migration `2026_12_03_100000_create_communication_tables`): + +- `inquiry_issues`: Anliegen und Unteranliegen (`parent_id`), stabile Kennung, Bezeichnung, Reihenfolge, aktiv, archiviert. +- `inquiry_fields`: Feldkatalog (Kennung, fachliche und öffentliche Bezeichnung, Hilfetext, Typ, Auswahlwerte mit stabilen Kennungen, Grenzen, Verwendung in der Anfrageübersicht). +- `inquiry_field_groups`: geordnete Liste von Feldern mit Pflichtangabe. +- `inquiry_templates` und `inquiry_template_versions`: Entwurf (`draft`) und unveränderliche, aufgelöste Fassungen mit Quelle (`source`). +- `inquiry_entries`: Konfiguration (`config`) und veröffentlichter Stand (`published_config`). +- `inquiries`: Anfrage mit Fassungsbezug, Kontaktspalten (zur Anzeige), `answers` (Schnappschuss je Antwort: Kennung, Bezeichnung, Typ, Wert, Anzeigetext, Schritt, Gruppe), Quellseite, Status, Benachrichtigungsstand, Einmalkennung. +- `inquiry_notes`: interne Notizen. `communication_settings`: Empfänger und Aufbewahrungsdauer. + +Feldtypen: Text, mehrzeiliger Text, E-Mail, Telefon, Zahl, Einfachauswahl, Mehrfachauswahl, Ja/Nein, Datum, Zeitraum. Ein neuer technischer Typ ist eine kontrollierte Softwareerweiterung (`FieldType`, `FieldValue`, `inquiry-form.js`). + +## 4. Bedienung in der Verwaltung + +Gruppe „Kommunikation“ (Menüreihenfolge: Anfragen, Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen, Anfrage-Einstiege, Einstellungen). + +1. **Anliegen und Unteranliegen** anlegen (Dialog), bearbeiten, mit „Nach oben/unten“ sortieren, deaktivieren oder archivieren. Die Kennung entsteht einmal aus der Bezeichnung; Umbenennen ändert sie nie. +2. **Feldkatalog:** Feld mit Typ anlegen; bei Auswahlfeldern die Werte als Liste pflegen (Kennungen bleiben bei Umbenennung stabil). Grenzen (Länge, kleinster und größter Wert) und die Verwendung („E-Mail-Adresse für Rückfragen“, Name, Telefon, Organisation, Nachricht) einstellen. Jede Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“. +3. **Feldgruppen:** Felder in Reihenfolge, je Feld Pflicht ja/nein. +4. **Anfragevorlage:** Reiter *Aufbau* (Schritte; je Schritt Bausteine: Auswahl des Anliegens, Feldgruppe, Einzelfeld), *Regeln* (Wirkung, Ziel, Bedingungen, alles als Auswahl), *Texte* (Überschrift, Beschreibung, Fragen, Schaltflächen, Zusammenfassung, Bestätigung, Fehlermeldung, Datenschutzhinweis). Aktionen: **Vorschau** (gespeicherter Entwurf, wählbar als Kompaktformular oder mehrstufiger Dialog), **Konfiguration prüfen**, **Veröffentlichen** (Dialog nennt die betroffenen Einstiege; Bemerkung zur Fassung). Unter „Fassungen“: wieder in Kraft setzen oder als Entwurf laden. +5. **Anfrage-Einstieg:** Vorlage, zugelassene Anliegen und Unteranliegen, Vorauswahl (zum Beispiel Kursformat „Schul-AG“), Formularart (kompakt oder mehrstufig), Öffnung (direkt oder erst per Schaltfläche), Texte überschreiben. Aktionen: Vorschau, Veröffentlichen, Zurückziehen, Archivieren. +6. **Posteingang** „Anfragen“: Suche, Filter, Sortierung; Detail mit Antworten, Status, Notizen, erneutem Versand der Benachrichtigung und (nur Systemverwaltung) Löschen. +7. **Einstellungen:** Empfänger, Aufbewahrungsdauer, Testnachricht, Beispielkonfiguration. + +## 5. Regeln und Prüfungen + +Gespeichert wird immer, veröffentlicht nur eine gültige Konfiguration. Beim Veröffentlichen prüft `TemplateCompiler`: Verweise auf verfügbare Gruppen und Felder, doppelte Verwendung, Ziele und Wirkungen, Bedingungsquellen (nur Auswahl- und Ja/Nein-Felder sowie Anliegen), gültige Vergleichswerte, **Reihenfolge (Quelle vor Ziel)**, Vorbelegungen, Widersprüche (gleiche Bedingung zeigt und blendet aus), genau ein Feld je Verwendung, mindestens ein Feld „E-Mail für Rückfragen“. + +Auswertung (`FormEvaluator`): ein Durchlauf in Dokumentreihenfolge; Bedingungen sehen nur sichtbare Felder davor; ein ausgeblendetes Feld, eine ausgeblendete Gruppe oder ein übersprungener Schritt liefern keine Werte. + +## 6. Anfrageverarbeitung + +`InquiryService::submit`: Token (verschlüsselt: Einstieg, Fassung, Zeitpunkt, Einmalkennung) → Doppelsendung erkennen → Fassung und wirksames Formular → Köderfeld und Mindestdauer → Eingaben auswerten und prüfen → Transaktion → Benachrichtigung nach dem Speichern. Fehlerantworten: 422 mit Feldmeldungen, 419 abgelaufen (der Browser holt einmal ein neues Token und sendet erneut), 429 zu schnell oder zu häufig, 410 nicht mehr verfügbar. + +## 7. Berechtigungen und Sicherheit + +| Funktion | Rollen | +|---|---| +| Anliegen, Felder, Gruppen, Vorlagen, Einstiege, Vorschau | Redakteur, Systemverwalter | +| Posteingang, Notizen, Status, Einstellungen | Kundenbetreuung, Systemverwalter | +| Anfrage löschen | Systemverwalter | +| Widget „Anfrage“ im CMS | wie das übrige CMS (Redakteur); sieht nur Name der veröffentlichten Einstiege | + +Maßnahmen: serverseitige Prüfung aller Werte, nur bekannte Schlüssel, nur angebotene Auswahlwerte, Ausgabe stets maskiert (Blade und `textContent`), Ratenbegrenzung (5 je Minute und 20 je Stunde je Adresse für das Senden, 120 je Minute für die Zustandsabfrage), Größenbegrenzung der Eingaben, keine Kontaktdaten in der Benachrichtigung, keine öffentliche Angabe von Empfängern. + +## 8. Versionierung und Veröffentlichung + +Entwurf → Prüfen → Vorschau → Veröffentlichen als neue Fassung. Fassungen sind unveränderlich (das Modell verweigert Änderung und Löschen). Eine Anfrage speichert Fassung und Bezeichnungen. Ein Einstieg zeigt immer die gültige Fassung seiner Vorlage; die CMS-Seite enthält nur die Einstiegs-Kennung und wird nie umgeschrieben. + +## 9. Einbindung im CMS und Besucherführung + +Im Seiteneditor: Widget „Anfrage“ einfügen, einen veröffentlichten Einstieg wählen, speichern und veröffentlichen. Mehr gibt es im CMS nicht zu pflegen. Für die Sprungmarke des Abschnitts („Anfrage“ als Sprungmarke `anfrage`) funktionieren Links wie `/kurse#anfrage` mit dem Linkwähler. + +Besucherführung nach §21 (Redaktionsschritte, nicht Teil der Migration): Startseite „Über Kursangebote informieren“ und Hero „Kurse & Workshops“ führen auf die künftige Kursübersichtsseite; dort steht oben „Hier unverbindlich anfragen“ mit Ziel `#anfrage` auf das eingebundene Widget; ein allgemeiner Kontaktweg gehört in Navigation oder Fußbereich (Seite mit dem Einstieg „Allgemeiner Kontakt“). + +## 10. Beispielkonfiguration + +„Einstellungen → Beispielkonfiguration anlegen“ (nur in leerer Verwaltung) legt an und veröffentlicht: vier Anliegen mit zwei Unteranliegen (sechs Einträge), 38 Felder, 12 Feldgruppen, vier Vorlagen und fünf Einstiege: *Allgemeiner Kontakt* (kompakt, Name, E-Mail, Nachricht), *Kurse & Workshops* (mehrstufig, Information oder konkretes Vorhaben mit Einrichtung, Träger, Durchführungsort, Kindergruppe, Planung), *Schul-AG* (mehrstufig, Format und konkretes Vorhaben vorausgewählt, Zusatzfragen zur Laufzeit), *Programme & Materialien*, *Kooperation*. Alles ist gewöhnliche Konfiguration und in der Verwaltung änderbar. + +## 11. Offene fachliche und rechtliche Prüfpunkte + +- Datenschutzhinweis (Wortlaut), Rechtsgrundlage und Informationspflichten mit dem Datenschutzkonzept abgleichen; keine Pflicht-Einwilligungsbox ohne Prüfung. +- Aufbewahrungsdauer festlegen; ein Zeitplaner für `communication:purge` ist nicht eingerichtet (Betrieb). +- E-Mail-Versand auf den Servern: `MAIL_*` in `/etc/luf/test.env` und `/etc/luf/prod.env`; solange `MAIL_MAILER=log` gilt, kommt keine Nachricht an (der Posteingang vermerkt dennoch „gesendet“, weil der Mailer die Nachricht annimmt). Wirksamkeit mit der Testnachricht in den Einstellungen prüfen. +- Kursformate sind Arbeitsvorschläge; das Formular darf keine Termine, Preise oder Buchung suggerieren (Texte der Beispiele sind entsprechend formuliert). +- Spam-Schutz: Köderfeld, Mindestdauer und Ratenbegrenzung. Ein externes Captcha ist nicht eingebaut (Datenschutz); bei Missbrauch nachrüsten. +- Texte des Beispiels sind Entwürfe des Betreibers zur Prüfung. + +## 12. UX-Überarbeitung (ADR-61) + +Stand: 27.11.2026. Menü der Gruppe „Kommunikation“: **Anfragen**, **Formulare & Befragungen**, **Einstellungen**. Die Abschnitte 4 und 9 gelten für Anliegen, Feldkatalog, Feldgruppen und Einstiege weiter, nur ohne eigenen Menüpunkt; erreichbar sind sie unter „Einstellungen → Weitere Bausteine“. + +### Formular bearbeiten + +1. „Formulare & Befragungen“ → „Formular anlegen“ (Name) → der Editor öffnet. +2. Reiter **Aufbau:** Bereiche (Titel, Einleitung, Bedingung), darin „Feld oder Teilbereich hinzufügen“. + - **Feld:** Frage, Art der Antwort (nach dem Speichern fest), Auswahlwerte, Hilfetext, Pflicht, Bedingung; „Vorhandenes Feld verwenden“ übernimmt ein Feld aus dem Katalog (zum Beispiel die E-Mail-Adresse). Unter „Weitere Einstellungen“ die Verwendung in der Anfrageübersicht. Jedes Formular braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“. + - **Teilbereich:** Überschrift für die folgenden Felder, bis zum nächsten Teilbereich oder „Ende des Teilbereichs“. + - **Frage nach dem Anliegen:** die Auswahl des Anliegens (angebotene Anliegen). + - **Bedingung** (Feld, Teilbereich, Bereich): „nur anzeigen, wenn …“, „ausblenden, wenn …“, bei Feldern „Pflichtfeld, wenn …“, bei Bereichen „überspringen, wenn …“. Beispiel: Teilbereich „Angaben zur Schule“ nur anzeigen, wenn „Sind Sie eine Schule?“ = Ja. +3. Reiter **Texte:** Überschrift, Beschreibung, Schaltflächen, Bestätigung, Datenschutzhinweis. Reiter **Weitere Regeln:** nur, was sich nicht an ein Element heften lässt (zum Beispiel Vorbelegungen). +4. **Speichern**, **Konfiguration prüfen**, **Vorschau** (als langes Formular oder mehrstufig, es wird nichts gesendet), **Veröffentlichen** (neue Fassung, sofort gültig überall, wo das Formular eingebunden ist), Fassungen unten (zurückkehren möglich). + +Ein Feld, das mehrere Formulare nutzen, wird an Ort und Stelle bearbeitet; der Editor nennt die anderen Formulare. Die Änderung gilt dort mit deren nächster Veröffentlichung. + +### Widget „Anfrage“ im Seiteneditor + +- Reiter **Inhalt:** **Anfragegründe** (Bezeichnung, Kurzbeschreibung, Formular, optional Anliegen und Unteranliegen vorwählen), Frage der Auswahl, Beschriftung des Buttons. Die Kennung eines Grundes (für Links) entsteht beim Speichern. +- Reiter **Darstellung:** **Formularführung** (langes Formular oder mehrstufig, Schritt für Schritt) und **Präsentation** (im Abschnitt oder im Pop-up-Fenster über der Seite) getrennt; Auswahl als Karten oder Auswahlfeld, Breite, Abstände, Feldanordnung, Buttondarstellung. Das responsive Verhalten ergibt sich aus der verfügbaren Breite. +- **Vorauswahl durch einen Button der Seite:** Link auf die Seite mit `?grund=Kennung` (und gegebenenfalls `#Sprungmarke`). Das Widget wählt den Grund und öffnet bei „Dialog“ den Dialog. +- Mehrere zulässige Gründe: Der Besucher sieht zuerst die Frage, danach nur das Formular seines Grundes („Anderen Grund wählen“ wechselt, Eingaben bleiben je Grund erhalten). Ein einziger Grund: kein Auswahlschritt. +- Vorschau im Dialog des Widgets, in der Seitenvorschau und in der Geräteansicht. + +### Öffentliche Adressen und Grenzen + +`/anfrage/formular/{vorlage}` (Beschreibung und Token), `/zustand`, `/senden`; Grund in der Adresse (`anliegen`, `unteranliegen`, `modus`). Dieselbe Ratenbegrenzung wie bei Einstiegen. Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. Nicht umgesetzt: Vorbelegung weiterer Felder (zum Beispiel Kursformat) je Anfragegrund; dafür bleibt der Anfrage-Einstieg. + +## 13. Formularansicht des Aufbaus (ADR-62) + +Der Aufbau eines Formulars ist eine eigene Ansicht statt einer Filament-Liste. + +### Aufbau der Ansicht + +- **Bereich** (im mehrstufigen Dialog ein Schritt): Karte mit Nummer, Titel und Symbolen für Einleitung, Bedingung, weitere Einstellungen und Entfernen. Darunter die Felder und Teilbereiche, am Ende „Neues Feld“, „Vorhandenes Feld einfügen“, „Teilbereich“ und (einmal im Formular) „Frage nach dem Anliegen“. +- **Teilbereich:** eingerahmte Einheit im Bereich mit Überschrift, Symbolen und eigener Feldliste („Neues Feld im Teilbereich“). Die Bedingung gilt für alle Felder darin. +- **Feld:** eine Zeile mit Griff, Frage, Art der Antwort und Pflicht. Symbole öffnen Pop-ups: Hilfetext, Auswahlwerte (nur bei Auswahlfeldern, mit Zähler), Bedingung, weitere Einstellungen. Die Art ist nach dem ersten Speichern gesperrt. +- **Bedingung:** Wirkung, „alle/mindestens eine“, Vergleiche auf Felder oberhalb des Elements und die Frage nach dem Anliegen; als Satz unter dem Element sichtbar. Verweist eine Bedingung nach einer Verschiebung auf ein Feld darunter, ist das Symbol gelb markiert. +- **Weitere Einstellungen:** Verwendung in der Anfrageübersicht, Hinweis auf gemeinsame Verwendung, „Verschieben nach …“. +- **Rückgängig** bis zum Speichern; Hinweiszeile mit Anzahl der Bereiche, Felder und Teilbereiche. + +### Bedienung + +- **Ziehen:** am Griff; Felder in jeden Bereich und Teilbereich, Teilbereiche zwischen Bereiche, Bereiche untereinander. +- **Tastatur:** Griff fokussieren, Pfeil hoch oder runter; am Rand eines Teilbereichs verlässt das Feld ihn. „Verschieben nach …“ setzt ein Element ans Ende eines Bereichs oder Teilbereichs. +- **Fehlende Angaben** (Titel, Frage, Auswahlwerte) sind rot umrandet; Speichern nennt die Gründe und ändert nichts. + +### Technik + +`TemplateEditor` liefert die Ansicht über ein `ViewField` (`editor_json`). Der Browser führt den Baum (Alpine, `form-editor-script.blade.php`) und schreibt ihn beim Speichern als Text. `FormEditor::validateTree` prüft, `fromTree` überführt ihn in die flache Ansicht, `persist` schreibt Katalog und Entwurf wie bisher; `toTree` ist die Gegenrichtung beim Öffnen. Nach dem Speichern liefert der Server den Baum mit festen Kennungen, die Ansicht übernimmt ihn (sonst legte ein zweites Speichern Felder doppelt an). Keine Migration. + +### Grenzen + +Ziehen auf Berührungsbildschirmen und Screenreader-Ansagen sind nicht geprüft. Neue Felder und Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung. Die Regelliste „Weitere Regeln“ ist unverändert. diff --git a/docs/betrieb/Release-Vorbereitung_2026-11-21.md b/docs/betrieb/Release-Vorbereitung_2026-11-21.md index 6fb01d8..44b11e2 100644 --- a/docs/betrieb/Release-Vorbereitung_2026-11-21.md +++ b/docs/betrieb/Release-Vorbereitung_2026-11-21.md @@ -16,6 +16,9 @@ ## 1. Inhalt (Stand 21.11.2026 abends: 22 Commits seit `main`) | Reiter „Darstellung“ gegliedert | Aufbau, Gruppen je Widget, Erklärungen im (i), Einzelschalter für Texte verschwinden bei „Texte auf der Karte: Ausblenden“; Bezeichnungen vereinheitlicht. Keine Migration, gespeicherte Werte unverändert | Claude | | 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 | +| Kommunikation: Formularansicht des Aufbaus (ADR-62) | Der Aufbau eines Formulars ist eine eigene Ansicht mit Ziehen und Ablegen, Pop-ups für Hilfetext, Auswahlwerte und Bedingung (statt Builder-Liste). Keine Migration, Daten unverändert. Rückfall auf ADR-61 liest denselben Entwurf. Livewire-Tests des Editors bewusst auf den Baumtext umgestellt. | 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 | @@ -47,6 +50,7 @@ ## 3. Migrationen (Prod steht bei der 32. Migration `2026_11_20_200000_editorial | `2026_11_21_130000_allow_deleting_media_with_stills_and_aliases` | lockert zwei Fremdschlüssel (`film_still_sources`, `website_media_aliases`) | ja, lockert nur | | `2026_11_21_140000_create_composition_still_sources` | neue Tabelle | ja | | `2026_12_02_100000_add_anchor_to_navigation_items` | nullable Spalte `anchor` an `navigation_items` | ja, additiv (ältere Stände ignorieren sie; der Menülink führt dann zum Seitenanfang) | +| `2026_12_03_100000_create_communication_tables` | neun neue Tabellen (`inquiry_*`, `inquiries`, `communication_settings`) | ja, additiv (ältere Stände ignorieren sie) | Keine bestehende Migration wurde geändert. Verglichen mit der Migrationstabelle von Prod (lesend): Prod hat 32 angewendet, `develop` 37 Dateien, **genau diese fünf sind ausstehend**, nichts auf Prod fehlt in `develop`. Prod hat 0 Bestellungen; die Rückrechnung in `add_shop_foundation` hat dort nichts zu tun. Der Rollback des Deploy-Skripts setzt nur den Code zurück, nicht die Datenbank; die neuen Tabellen und gelockerten Schlüssel stören älteren Code nicht. diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht.md b/docs/ux/verwaltung/abnahme/formular-ansicht.md new file mode 100644 index 0000000..e17b1ac --- /dev/null +++ b/docs/ux/verwaltung/abnahme/formular-ansicht.md @@ -0,0 +1,27 @@ +# Abnahme: Formularansicht des Aufbaus (ADR-62) + +Stand: 28.11.2026, Testinstanz `luf-test` auf `develop` @ `41bf9a0`. Prüfung durch Claude im Browser (Playwright, Chromium) über die echte Oberfläche; die praktische Abnahme durch den Betreiber steht aus. Entscheidung: ADR-62, Beschreibung: `docs/architektur/kommunikationsverwaltung.md` Abschnitt 13. Screenshots: `abnahme/formular-ansicht/`. + +## Anforderungen aus der Rückmeldung vom 28.11.2026 + +| Anforderung | Umsetzung | Beleg | +|---|---|---| +| Keine Endloslisten, Formular-Darstellung: links die Frage, daneben der Feldtyp | Feld = eine Zeile: Griff, Frage, Art der Antwort, Pflicht, Symbole | `aufbau-neu` | +| Hilfetext, Bedingungen über Symbole, als Pop-up | Symbole je Feld, Teilbereich und Bereich öffnen ein Pop-up (Hilfetext, Auswahlwerte, Bedingung, weitere Einstellungen); gesetzte Angaben sind am Symbol markiert, die Bedingung steht als Satz unter dem Element | `dialog-hilfetext`, `dialog-auswahlwerte`, `dialog-bedingung` | +| Bereiche und Teilbereiche deutlich abgegrenzt, eine visuelle Einheit | Bereich = Karte mit grünem Rand und Nummer; Teilbereich = blau eingerahmte Einheit mit eigener Feldliste, „Neues Feld im Teilbereich“ | `aufbau-neu`, `nach-ziehen` | +| Felder und Teilbereiche per Ziehen an beliebige Positionen | SortableJS: Feld in jeden Bereich und Teilbereich, Teilbereich zwischen Bereiche, Bereiche untereinander | `nach-ziehen` | + +## Geprüft auf luf-test (26 von 26 Prüfungen) + +Formular über die Liste anlegen; Bereich, Felder, Auswahlfeld (Pop-up öffnet sofort, drei Werte), Hilfetext, Teilbereich mit zwei Feldern; Feld in den Teilbereich ziehen und zurück, Teilbereich in einen anderen Bereich, Bereich nach oben; zweimal „Rückgängig“; Tastatur (Pfeil runter am Griff, Fokus bleibt); Speichern zweimal ohne Doppelungen (feste Kennungen, gleicher Aufbau nach Neuladen); Bedingung am Teilbereich („nur anzeigen, wenn Welches Format … ist Schul-AG“); „Verschieben nach …“; fehlende Frage: rote Meldung mit Grund, nichts gespeichert; 1440, 768 und 390 px ohne waagerechtes Scrollen; Pop-up passt auf 390 px; Esc schließt das Pop-up; keine Skriptfehler. + +Lokal zusätzlich: kein Warnhinweis beim Verlassen ohne Änderung, Warnung nach einer Änderung, Register „Weitere Regeln“ und „Konfiguration prüfen“ aus der neuen Ansicht. Tests (Gitea-Gate, grün): Baumumwandlung ohne Verlust über alle Beispielformulare, Teilbereich mit Feldern und Einzelfeld danach, Prüfung fehlender Angaben, Anlegen im Editor mit zweimaligem Speichern, Ablehnung eines unvollständigen Formulars. + +## Nicht geprüft oder offen + +- **Berührungsbildschirme:** Ziehen mit dem Finger und Screenreader-Ansagen nicht geprüft; ohne Maus gehen Pfeiltasten am Griff und „Verschieben nach …“. +- **Tastatur in der Verwaltung** nur für Griff, Pop-ups und Esc geprüft, nicht für jede Kombination. +- **Neue Felder und Auswahlwerte** stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung (Hinweis im Pop-up). +- **Veröffentlichen** aus der neuen Ansicht ist durch Tests belegt, auf luf-test nicht durchgespielt. +- **Testinhalte auf luf-test:** mehrere Formulare „Editor Formular …“ und „Pruef Formular …“ (unveröffentlicht); zum Löschen oder Archivieren durch den Betreiber. +- Der Screenshot-Ausschnitt zeigt in Vollseitenaufnahmen die mitlaufende Kopfleiste mitten im Bild; das ist ein Aufnahmeartefakt, kein Fehler der Seite. diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-neu.png b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-neu.png new file mode 100644 index 0000000..77c90b8 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-neu.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-schmal.png b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-schmal.png new file mode 100644 index 0000000..89ce6ea Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-schmal.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-tablet.png b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-tablet.png new file mode 100644 index 0000000..64491ec Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/aufbau-tablet.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-auswahlwerte.png b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-auswahlwerte.png new file mode 100644 index 0000000..255ea73 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-auswahlwerte.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-bedingung.png b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-bedingung.png new file mode 100644 index 0000000..1864555 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-bedingung.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-hilfetext.png b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-hilfetext.png new file mode 100644 index 0000000..7f041b1 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-hilfetext.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-schmal.png b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-schmal.png new file mode 100644 index 0000000..8f3eac7 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/dialog-schmal.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/fehler.png b/docs/ux/verwaltung/abnahme/formular-ansicht/fehler.png new file mode 100644 index 0000000..5d3e9f0 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/fehler.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/gespeichert.png b/docs/ux/verwaltung/abnahme/formular-ansicht/gespeichert.png new file mode 100644 index 0000000..4b1f128 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/gespeichert.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/nach-ziehen.png b/docs/ux/verwaltung/abnahme/formular-ansicht/nach-ziehen.png new file mode 100644 index 0000000..960b8b1 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/nach-ziehen.png differ diff --git a/docs/ux/verwaltung/abnahme/formular-ansicht/neu-leer.png b/docs/ux/verwaltung/abnahme/formular-ansicht/neu-leer.png new file mode 100644 index 0000000..9c6e192 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/formular-ansicht/neu-leer.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux.md b/docs/ux/verwaltung/abnahme/kommunikation-ux.md new file mode 100644 index 0000000..b3fa7ed --- /dev/null +++ b/docs/ux/verwaltung/abnahme/kommunikation-ux.md @@ -0,0 +1,33 @@ +# Abnahme: Formular-Editor und Anfragegründe im Widget (ADR-61) + +Stand: 27.11.2026, Testinstanz `luf-test` auf `develop` @ `5bc362d`. Prüfung durch Claude im Browser (Playwright, Chromium) über die echte Oberfläche; die praktische Abnahme durch den Betreiber steht aus. Beschreibung: `docs/architektur/kommunikationsverwaltung.md` Abschnitt 12, Entscheidung ADR-61. Screenshots: `abnahme/kommunikation-ux/`. + +## Die sieben Abnahmefälle des Auftrags + +| Nr. | Anwendungsfall | Ergebnis auf luf-test | Beleg | +|---|---|---|---| +| 1 | Ein Formular vollständig in einem Editor bearbeiten | Formular angelegt; drei Felder, ein Teilbereich und ein Feld darin direkt im Bereich angelegt (Texte, Pflicht, Verwendung E-Mail, Ja/Nein, Auswahlwerte), Bedingung am Teilbereich gesetzt, geprüft, veröffentlicht, ohne einen anderen Verwaltungsbereich zu öffnen. Die Beispielformulare öffnen und speichern unverändert (Test). | `neu-leer`, `felder-offen`, `bedingung`, `vorschau` | +| 2 | Im Widget mehrere Anfragegründe konfigurieren, ohne Einstieg | Seite `/anfrage-widget-abnahme` im Seiteneditor: drei Gründe (Allgemeine Anfrage, Kurse & Workshops, Zusammenarbeit) mit Formular und vorgewähltem Anliegen; kein Anfrage-Einstieg angelegt. | `dialog-gruende-inline`, `seite-editor` | +| 3 | Besucher wählt einen Grund und erhält ausschließlich das zugehörige Formular | Zuerst die Frage „Worum geht es?“; nach der Wahl genau ein Formular, das Anliegen ist vorgewählt und wird nicht erneut gefragt; „Anderen Grund wählen“ wechselt, Eingaben je Grund bleiben erhalten. | `breit-1`, `breit-2` | +| 4 | Dasselbe Formular als Langformular oder mehrstufiger Dialog | Einstellung „Formularführung“ je Widget: Abschnitt 1 langes Formular, Abschnitt 2 mehrstufig mit Fortschritt. | `breit-2`, `breit-5` | +| 5 | Beide Führungen inline und als Dialog | Einstellung „Präsentation“ unabhängig davon: lokal sechs Widgets in unterschiedlichen Kombinationen (Karten oder Auswahlfeld, inline oder Dialog, lang oder mehrstufig, ein oder mehrere Gründe); auf luf-test lang/inline und mehrstufig/Dialog. Dialog: Esc und Schließen behalten die Eingaben, Fokus kehrt zum Button zurück, Seite dahinter fixiert. | `breit-4`, `breit-5` | +| 6 | Desktop und Smartphone | 1280/1440 px und 390 px: kein waagerechtes Scrollen, Karten stehen untereinander, der Dialog füllt den Bildschirm, „Weiter“/„Absenden“ bleiben unten erreichbar. Tablet (768 px) wurde für das Widget nicht gesondert geprüft; die Umbrüche folgen der Containerbreite. | `schmal-1` bis `schmal-3` | +| 7 | Anfrage absenden und unverändert verarbeiten | Anfrage über das Widget abgesendet (Kennzeichen), im Posteingang mit Herkunft „Formular …“, Quellseite, Antworten und Status/Notizen wie bisher. Die bestehenden Tests für Einstiege laufen unverändert. | `breit-3`, `posteingang-liste`, `posteingang-anfrage` | + +Weitere Prüfungen: Vorauswahl über `?grund=Kennung` (wählt den Grund, öffnet bei „Dialog“ den Dialog), Vorschau des Widgets im Bearbeitungsdialog (Dialog als gerahmtes Beispiel), Seitenvorschau und Geräteansicht (echter Dialog, kein Senden), alte Seiten mit Anfrage-Einstieg werden weiter dargestellt (Test). + +## Prüfumfang + +- **Browser (luf-test):** Editor 10 von 10, Widget im Seiteneditor und öffentlich 11 von 11, Besucher, Smartphone und Posteingang 11 von 11 Prüfungen. +- **Browser (lokal):** öffentliche Abläufe mit allen Kombinationen 30 von 30, Seitenvorschau und Geräteansicht 5 von 5. +- **Tests (Gitea-Gate, grün):** unter anderem Auslieferung je Grund, Token (Einstieg und Formular nicht austauschbar), nicht veröffentlichte oder archivierte Formulare, Bedingungen am Element und Umwandlung in Regeln, unveränderter Round-Trip aller Beispielformulare, Anlegen im Editor mit zweimaligem Speichern ohne Doppelungen, Navigation. Bewusst geändert: zwei Tests zum Widget-Vertrag (Anfragegründe statt Einstieg). + +## Nicht geprüft oder offen + +- **E-Mail-Zustellung** der Benachrichtigung (Empfänger in „Einstellungen“ eintragen, „Testnachricht senden“) wie bei ADR-60. +- **Tastatur in der Verwaltung** (Editor) und **Screenreader** nicht geprüft; öffentlich: Auswahl per Tastatur, Fokus im Dialog (Esc, Rückkehr zum Button) geprüft. +- **Neue Felder in Bedingungen:** Ein Feld und seine Auswahlwerte stehen in Bedingungen erst nach dem ersten Speichern zur Verfügung (Hinweis im Editor). +- **Vorbelegung weiterer Felder** (zum Beispiel Kursformat „Schul-AG“) je Anfragegrund gibt es nicht; ein Grund wählt Formular, Anliegen und Unteranliegen. Dafür bleibt der Anfrage-Einstieg. +- **Gemeinsame Felder:** Eine Änderung an einem Feld, das mehrere Formulare nutzen, wirkt dort mit deren nächster Veröffentlichung; der Editor nennt die anderen Formulare. +- **Darstellung des Dialogs in der Live-Vorschau des Widgets** ist ein verkleinertes Beispiel; die Prüfung des echten Dialogs geht über Seitenvorschau oder Geräteansicht. +- **Testseiten auf luf-test:** `/anfrage-widget-abnahme` (veröffentlicht), Formular „Pruef Formular Abnahme“, mehrere Prüfanfragen („Mira Widget …“) im Posteingang; zum Zurückziehen oder Löschen durch den Betreiber. diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/bedingung.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/bedingung.png new file mode 100644 index 0000000..ecbd98e Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/bedingung.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-1-auswahl-karten.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-1-auswahl-karten.png new file mode 100644 index 0000000..09e0036 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-1-auswahl-karten.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-2-langes-formular-inline.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-2-langes-formular-inline.png new file mode 100644 index 0000000..7bdb37a Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-2-langes-formular-inline.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-3-erfolg.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-3-erfolg.png new file mode 100644 index 0000000..bcc2faa Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-3-erfolg.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-4-dialog-auswahl.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-4-dialog-auswahl.png new file mode 100644 index 0000000..66ae66a Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-4-dialog-auswahl.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-5-dialog-mehrstufig.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-5-dialog-mehrstufig.png new file mode 100644 index 0000000..6bfa616 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/breit-5-dialog-mehrstufig.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-inline.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-inline.png new file mode 100644 index 0000000..b8066fd Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-inline.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-modal.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-modal.png new file mode 100644 index 0000000..6fd76e4 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-darstellung-modal.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-inline.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-inline.png new file mode 100644 index 0000000..c059d4c Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-inline.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-modal.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-modal.png new file mode 100644 index 0000000..b2b388f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/dialog-gruende-modal.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/felder-offen.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/felder-offen.png new file mode 100644 index 0000000..fa75e2f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/felder-offen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/neu-leer.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/neu-leer.png new file mode 100644 index 0000000..7244e2b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/neu-leer.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-dialog.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-dialog.png new file mode 100644 index 0000000..a205d6f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-dialog.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-lang.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-lang.png new file mode 100644 index 0000000..629f230 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/oeffentlich-lang.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-anfrage.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-anfrage.png new file mode 100644 index 0000000..35f992f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-anfrage.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-liste.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-liste.png new file mode 100644 index 0000000..5270a23 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/posteingang-liste.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-1-auswahl.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-1-auswahl.png new file mode 100644 index 0000000..b1b7908 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-1-auswahl.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-2-langes-formular.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-2-langes-formular.png new file mode 100644 index 0000000..d3503d8 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-2-langes-formular.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-3-dialog.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-3-dialog.png new file mode 100644 index 0000000..7d9fbe3 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/schmal-3-dialog.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/seite-editor.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/seite-editor.png new file mode 100644 index 0000000..bc8005d Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/seite-editor.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation-ux/vorschau.png b/docs/ux/verwaltung/abnahme/kommunikation-ux/vorschau.png new file mode 100644 index 0000000..033d9cb Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation-ux/vorschau.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation.md b/docs/ux/verwaltung/abnahme/kommunikation.md new file mode 100644 index 0000000..69af8f0 --- /dev/null +++ b/docs/ux/verwaltung/abnahme/kommunikation.md @@ -0,0 +1,35 @@ +# Abnahme: Kommunikationsverwaltung (ADR-60) + +Stand: 27.11.2026, Testinstanz `luf-test` auf `develop` @ `b9407c2`. Prüfung durch Claude im Browser (Playwright, Chromium) über die echte Oberfläche; die praktische Abnahme durch den Betreiber steht aus. Beschreibung: `docs/architektur/kommunikationsverwaltung.md`. + +## Was geprüft wurde (luf-test) + +**Verwaltung, 17 von 17 Prüfungen** (Skript `admin_e2e`, Prüfkonto mit Redaktion, Kundenbetreuung und Systemverwaltung): +- A1 Anliegen über den Dialog anlegen; Kennung steht fest. +- A3 Auswahlfeld mit eigenen Auswahlwerten anlegen. +- A6/A7/A14 In der Vorlage „Kursanfragen“ eine Regel („Ausblenden, wenn Unteranliegen = Allgemeine Kursinformation“) über Auswahllisten anlegen, speichern, „Konfiguration prüfen“, „Veröffentlichen“ (der Dialog nennt die betroffenen Einstiege „Kurse & Workshops“ und „Schul-AG“, Bemerkung zur Fassung). +- B5 Die veröffentlichte Regel wirkt sofort auf den öffentlichen Zustand (Kursformat bei „Information“ ausgeblendet). Danach die Regel wieder entfernt und neu veröffentlicht: ursprüngliches Verhalten (Fassungen 2 und 3 stehen im Verlauf). +- A10/A13 Vorschau eines Einstiegs: mehrstufiger Dialog, Hinweis „es wird nichts gesendet“. +- D4/D5 Status ändern und interne Notiz hinterlegen im Posteingang. +- 390 px: Vorlagen, Anfragen, Einstiege ohne waagerechtes Scrollen. +- Aufräumen: die Prüfeinträge („Pruef …“) wurden archiviert, nichts gelöscht. + +**CMS (Seiteneditor, echte Oberfläche):** Beispielkonfiguration über „Kommunikation → Einstellungen“ angelegt (fünf Einstiege veröffentlicht). Seite `/anfrage-abnahme-1` mit drei Abschnitten (Sprungmarken `kontakt`, `kurse`, `schul-ag`) und Seite `/anfrage-abnahme-2` mit demselben Einstieg „Allgemeiner Kontakt“ angelegt: im Dialog „Widget einsetzen → Anfrage“ stehen nur die fünf veröffentlichten Einstiege zur Auswahl, sonst nichts. Beide Seiten sind veröffentlicht und zeigen das Formular (B1 bis B4, B7). + +**Öffentliche Formulare, 33 von 33 Prüfungen** (Skript `form_e2e` gegen `/anfrage-abnahme-1`): Kompaktformular mit Fehleranzeige und Fokus auf die Fehlerübersicht; Erfolgsmeldung mit Kennzeichen erst nach dem Speichern; mehrstufiger Dialog (Fortschritt, Weiter nur mit Auswahl, Fokus auf dem Schritttitel, Träger- und Ortsangaben und Schulart bedingt, „Ändern“ aus der Zusammenfassung, Werte bleiben beim Hin- und Herwechseln, Schritt 2 entfällt bei „Information“, nichts aus dem übersprungenen Schritt in der Zusammenfassung); Vorauswahl „Schul-AG“ und Wechsel des Formats; manipulierte Eingaben liefern 422; 390 px und 768 px ohne waagerechtes Scrollen; Auswahl per Tastatur; keine Fehler in der Browserkonsole. + +Aus Tests (Gitea-Gate, 1270+ Tests grün): Bedingungen, Validierung, Doppelsendung, Köderfeld, Mindestdauer, Ratenbegrenzung, Versandfehler ohne Datenverlust, historische Anfragen nach Katalogänderung, Berechtigungen (D10), Veröffentlichung und Rückkehr zu einer Fassung. + +## Screenshots + +In `abnahme/kommunikation/`: `breit-*` (1440 px: Anliegen, Feld anlegen und bearbeiten, Regel, Veröffentlichen, Fassungen, Einstieg, Vorschau, Posteingang, Anfrage, Einstellungen), `schmal-*` (390 px), `d-tablet-schritt2.png` (768 px), `a-*`, `b-*`, `e-*` (öffentliches Formular breit und schmal). + +## Nicht geprüft oder offen + +- **E-Mail-Zustellung (D6):** Auf luf-test wurden keine Empfänger hinterlegt (kein Empfänger vorgegeben). Der Posteingang zeigt daher „Keine Empfänger hinterlegt“ an der Anfrage, die Anfrage ist gespeichert (D7 am Ablauf belegt). Ob der Mailserver zustellt (`MAIL_MAILER` auf luf-test unbekannt, vermutlich `log`), ist nicht belegt. Zum Prüfen: Empfänger in „Einstellungen“ eintragen und „Testnachricht senden“. +- **Tastatur in der Verwaltung:** nur das öffentliche Formular wurde per Tastatur geprüft (Tab, Leertaste, Fokus), nicht die Verwaltungsmasken. +- **Screenreader:** keine Prüfung mit einem Screenreader; Auszeichnung nach Fieldset/Legend, `aria-live`, `aria-busy`, Fehlerübersicht mit Fokus. +- **Meldungstexte:** Meldungen der Laufzeitprüfung in der Verwaltung stehen teils englisch („The wenn … field is required.“), weil es für die Laravel-Validierung keine deutsche Sprachdatei gibt; das gilt für die gesamte Verwaltung. +- **Besucherführung nach §21** (Links auf der Startseite und der Kursübersicht, allgemeiner Kontaktweg) ist ein Redaktionsschritt und wurde auf luf-test nicht verändert. +- **Rechtliches:** Wortlaut des Datenschutzhinweises, Rechtsgrundlage und Aufbewahrungsdauer sind offen; ein Zeitplaner für `communication:purge` ist nicht eingerichtet. +- **Testseiten auf luf-test:** `/anfrage-abnahme-1`, `/anfrage-abnahme-2` (veröffentlicht, zum Löschen oder Zurückziehen durch den Betreiber), mehrere Prüfanfragen („Mira Beispiel“) im Posteingang. diff --git a/docs/ux/verwaltung/abnahme/kommunikation/a-erfolg.png b/docs/ux/verwaltung/abnahme/kommunikation/a-erfolg.png new file mode 100644 index 0000000..88fc668 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/a-erfolg.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/a-kompakt-breit.png b/docs/ux/verwaltung/abnahme/kommunikation/a-kompakt-breit.png new file mode 100644 index 0000000..caedbdf Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/a-kompakt-breit.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/b-schritt2-breit.png b/docs/ux/verwaltung/abnahme/kommunikation/b-schritt2-breit.png new file mode 100644 index 0000000..95641a1 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/b-schritt2-breit.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/b-zusammenfassung-breit.png b/docs/ux/verwaltung/abnahme/kommunikation/b-zusammenfassung-breit.png new file mode 100644 index 0000000..70cd782 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/b-zusammenfassung-breit.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-anfrage-detail.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-anfrage-detail.png new file mode 100644 index 0000000..d2b2f72 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-anfrage-detail.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-anfragen-liste.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-anfragen-liste.png new file mode 100644 index 0000000..a60f1a5 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-anfragen-liste.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-anliegen-bearbeiten.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-anliegen-bearbeiten.png new file mode 100644 index 0000000..7f8d898 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-anliegen-bearbeiten.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-einstellungen.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-einstellungen.png new file mode 100644 index 0000000..0ab5164 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-einstellungen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-einstieg-bearbeiten.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-einstieg-bearbeiten.png new file mode 100644 index 0000000..a36868d Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-einstieg-bearbeiten.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-anlegen.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-anlegen.png new file mode 100644 index 0000000..8970a28 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-anlegen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-bearbeiten.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-bearbeiten.png new file mode 100644 index 0000000..e288306 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-feld-bearbeiten.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-regel-neu.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-regel-neu.png new file mode 100644 index 0000000..374121b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-regel-neu.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-fassungen.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-fassungen.png new file mode 100644 index 0000000..b65cd4f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-fassungen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-veroeffentlichen.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-veroeffentlichen.png new file mode 100644 index 0000000..c9af98c Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorlage-veroeffentlichen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/breit-vorschau-einstieg.png b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorschau-einstieg.png new file mode 100644 index 0000000..b08e77f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/breit-vorschau-einstieg.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/d-tablet-schritt2.png b/docs/ux/verwaltung/abnahme/kommunikation/d-tablet-schritt2.png new file mode 100644 index 0000000..22aadfd Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/d-tablet-schritt2.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt1.png b/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt1.png new file mode 100644 index 0000000..d849742 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt1.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt2.png b/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt2.png new file mode 100644 index 0000000..366fd94 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/e-schmal-schritt2.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/schmal-anfragen.png b/docs/ux/verwaltung/abnahme/kommunikation/schmal-anfragen.png new file mode 100644 index 0000000..c97d132 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/schmal-anfragen.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/schmal-einstiege.png b/docs/ux/verwaltung/abnahme/kommunikation/schmal-einstiege.png new file mode 100644 index 0000000..7e32d02 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/schmal-einstiege.png differ diff --git a/docs/ux/verwaltung/abnahme/kommunikation/schmal-vorlagen.png b/docs/ux/verwaltung/abnahme/kommunikation/schmal-vorlagen.png new file mode 100644 index 0000000..6cd93ab Binary files /dev/null and b/docs/ux/verwaltung/abnahme/kommunikation/schmal-vorlagen.png differ diff --git a/resources/css/app.css b/resources/css/app.css index ba892e2..399511c 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -15,6 +15,8 @@ @import './components/lf-karten-verteilung.css'; /* Hinweiszeile (Widget „notice“). */ @import './components/lf-hinweiszeile.css'; +/* Anfrageformular (ADR-60): Kompaktformular und mehrstufiger Dialog. */ +@import './components/lf-anfrage.css'; /* Premium-Widgets nach Brand-UI-Kit v1.6; ersetzen das frühere Hero- und Bild-und-Text-CSS. */ @import './components/lf-hero.css'; @import './components/lf-bild-text.css'; diff --git a/resources/css/components/lf-anfrage.css b/resources/css/components/lf-anfrage.css new file mode 100644 index 0000000..9853f11 --- /dev/null +++ b/resources/css/components/lf-anfrage.css @@ -0,0 +1,762 @@ +/* + * Anfrageformular (ADR-60, Widget „inquiry“): Kompaktformular und mehrstufiger Dialog. Nur Tokens aus tokens.css. + * Der Aufbau kommt zur Laufzeit aus resources/js/inquiry-form.js. + */ +.inquiry { + --inquiry-width: 44rem; + container-type: inline-size; + max-width: var(--inquiry-width); + margin-inline: auto; + color: var(--color-text); +} + +.inquiry [hidden] { + display: none !important; +} + +.inquiry-loading, +.inquiry-note { + margin: 0; + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-small); + background: var(--color-info-surface); + color: var(--color-text); +} + +.inquiry-heading { + margin: 0 0 var(--space-2); +} + +.inquiry-heading:focus, +.inquiry-step-title:focus, +.inquiry-success:focus, +.inquiry-errors:focus { + outline: 3px solid var(--color-focus); + outline-offset: 3px; +} + +.inquiry-intro { + margin: 0 0 var(--space-3); + color: var(--color-text-muted); +} + +.inquiry-legend { + margin: 0 0 var(--space-4); + font-size: 0.9em; + color: var(--color-text-muted); +} + +.inquiry-form { + display: grid; + gap: var(--space-5); +} + +.inquiry-step { + display: grid; + gap: var(--space-4); + margin: 0; + padding: 0; + border: 0; +} + +.inquiry-step-title { + margin: 0; + font-size: 1.2em; +} + +.inquiry-step-intro { + margin: 0; + color: var(--color-text-muted); +} + +.inquiry-group { + display: grid; + gap: var(--space-4); + margin: 0; + padding: var(--space-4) 0 0; + border: 0; + border-top: 1px solid var(--color-border); +} + +.inquiry-group:first-child { + border-top: 0; + padding-top: 0; +} + +.inquiry-group > legend { + padding: 0; + font-weight: 700; + color: var(--color-heading); +} + +.inquiry-field, +.inquiry-fieldset { + display: grid; + gap: var(--space-2); + margin: 0; + padding: 0; + border: 0; + min-width: 0; +} + +.inquiry-label { + font-weight: 600; + padding: 0; +} + +.inquiry-req { + display: none; + color: var(--color-danger); +} + +.inquiry-field.is-required .inquiry-req { + display: inline; +} + +.inquiry-help, +.inquiry-option-desc { + margin: 0; + font-size: 0.92em; + color: var(--color-text-muted); +} + +.inquiry input[type='text'], +.inquiry input[type='email'], +.inquiry input[type='tel'], +.inquiry input[type='date'], +.inquiry select, +.inquiry textarea { + font: inherit; + width: 100%; + min-height: var(--touch-target); + padding: 0.5rem 0.75rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-small); + background: var(--lf-white); + color: var(--lf-ink); + box-sizing: border-box; +} + +.inquiry textarea { + resize: vertical; +} + +.inquiry input:focus-visible, +.inquiry select:focus-visible, +.inquiry textarea:focus-visible, +.inquiry button:focus-visible, +.inquiry a:focus-visible { + outline: 3px solid var(--color-focus); + outline-offset: 2px; +} + +.inquiry-field.is-invalid input:not([type='radio']):not([type='checkbox']), +.inquiry-field.is-invalid select, +.inquiry-field.is-invalid textarea { + border-color: var(--color-danger); + border-width: 2px; +} + +.inquiry-error { + margin: 0; + min-height: 0; + color: var(--color-danger); + font-weight: 600; +} + +.inquiry-error:empty { + display: none; +} + +.inquiry-options { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); + gap: var(--space-2); +} + +/* Anliegen mit Beschreibung: je Zeile eine Option. */ +.inquiry-choice .inquiry-options { + grid-template-columns: 1fr; +} + +.inquiry-option { + display: flex; + align-items: flex-start; + gap: var(--space-3); + min-height: var(--touch-target); + padding: var(--space-2) var(--space-3); + border: 1px solid var(--color-border); + border-radius: var(--radius-small); + background: var(--color-surface); +} + +.inquiry-option:has(input:checked) { + border-color: var(--color-action); + background: var(--color-success-surface); +} + +.inquiry-option input { + flex: none; + width: 1.4rem; + height: 1.4rem; + min-height: 0; + margin-top: 0.15rem; + accent-color: var(--color-action); +} + +.inquiry-option label { + display: grid; + gap: 0.15rem; + flex: 1; + cursor: pointer; +} + +.inquiry-option-label { + font-weight: 600; +} + +.inquiry-period { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-3); +} + +.inquiry-sublabel { + display: block; + margin-bottom: var(--space-1); + font-size: 0.92em; +} + +@container (min-width: 34rem) { + .inquiry-group { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .inquiry-group > legend, + .inquiry-group > .inquiry-help, + .inquiry-group .inquiry-field[data-type='textarea'], + .inquiry-group .inquiry-field[data-type='select'], + .inquiry-group .inquiry-field[data-type='boolean'], + .inquiry-group .inquiry-field[data-type='multiselect'], + .inquiry-group .inquiry-field[data-type='period'] { + grid-column: 1 / -1; + } +} + +.inquiry-progress { + display: flex; + gap: var(--space-2); + flex-wrap: wrap; + margin: 0; + padding: 0; + list-style: none; + counter-reset: none; +} + +.inquiry-progress-item { + display: inline-flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-1) var(--space-3) var(--space-1) var(--space-1); + border: 1px solid var(--color-border); + border-radius: var(--radius-pill); + color: var(--color-text-muted); + font-size: 0.92em; +} + +.inquiry-progress-nr { + display: inline-grid; + place-items: center; + width: 1.6rem; + height: 1.6rem; + border-radius: 50%; + background: var(--color-surface-subtle); + font-weight: 700; +} + +.inquiry-progress-item.is-current { + border-color: var(--color-action); + color: var(--color-heading); + font-weight: 700; +} + +.inquiry-progress-item.is-current .inquiry-progress-nr { + background: var(--color-action); + color: var(--color-action-text); +} + +.inquiry-progress-item.is-done .inquiry-progress-nr::after { + content: '✓'; +} + +.inquiry-progress-item.is-done .inquiry-progress-nr { + font-size: 0; +} + +.inquiry-progress-item.is-done .inquiry-progress-nr::after { + font-size: 1rem; +} + +@container (max-width: 33rem) { + .inquiry-progress-item:not(.is-current) .inquiry-progress-title { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } +} + +.inquiry-actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.inquiry-actions .button { + min-height: var(--touch-target); +} + +.inquiry-privacy { + margin: 0; + font-size: 0.92em; + color: var(--color-text-muted); +} + +.inquiry-errors { + padding: var(--space-3) var(--space-4); + border: 2px solid var(--color-danger); + border-radius: var(--radius-small); + background: var(--color-danger-surface); +} + +.inquiry-errors-title { + margin: 0 0 var(--space-2); + font-weight: 700; +} + +.inquiry-errors ul { + margin: 0; + padding-left: 1.2rem; +} + +.inquiry-errors a { + color: var(--color-danger); +} + +.inquiry-summary-list { + display: grid; + gap: var(--space-2); + margin: 0; +} + +.inquiry-summary-step { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-3); + margin-top: var(--space-3); + padding-bottom: var(--space-1); + border-bottom: 1px solid var(--color-border); +} + +.inquiry-summary-step dt { + font-weight: 700; + color: var(--color-heading); +} + +.inquiry-summary-step dd, +.inquiry-summary-row dd { + margin: 0; +} + +.inquiry-summary-row { + display: grid; + grid-template-columns: minmax(8rem, 14rem) 1fr; + gap: var(--space-3); +} + +.inquiry-summary-row dt { + color: var(--color-text-muted); +} + +.inquiry-summary-row dd { + white-space: pre-line; + overflow-wrap: anywhere; +} + +@container (max-width: 30rem) { + .inquiry-summary-row { + grid-template-columns: 1fr; + gap: 0; + } +} + +.inquiry-link { + min-height: var(--touch-target); + padding: 0 var(--space-2); + border: 0; + background: none; + color: var(--color-link); + font: inherit; + font-weight: 600; + text-decoration: underline; + cursor: pointer; +} + +.inquiry-success { + padding: var(--space-5); + border: 2px solid var(--color-success); + border-radius: var(--radius-small); + background: var(--color-success-surface); +} + +.inquiry-success h3 { + margin-top: 0; +} + +.inquiry-reference { + margin-bottom: 0; +} + +/* Köderfeld gegen Automaten: für Menschen und Hilfstechnik unsichtbar. */ +.inquiry-hp { + position: absolute; + left: -10000px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.inquiry-sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.inquiry-opener { + margin-bottom: var(--space-3); +} + +@media (prefers-reduced-motion: reduce) { + .inquiry * { + scroll-behavior: auto !important; + 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; +} diff --git a/resources/js/app.js b/resources/js/app.js index 66bb9d5..37ee7ee 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -3,6 +3,8 @@ import './site-nav.js'; 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-embed.js b/resources/js/inquiry-embed.js new file mode 100644 index 0000000..7786fe9 --- /dev/null +++ b/resources/js/inquiry-embed.js @@ -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'; diff --git a/resources/js/inquiry-form.js b/resources/js/inquiry-form.js new file mode 100644 index 0000000..eab963f --- /dev/null +++ b/resources/js/inquiry-form.js @@ -0,0 +1,955 @@ +/* + * Anfrageformular (ADR-60). Das Formular wird aus der Beschreibung gebaut, die der Server liefert (Texte, Schritte, Felder, + * Auswahlwerte). Welche Fragen sichtbar oder Pflicht sind, entscheidet allein der Server: nach jeder Änderung einer + * steuernden Auswahl wird der Zustand abgefragt. Kompaktformular und mehrstufiger Dialog sind nur zwei Darstellungen + * derselben Beschreibung. Eingaben ausgeblendeter Fragen bleiben im Browser erhalten, werden aber nie gesendet. + */ + +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; +} + +const REQUIRED_MESSAGE = 'Bitte füllen Sie dieses Feld aus.'; + +class InquiryForm { + constructor(root) { + this.root = root; + this.id = 'inq' + ++counter; + this.preview = root.dataset.preview === '1'; + this.values = {}; + this.touched = new Set(); + this.state = null; + this.def = null; + this.current = 0; + this.sequence = 0; + this.pending = Promise.resolve(); + this.submitting = false; + this.finished = false; + } + + async start() { + try { + 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; + + return; + } + + this.def = await response.json(); + } catch { + this.root.replaceChildren(h('p', { class: 'inquiry-note', role: 'alert', text: 'Das Anfrageformular konnte nicht geladen werden. Bitte laden Sie die Seite neu.' })); + + return; + } + + this.token = this.def.token; + this.csrf = this.def.csrf; + this.state = this.def.state; + this.values = { ...(this.def.defaults || {}) }; + this.wizard = this.def.mode === 'wizard'; + this.render(); + } + + /* ------------------------------------------------------------------ Aufbau */ + + render() { + const def = this.def; + const open = def.open === 'button'; + + this.panel = h('div', { class: 'inquiry-panel', id: this.id + '-panel', hidden: open }); + this.status = h('p', { class: 'inquiry-sr', 'aria-live': 'polite', role: 'status' }); + this.formEl = h('form', { class: 'inquiry-form', novalidate: true, 'aria-labelledby': this.id + '-heading', onsubmit: (event) => event.preventDefault() }); + + this.heading = h('h2', { class: 'inquiry-heading', id: this.id + '-heading', tabindex: '-1', text: def.texts.heading }); + const intro = def.texts.intro ? h('p', { class: 'inquiry-intro', text: def.texts.intro }) : null; + + this.progress = this.wizard ? h('ol', { class: 'inquiry-progress', 'aria-label': 'Fortschritt' }) : null; + this.summaryBox = h('div', { class: 'inquiry-errors', role: 'alert', tabindex: '-1', hidden: true }); + this.stepEls = new Map(); + this.fieldEls = new Map(); + this.groupEls = new Map(); + + const steps = def.steps.map((step) => this.buildStep(step)); + this.summaryEl = this.wizard ? this.buildSummary() : null; + this.actions = h('div', { class: 'inquiry-actions' }); + this.privacy = def.texts.privacy_note ? h('p', { class: 'inquiry-privacy', text: def.texts.privacy_note }) : null; + this.honeypot = h('div', { class: 'inquiry-hp', 'aria-hidden': 'true' }, h('label', {}, 'Bitte leer lassen', h('input', { type: 'text', name: 'inq_hp', tabindex: '-1', autocomplete: 'off' }))); + + this.formEl.append( + ...[this.progress, this.summaryBox, ...steps, this.summaryEl, this.privacy, this.honeypot, this.actions].filter(Boolean), + ); + this.panel.append(...[this.heading, intro, h('p', { class: 'inquiry-legend', text: 'Mit * markierte Angaben sind Pflichtangaben.' }), this.formEl, this.status].filter(Boolean)); + + this.root.replaceChildren(); + + if (open) { + this.opener = h('button', { + type: 'button', + class: 'button inquiry-opener', + 'aria-expanded': 'false', + 'aria-controls': this.id + '-panel', + text: def.texts.open_label, + onclick: () => this.openPanel(), + }); + this.root.append(this.opener); + } + + this.root.append(this.panel); + + this.syncValues(); + this.applyState(); + this.renderActions(); + } + + openPanel() { + this.panel.hidden = false; + this.opener.setAttribute('aria-expanded', 'true'); + this.opener.hidden = true; + this.heading.focus(); + } + + buildStep(step) { + const el = h('section', { class: 'inquiry-step', 'data-step': step.key, 'aria-labelledby': this.id + '-s-' + step.key }); + const showTitle = this.wizard || this.def.steps.length > 1; + el.append(h('h3', { class: 'inquiry-step-title', id: this.id + '-s-' + step.key, tabindex: '-1', text: step.title, hidden: !showTitle })); + + if (step.intro) { + el.append(h('p', { class: 'inquiry-step-intro', text: step.intro })); + } + + for (const item of step.items) { + if (item.kind === 'issue') { + el.append(this.buildIssues()); + } else { + el.append(this.buildGroup(item)); + } + } + + this.stepEls.set(step.key, el); + + return el; + } + + buildGroup(group) { + const el = h(group.label ? 'fieldset' : 'div', { class: 'inquiry-group', 'data-group': group.key || null }); + + if (group.label) { + el.append(h('legend', { text: group.label })); + } + + if (group.description) { + el.append(h('p', { class: 'inquiry-help', text: group.description })); + } + + for (const row of group.fields) { + el.append(this.buildField(this.def.fields[row.field])); + } + + if (group.key) { + this.groupEls.set(group.key, el); + } + + return el; + } + + buildIssues() { + const wrap = h('div', { class: 'inquiry-issues' }); + this.issueEl = this.choiceField('anliegen', this.def.texts.issue_question, this.def.issues.map((issue) => ({ key: issue.key, label: issue.label, description: issue.description }))); + this.subissueEl = h('div', { class: 'inquiry-field', 'data-field': 'unteranliegen', hidden: true }); + this.fieldEls.set('unteranliegen', this.subissueEl); + wrap.append(this.issueEl, this.subissueEl); + + return wrap; + } + + /** Auswahl des Anliegens: große Optionen mit Beschreibung. */ + choiceField(key, legend, options) { + const el = h('fieldset', { class: 'inquiry-field inquiry-choice', 'data-field': key }); + el.append(h('legend', {}, legend, h('span', { class: 'inquiry-req', 'aria-hidden': 'true', text: ' *' }))); + const list = h('div', { class: 'inquiry-options' }); + + for (const option of options) { + const id = `${this.id}-${key}-${option.key}`; + const input = h('input', { type: 'radio', name: `${this.id}-${key}`, id, value: option.key, onchange: () => this.onIssueChange(key, option.key) }); + input.checked = this.values[key] === option.key; + list.append(h('div', { class: 'inquiry-option' }, input, h('label', { for: id }, h('span', { class: 'inquiry-option-label', text: option.label }), option.description ? h('span', { class: 'inquiry-option-desc', text: option.description }) : null))); + } + + el.append(list, h('p', { class: 'inquiry-error', id: `${this.id}-${key}-err`, 'aria-live': 'polite' })); + this.fieldEls.set(key, el); + + return el; + } + + renderSubissues() { + const parent = this.def.issues.find((issue) => issue.key === this.state.issue); + const children = parent ? parent.children : []; + + if (!children.some((child) => child.key === this.values.unteranliegen)) { + delete this.values.unteranliegen; + } + + const fresh = this.choiceField('unteranliegen', 'Worum geht es genauer?', children.map((child) => ({ key: child.key, label: child.label, description: child.description }))); + this.subissueEl.replaceWith(fresh); + this.subissueEl = fresh; + } + + buildField(field) { + const id = `${this.id}-${field.key}`; + const wrap = h('div', { class: 'inquiry-field', 'data-field': field.key, 'data-type': field.type }); + const describedBy = [field.help ? id + '-help' : null, id + '-err'].filter(Boolean).join(' '); + const requiredMark = () => h('span', { class: 'inquiry-req', 'aria-hidden': 'true', text: ' *' }); + const label = (text, forId) => h('label', { for: forId, class: 'inquiry-label' }, text, requiredMark()); + const legend = (text) => h('legend', { class: 'inquiry-label' }, text, requiredMark()); + const help = field.help ? h('p', { class: 'inquiry-help', id: id + '-help', text: field.help }) : null; + const error = h('p', { class: 'inquiry-error', id: id + '-err', 'aria-live': 'polite' }); + const control = (input) => { + input.addEventListener('input', () => this.onInput(field, input)); + input.addEventListener('change', () => this.onInput(field, input)); + + return input; + }; + const value = this.values[field.key]; + const options = field.type === 'boolean' ? [{ key: 'ja', label: 'Ja' }, { key: 'nein', label: 'Nein' }] : field.options || []; + const dropdown = field.type === 'select' && options.length > 6; + const grouped = ['boolean', 'multiselect', 'period'].includes(field.type) || (field.type === 'select' && !dropdown); + const box = grouped ? h('fieldset', { class: 'inquiry-fieldset' }) : wrap; + const choice = (kind, option) => { + const oid = `${id}-${option.key}`; + const input = control(h('input', { type: kind, id: oid, value: option.key, name: kind === 'radio' ? id : null, 'aria-describedby': describedBy })); + input.checked = kind === 'radio' ? value === option.key : Array.isArray(value) && value.includes(option.key); + + return h('div', { class: 'inquiry-option' }, input, h('label', { for: oid }, h('span', { class: 'inquiry-option-label', text: option.label }))); + }; + let parts; + + if (field.type === 'textarea') { + parts = [label(field.label, id), help, control(h('textarea', { id, name: field.key, rows: 5, maxlength: field.max_length || 4000, 'aria-describedby': describedBy }, value || '')), error]; + } else if (dropdown) { + const select = h('select', { id, name: field.key, 'aria-describedby': describedBy }, h('option', { value: '', text: 'Bitte wählen' }), options.map((option) => h('option', { value: option.key, text: option.label }))); + select.value = value || ''; + parts = [label(field.label, id), help, control(select), error]; + } else if (field.type === 'select' || field.type === 'boolean') { + parts = [legend(field.label), help, h('div', { class: 'inquiry-options' }, options.map((option) => choice('radio', option))), error]; + } else if (field.type === 'multiselect') { + parts = [legend(field.label), help, h('div', { class: 'inquiry-options' }, options.map((option) => choice('checkbox', option))), error]; + } else if (field.type === 'period') { + const range = value || {}; + const part = (name, text) => h('div', {}, h('label', { for: `${id}-${name}`, class: 'inquiry-sublabel', text }), control(h('input', { type: 'date', id: `${id}-${name}`, 'data-part': name, value: range[name] || '', 'aria-describedby': describedBy }))); + parts = [legend(field.label), help, h('div', { class: 'inquiry-period' }, part('von', 'Von'), part('bis', 'Bis')), error]; + } else { + const attrs = { id, name: field.key, type: { email: 'email', phone: 'tel', date: 'date' }[field.type] || 'text', value: value || '', 'aria-describedby': describedBy }; + + if (field.type === 'email') { + attrs.autocomplete = 'email'; + attrs.inputmode = 'email'; + } else if (field.type === 'phone') { + attrs.autocomplete = 'tel'; + } else if (field.type === 'number') { + attrs.inputmode = 'decimal'; + } else if (field.type === 'text') { + attrs.maxlength = field.max_length || 200; + } + + parts = [label(field.label, id), help, control(h('input', attrs)), error]; + } + + if (grouped) { + wrap.append(box); + } + + box.append(...parts.filter(Boolean)); + this.fieldEls.set(field.key, wrap); + + return wrap; + } + + buildSummary() { + this.summaryList = h('dl', { class: 'inquiry-summary-list' }); + + return h('section', { class: 'inquiry-step inquiry-summary', 'data-step': '_summary', 'aria-labelledby': this.id + '-sum', hidden: true }, + h('h3', { class: 'inquiry-step-title', id: this.id + '-sum', tabindex: '-1', text: this.def.texts.summary_title }), + this.summaryList, + ); + } + + /* ------------------------------------------------------------------ Eingaben */ + + onIssueChange(key, value) { + this.values[key] = value; + this.touched.add(key); + + if (key === 'anliegen') { + delete this.values.unteranliegen; + } + + this.refresh(); + } + + onInput(field, input) { + const type = field.type; + const wrap = this.fieldEls.get(field.key); + + if (type === 'multiselect') { + this.values[field.key] = [...wrap.querySelectorAll('input[type=checkbox]:checked')].map((box) => box.value); + } else if (type === 'period') { + this.values[field.key] = { von: wrap.querySelector('[data-part=von]').value, bis: wrap.querySelector('[data-part=bis]').value }; + } else if (input.type === 'radio') { + this.values[field.key] = input.value; + } else { + this.values[field.key] = input.value; + } + + this.touched.add(field.key); + this.setError(field.key, ''); + + if ((this.def.controls || []).includes(field.key)) { + this.refresh(); + } + } + + /** Überträgt die Werte in die Steuerelemente (nach Vorbelegung durch den Server). */ + syncValues() { + for (const [key, el] of this.fieldEls) { + const value = this.values[key]; + + if (key === 'anliegen' || key === 'unteranliegen') { + el.querySelectorAll('input[type=radio]').forEach((radio) => { radio.checked = radio.value === value; }); + continue; + } + + const field = this.def.fields[key]; + if (!field) { + continue; + } + + if (field.type === 'multiselect') { + el.querySelectorAll('input[type=checkbox]').forEach((box) => { box.checked = Array.isArray(value) && value.includes(box.value); }); + } else if (field.type === 'period') { + el.querySelector('[data-part=von]').value = value?.von || ''; + el.querySelector('[data-part=bis]').value = value?.bis || ''; + } else if (field.type === 'select' || field.type === 'boolean') { + const radios = el.querySelectorAll('input[type=radio]'); + if (radios.length) { + radios.forEach((radio) => { radio.checked = radio.value === value; }); + } else { + el.querySelector('select').value = value || ''; + } + } else { + el.querySelector('input, textarea').value = value || ''; + } + } + } + + /* ------------------------------------------------------------------ Zustand */ + + refresh() { + const run = ++this.sequence; + this.root.setAttribute('aria-busy', 'true'); + this.pending = this.pending.then(async () => { + try { + if (run !== this.sequence) { + return; + } + + const response = await fetch(this.root.dataset.stateUrl, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.csrf }, + body: JSON.stringify({ values: this.allValues() }), + }); + + if (!response.ok || run !== this.sequence) { + return; + } + + const before = this.visibleKeys(); + this.state = await response.json(); + this.applyPresets(); + this.applyState(); + this.announce(before); + } catch { + // Der letzte bekannte Zustand bleibt; beim Absenden prüft der Server ohnehin alles. + } finally { + if (run === this.sequence) { + this.root.removeAttribute('aria-busy'); + } + } + }); + + return this.pending; + } + + applyPresets() { + let changed = false; + + for (const [key, value] of Object.entries(this.state.presets || {})) { + if (!this.touched.has(key) && (this.values[key] === undefined || this.values[key] === '') && this.values[key] !== value) { + this.values[key] = value; + changed = true; + } + } + + if (changed) { + this.syncValues(); + this.refresh(); + } + } + + visibleKeys() { + return Object.entries(this.state?.fields || {}).filter(([, visible]) => visible).map(([key]) => key); + } + + announce(before) { + const now = this.visibleKeys(); + const added = now.filter((key) => !before.includes(key)); + const removed = before.filter((key) => !now.includes(key)); + + if (added.length) { + this.status.textContent = 'Weitere Fragen wurden eingeblendet.'; + } else if (removed.length) { + this.status.textContent = 'Einige Fragen sind entfallen.'; + } + } + + /** Alle erfassten Werte für die Abfrage des Zustands; der Server entscheidet, welche davon zählen. */ + allValues() { + const out = {}; + + for (const [key, value] of Object.entries(this.values)) { + if (value !== undefined && value !== '') { + out[key] = value; + } + } + + return out; + } + + /** Nur Werte sichtbarer Fragen: Das Gesendete entspricht dem, was der Besucher sieht. */ + visibleValues() { + const out = {}; + + for (const [key, value] of Object.entries(this.values)) { + if (this.state?.fields?.[key] && value !== undefined && value !== '') { + out[key] = value; + } + } + + return out; + } + + applyState() { + const state = this.state; + + if (this.issueEl && (this.subissueEl.dataset.parent === undefined || this.subissueEl.dataset.parent !== (state.issue || ''))) { + this.renderSubissues(); + this.subissueEl.dataset.parent = state.issue || ''; + } + + for (const [key, el] of this.groupEls) { + el.hidden = state.groups[key] === false; + } + + for (const [key, el] of this.fieldEls) { + const visible = !!state.fields[key]; + el.hidden = !visible; + el.classList.toggle('is-required', !!state.required[key]); + el.querySelectorAll('input, select, textarea').forEach((input) => { + input.disabled = !visible; + + if (state.required[key]) { + input.setAttribute('aria-required', 'true'); + } else { + input.removeAttribute('aria-required'); + } + }); + } + + this.syncSteps(); + } + + /* ------------------------------------------------------------------ Schritte */ + + stepHasContent(step) { + if (!this.state.steps[step.key]) { + return false; + } + + return step.items.some((item) => (item.kind === 'issue' + ? this.state.fields.anliegen || this.state.fields.unteranliegen + : item.fields.some((row) => this.state.fields[row.field]))); + } + + visibleSteps() { + return this.def.steps.filter((step) => this.stepHasContent(step)); + } + + /** Anzeige der Schritte: im Dialog nur der aktuelle, im Kompaktformular alle sichtbaren. */ + syncSteps() { + const steps = this.visibleSteps(); + + if (!this.wizard) { + for (const step of this.def.steps) { + this.stepEls.get(step.key).hidden = !steps.includes(step); + } + + this.renderActions(); + + return; + } + + const total = steps.length + 1; + this.current = Math.max(0, Math.min(this.current, total - 1)); + const onSummary = this.current === steps.length; + + for (const step of this.def.steps) { + this.stepEls.get(step.key).hidden = onSummary || steps[this.current] !== step; + } + + this.summaryEl.hidden = !onSummary; + this.progress.replaceChildren(...[...steps.map((step) => step.title), this.def.texts.summary_title].map((title, index) => h('li', { + class: 'inquiry-progress-item' + (index === this.current ? ' is-current' : '') + (index < this.current ? ' is-done' : ''), + 'aria-current': index === this.current ? 'step' : null, + }, h('span', { class: 'inquiry-progress-nr', text: String(index + 1) }), h('span', { class: 'inquiry-progress-title', text: title })))); + + if (onSummary) { + this.fillSummary(steps); + } + + this.renderActions(); + } + + goTo(index, focusHeading = true) { + this.current = index; + this.syncSteps(); + + if (focusHeading) { + const steps = this.visibleSteps(); + const target = this.current === steps.length ? this.summaryEl.querySelector('h3') : this.stepEls.get(steps[this.current].key).querySelector('h3'); + target.focus({ preventScroll: false }); + target.scrollIntoView({ block: 'start', behavior: 'smooth' }); + } + } + + renderActions() { + const texts = this.def.texts; + this.actions.replaceChildren(); + + if (!this.wizard) { + this.actions.append(this.submitButton()); + + return; + } + + const steps = this.visibleSteps(); + const last = this.current >= steps.length; + + if (this.current > 0) { + this.actions.append(h('button', { type: 'button', class: 'button button-secondary', text: texts.back_label, onclick: () => this.goTo(this.current - 1) })); + } + + this.actions.append(last ? this.submitButton() : h('button', { type: 'button', class: 'button', text: texts.next_label, onclick: () => this.next() })); + } + + submitButton() { + this.submitEl = h('button', { type: 'button', class: 'button', text: this.def.texts.submit_label, onclick: () => this.submit() }); + + return this.submitEl; + } + + async next() { + await this.pending; + const steps = this.visibleSteps(); + const errors = this.validateStep(steps[this.current]); + + if (errors.length) { + this.showErrors(errors); + + return; + } + + this.hideSummary(); + this.goTo(this.current + 1); + } + + fillSummary(steps) { + const rows = []; + + for (const step of steps) { + const index = steps.indexOf(step); + + for (const item of step.items) { + const entries = item.kind === 'issue' + ? this.issueRows() + : item.fields.filter((row) => this.state.fields[row.field]).map((row) => this.fieldRow(this.def.fields[row.field])); + + for (const entry of entries.filter(Boolean)) { + rows.push({ ...entry, index, step }); + } + } + } + + this.summaryList.replaceChildren(); + let last = null; + + for (const row of rows) { + if (last !== row.step) { + this.summaryList.append(h('div', { class: 'inquiry-summary-step' }, h('dt', { class: 'inquiry-summary-heading', text: row.step.title }), h('dd', {}, h('button', { type: 'button', class: 'inquiry-link', text: this.def.texts.edit_label, 'aria-label': `${this.def.texts.edit_label}: ${row.step.title}`, onclick: () => this.goTo(row.index) })))); + last = row.step; + } + + this.summaryList.append(h('div', { class: 'inquiry-summary-row' }, h('dt', { text: row.label }), h('dd', { text: row.text }))); + } + + if (!rows.length) { + this.summaryList.append(h('p', { text: 'Sie haben noch keine Angaben gemacht.' })); + } + } + + issueRows() { + const rows = []; + const parent = this.def.issues.find((issue) => issue.key === this.state.issue); + + if (parent && this.state.fields.anliegen) { + rows.push({ label: 'Anliegen', text: parent.label }); + } + + const child = parent?.children.find((item) => item.key === this.state.subissue); + + if (child && this.state.fields.unteranliegen) { + rows.push({ label: 'Genauer', text: child.label }); + } + + return rows; + } + + fieldRow(field) { + const text = this.displayValue(field, this.values[field.key]); + + return text === '' ? null : { label: field.label, text }; + } + + displayValue(field, value) { + if (value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)) { + return ''; + } + + const label = (key) => (field.options || []).find((option) => option.key === key)?.label || key; + const date = (iso) => iso ? iso.split('-').reverse().join('.') : ''; + + switch (field.type) { + case 'select': return label(value); + case 'multiselect': return value.map(label).join(', '); + case 'boolean': return value === 'ja' ? 'Ja' : 'Nein'; + case 'date': return date(value); + case 'period': return [date(value.von), date(value.bis)].filter(Boolean).join(' bis '); + default: return String(value); + } + } + + /* ------------------------------------------------------------------ Prüfung und Senden */ + + /** Prüfung der Pflichtangaben zur Bedienung; maßgeblich ist die Prüfung des Servers. */ + validateStep(step) { + const errors = []; + const keys = []; + + for (const item of step.items) { + if (item.kind === 'issue') { + keys.push('anliegen', 'unteranliegen'); + } else { + item.fields.forEach((row) => keys.push(row.field)); + } + } + + for (const key of keys) { + if (!this.state.fields[key]) { + continue; + } + + const message = this.checkField(key); + + this.setError(key, message); + + if (message) { + errors.push({ key, message, label: this.labelOf(key) }); + } + } + + return errors; + } + + labelOf(key) { + if (key === 'anliegen') { + return this.def.texts.issue_question; + } + + return key === 'unteranliegen' ? 'Worum geht es genauer?' : this.def.fields[key]?.label || key; + } + + checkField(key) { + const value = this.values[key]; + const empty = value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length) + || (typeof value === 'object' && !Array.isArray(value) && !value.von && !value.bis); + + if (empty) { + return this.state.required[key] ? (key === 'anliegen' || key === 'unteranliegen' ? 'Bitte treffen Sie eine Auswahl.' : REQUIRED_MESSAGE) : ''; + } + + const field = this.def.fields[key]; + + if (field?.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value))) { + return 'Bitte geben Sie eine gültige E-Mail-Adresse ein.'; + } + + if (field?.type === 'period' && this.state.required[key] && !(value.von && value.bis)) { + return 'Bitte geben Sie Beginn und Ende an.'; + } + + return ''; + } + + setError(key, message) { + const wrap = this.fieldEls.get(key); + + if (!wrap) { + return; + } + + wrap.classList.toggle('is-invalid', !!message); + wrap.querySelectorAll('input, select, textarea').forEach((input) => { + if (message) { + input.setAttribute('aria-invalid', 'true'); + } else { + input.removeAttribute('aria-invalid'); + } + }); + const slot = wrap.querySelector('.inquiry-error'); + + if (slot) { + slot.textContent = message; + } + } + + hideSummary() { + this.summaryBox.hidden = true; + this.summaryBox.replaceChildren(); + } + + showErrors(errors, intro = 'Bitte prüfen Sie Ihre Angaben:') { + const list = h('ul', {}, errors.map((error) => h('li', {}, h('a', { href: '#', text: `${error.label}: ${error.message}`, onclick: (event) => { event.preventDefault(); this.focusField(error.key); } })))); + this.summaryBox.replaceChildren(h('p', { class: 'inquiry-errors-title', text: intro }), list); + this.summaryBox.hidden = false; + this.summaryBox.focus(); + this.summaryBox.scrollIntoView({ block: 'center', behavior: 'smooth' }); + } + + focusField(key) { + const wrap = this.fieldEls.get(key); + const input = wrap?.querySelector('input:not([disabled]), select, textarea'); + + if (input) { + input.focus(); + } + } + + async submit() { + if (this.submitting || this.finished) { + return; + } + + await this.pending; + const steps = this.visibleSteps(); + const errors = steps.flatMap((step) => this.validateStep(step)); + + if (errors.length) { + if (this.wizard) { + const first = steps.findIndex((step) => this.validateStep(step).length); + this.goTo(first, false); + this.validateStep(steps[first]); + } + + this.showErrors(errors); + + return; + } + + this.hideSummary(); + + if (this.preview) { + this.success('Vorschau'); + + return; + } + + this.submitting = true; + this.submitEl.disabled = true; + this.submitEl.setAttribute('aria-busy', 'true'); + this.formEl.setAttribute('aria-busy', 'true'); + + try { + const response = await this.post(); + const data = await response.json().catch(() => ({})); + + if (response.status === 201) { + this.success(data.reference); + + return; + } + + this.failure(response.status, data); + } catch { + this.failure(0, {}); + } finally { + this.submitting = false; + this.formEl.removeAttribute('aria-busy'); + + if (this.submitEl && !this.finished) { + this.submitEl.disabled = false; + this.submitEl.removeAttribute('aria-busy'); + } + } + } + + async post(retry = true) { + const response = await fetch(this.root.dataset.submitUrl, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.csrf }, + body: JSON.stringify({ + values: this.visibleValues(), + token: this.token, + website: this.honeypot.querySelector('input').value, + source: location.pathname, + }), + }); + + // Abgelaufenes Formular oder Sitzung: neues Token holen und einmal erneut senden. Die Eingaben bleiben erhalten. + if (response.status === 419 && retry) { + const fresh = await fetch(this.root.dataset.definitionUrl, { headers: { Accept: 'application/json' }, credentials: 'same-origin' }); + + if (fresh.ok) { + const data = await fresh.json(); + this.token = data.token; + this.csrf = data.csrf; + + return this.post(false); + } + } + + return response; + } + + failure(status, data) { + const fields = data.fields || {}; + const errors = Object.entries(fields).map(([key, message]) => ({ key, message, label: this.labelOf(key) })); + + if (errors.length) { + errors.forEach((error) => this.setError(error.key, error.message)); + + if (this.wizard) { + const steps = this.visibleSteps(); + const first = steps.findIndex((step) => step.items.some((item) => (item.kind === 'issue' ? errors.some((e) => e.key.endsWith('anliegen')) : item.fields.some((row) => fields[row.field])))); + this.goTo(first === -1 ? 0 : first, false); + } + + this.showErrors(errors); + + return; + } + + let message; + + if (status === 429 && data.fields === undefined) { + message = 'Es wurden in kurzer Zeit zu viele Anfragen gesendet. Bitte warten Sie einen Moment und versuchen Sie es dann noch einmal.'; + } else if ([410, 419, 422, 429].includes(status) && data.message) { + message = data.message; + } else { + message = this.def.texts.error_text; + } + + this.showMessage(message); + } + + showMessage(text) { + this.summaryBox.replaceChildren(h('p', { class: 'inquiry-errors-title', text })); + this.summaryBox.hidden = false; + this.summaryBox.focus(); + this.summaryBox.scrollIntoView({ block: 'center', behavior: 'smooth' }); + } + + 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 }), + h('p', { text: this.def.texts.success_text }), + preview + ? h('p', { class: 'inquiry-note', text: 'Vorschau: Es wurde nichts gesendet.' }) + : h('p', { class: 'inquiry-reference' }, 'Ihr Kennzeichen: ', h('strong', { text: reference })), + ); + + this.formEl.replaceWith(box); + this.heading.hidden = false; + box.focus(); + box.scrollIntoView({ block: 'center', behavior: 'smooth' }); + } +} + +export function initInquiryForms(root = document) { + root.querySelectorAll('[data-inquiry]').forEach((el) => { + if (el.dataset.inquiryReady === '1') { + return; + } + + el.dataset.inquiryReady = '1'; + new InquiryForm(el).start(); + }); +} + +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', () => initInquiryForms()); +} else { + initInquiryForms(); +} diff --git a/resources/js/inquiry-widget.js b/resources/js/inquiry-widget.js new file mode 100644 index 0000000..c38b0d6 --- /dev/null +++ b/resources/js/inquiry-widget.js @@ -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(); +} diff --git a/resources/views/communication/preview.blade.php b/resources/views/communication/preview.blade.php new file mode 100644 index 0000000..8459840 --- /dev/null +++ b/resources/views/communication/preview.blade.php @@ -0,0 +1,31 @@ +@extends('layouts.site') + +@section('title', $title) +@section('main_class', 'site-main') + +@push('head') + +@endpush + +@section('content') +

+ {{ $note }} + @if ($switchUrl) + Als {{ $mode === 'wizard' ? 'Kompaktformular' : 'mehrstufigen Dialog' }} ansehen + @endif +

+
+ @if ($errors !== []) + + @else + + @endif +
+@endsection diff --git a/resources/views/components/inquiry/mount.blade.php b/resources/views/components/inquiry/mount.blade.php new file mode 100644 index 0000000..145ea26 --- /dev/null +++ b/resources/views/components/inquiry/mount.blade.php @@ -0,0 +1,11 @@ +@props(['definitionUrl', 'stateUrl', 'submitUrl' => null, 'preview' => false, 'label' => null]) +{{-- Einhängepunkt des Anfrageformulars. Das Formular selbst, die Bedingungen und das Token kommen zur Laufzeit vom Server + (resources/js/inquiry-form.js); die gespeicherte Seite enthält nichts davon. --}} +
+

{{ $label ? 'Anfrageformular „'.$label.'“ wird geladen …' : 'Das Anfrageformular wird geladen …' }}

+ +
diff --git a/resources/views/filament/communication/answers.blade.php b/resources/views/filament/communication/answers.blade.php new file mode 100644 index 0000000..cb33a06 --- /dev/null +++ b/resources/views/filament/communication/answers.blade.php @@ -0,0 +1,27 @@ +@php + /** @var \App\Domain\Communication\Inquiry $record */ + $record = $getRecord(); + $answers = collect($record->answers ?? []); + $steps = $answers->groupBy(fn ($answer) => $answer['step'] ?? ''); +@endphp +@if ($answers->isEmpty()) +

Es wurden keine Antworten gespeichert.

+@else +
+ @foreach ($steps as $step => $stepAnswers) + @foreach ($stepAnswers->groupBy(fn ($answer) => $answer['group'] ?? '') as $group => $groupAnswers) +
+ @if ($group !== '' || $step !== '') +

{{ $step }}@if ($group !== '' && $group !== null) · {{ $group }}@endif

+ @endif +
+ @foreach ($groupAnswers as $answer) +
{{ $answer['label'] }}
+
{{ $answer['display'] }}
+ @endforeach +
+
+ @endforeach + @endforeach +
+@endif diff --git a/resources/views/filament/communication/form-editor-feld.blade.php b/resources/views/filament/communication/form-editor-feld.blade.php new file mode 100644 index 0000000..3179c5b --- /dev/null +++ b/resources/views/filament/communication/form-editor-feld.blade.php @@ -0,0 +1,55 @@ +{{-- Zeile eines Feldes in der Formularansicht. $f ist der Name der Alpine-Variable (item oder inner). --}} +
+ + + + + + + + + + + + + + + +
+

+ @include('filament.verwaltung.icon', ['name' => 'verzweigung']) + +

+

+ @include('filament.verwaltung.icon', ['name' => 'info']) + Auch verwendet in: +

diff --git a/resources/views/filament/communication/form-editor-script.blade.php b/resources/views/filament/communication/form-editor-script.blade.php new file mode 100644 index 0000000..cb07de7 --- /dev/null +++ b/resources/views/filament/communication/form-editor-script.blade.php @@ -0,0 +1,828 @@ +@verbatim + +@endverbatim diff --git a/resources/views/filament/communication/form-editor.blade.php b/resources/views/filament/communication/form-editor.blade.php new file mode 100644 index 0000000..4f0c628 --- /dev/null +++ b/resources/views/filament/communication/form-editor.blade.php @@ -0,0 +1,396 @@ +{{-- + Formularansicht des Aufbaus (ADR-62): Bereiche, Teilbereiche und Felder als Baum, im Browser bearbeitet und beim Speichern + als Text (editor_json) übergeben. Logik: form-editor-script.blade.php. Gestaltung: verwaltung/styles.blade.php (vw-fe-…). +--}} +@php + $statePath = $getStatePath(); +@endphp +@once + @include('filament.communication.form-editor-script') +@endonce + +
+ @if ($errors->has($statePath)) + + @endif + +
+
+

+ @include('filament.verwaltung.icon', ['name' => 'info']) + Ziehe Bereiche, Teilbereiche und Felder am Griff an eine beliebige Stelle. Mit der Tastatur: Griff wählen, dann Pfeil hoch oder runter. +

+
+ + +
+
+ +

+ (rot umrandet). Speichern ist erst danach möglich. +

+ +

+ +
+ +
+ +
+

Das Formular hat noch keinen Bereich. Im mehrstufigen Dialog ist jeder Bereich ein Schritt, im langen Formular stehen alle Bereiche untereinander.

+
+ +
+ +
+ + {{-- Ein Dialog für Hilfetext, Auswahlwerte, Bedingung, Einstellungen und Katalog --}} + +
+
+

+ +
+ +
+ {{-- Text: Hilfetext, Einleitung, Erläuterung --}} + + + {{-- Auswahlwerte --}} + + + {{-- Bedingung --}} + + + {{-- Anliegen --}} + + + {{-- Weitere Einstellungen --}} + + + {{-- Vorhandenes Feld aus dem Katalog --}} + +
+ +
+ +
+
+
+
+
diff --git a/resources/views/filament/verwaltung/icon.blade.php b/resources/views/filament/verwaltung/icon.blade.php index 3fe5931..0b186a4 100644 --- a/resources/views/filament/verwaltung/icon.blade.php +++ b/resources/views/filament/verwaltung/icon.blade.php @@ -25,6 +25,12 @@ 'schluessel' => '', 'etikett' => '', 'filter' => '', + 'frage' => '', + 'liste' => '', + 'verzweigung' => '', + 'papierkorb' => '', + 'teilbereich' => '', + 'bereich' => '', 'zuruecksetzen' => '', ]; $name = $name ?? 'info'; diff --git a/resources/views/filament/verwaltung/styles.blade.php b/resources/views/filament/verwaltung/styles.blade.php index df56ca5..50fb5e6 100644 --- a/resources/views/filament/verwaltung/styles.blade.php +++ b/resources/views/filament/verwaltung/styles.blade.php @@ -708,4 +708,136 @@ .vw-symbolfeld-kacheln { grid-template-columns: repeat(auto-fill, minmax(5.25rem, 1fr)); } .vw-symbolfeld-panel { max-height: 18rem; } } + /* Formularansicht des Aufbaus (Formular-Editor, ADR-62): Bereiche als Karten, Teilbereiche als eingerahmte Einheit darin */ + .vw-fe { display: grid; gap: 1rem; min-width: 0; } + .vw-fe-aussen { display: grid; gap: 0.75rem; min-width: 0; } + .vw-fe-fehler { border: 1px solid var(--vw-error); background: var(--vw-error-soft); color: var(--vw-error); padding: 0.75rem 1rem; border-radius: var(--vw-radius); } + .vw-fe-fehler ul { margin: 0.35rem 0 0; padding-left: 1.25rem; } + .vw-fe-leiste { display: flex; flex-wrap: wrap; gap: 0.6rem 1.2rem; align-items: center; justify-content: space-between; } + .vw-fe-hinweis { display: flex; gap: 0.5rem; align-items: flex-start; max-width: 48rem; color: var(--vw-quiet); font-size: var(--vw-small); } + .vw-fe-hinweis svg { width: 1.1rem; height: 1.1rem; flex: none; margin-top: 0.15rem; } + .vw-fe-leiste-aktionen { display: flex; gap: 0.75rem; align-items: center; margin-left: auto; } + .vw-fe-zahl { color: var(--vw-quiet); font-size: var(--vw-small); } + .vw-fe-zusatz { color: var(--vw-error); font-weight: 600; font-size: var(--vw-small); } + + .vw-fe-bereiche { container-type: inline-size; container-name: fe; display: grid; gap: 1.5rem; min-width: 0; } + .vw-fe-bereich { border: 1px solid var(--vw-line-strong); border-left: 6px solid var(--vw-pine); border-radius: var(--vw-radius); background: var(--vw-surface); box-shadow: 0 2px 6px rgb(3 37 81 / 8%); min-width: 0; } + .vw-fe-bereich-kopf { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.6rem; padding: 0.7rem 0.9rem 0.7rem 0.5rem; background: var(--vw-paper); border-bottom: 1px solid var(--vw-line); border-radius: 0 var(--vw-radius) 0 0; } + .vw-fe-nummer { display: grid; place-items: center; flex: none; width: 2rem; height: 2rem; border-radius: 50%; background: var(--vw-pine); color: #fff; font-weight: 700; } + .vw-fe-titel { flex: 1 1 12rem; min-width: 0; } + .vw-fe-bereich-kopf .vw-fe-titel input { font-size: 1.15rem; font-weight: 700; } + .vw-fe-teil-kopf .vw-fe-titel input { font-weight: 650; } + + .vw-fe input[type="text"], .vw-fe input[type="search"], .vw-fe select, .vw-fe textarea { + width: 100%; min-height: var(--vw-target); padding: 0.4rem 0.65rem; border: 1px solid var(--vw-line-strong); border-radius: var(--vw-radius-small); + background: #fff; color: var(--vw-ink); font: inherit; line-height: 1.35; + } + .vw-fe textarea { resize: vertical; } + .vw-fe select:disabled { background: var(--vw-paper); color: var(--vw-quiet); cursor: not-allowed; } + .vw-fe input[readonly] { background: var(--vw-paper); } + .vw-fe .is-invalid { border-color: var(--vw-error); background: var(--vw-error-soft); box-shadow: inset 0 0 0 1px var(--vw-error); } + + .vw-fe-griff { display: grid; place-items: center; flex: none; width: 2rem; min-height: 2.25rem; padding: 0; border: 0; border-radius: var(--vw-radius-small); background: transparent; color: var(--vw-muted); cursor: grab; touch-action: none; } + .vw-fe-griff:hover { background: var(--vw-paper); color: var(--vw-ink); } + .vw-fe-griff:active { cursor: grabbing; } + .vw-fe-griff svg { width: 1.15rem; height: 1.15rem; } + + .vw-fe-symbole { display: flex; flex: none; align-items: center; gap: 0.15rem; } + .vw-fe-symbol { + position: relative; display: inline-grid; place-items: center; width: 2.25rem; height: 2.25rem; padding: 0; border: 1px solid transparent; border-radius: var(--vw-radius-small); + background: transparent; color: var(--vw-muted); cursor: pointer; + } + .vw-fe-symbol svg { width: 1.2rem; height: 1.2rem; } + .vw-fe-symbol:hover { border-color: var(--vw-line-strong); color: var(--vw-ink); background: #fff; } + .vw-fe-symbol:disabled { opacity: 0.35; cursor: not-allowed; } + .vw-fe-symbol.is-gesetzt { border-color: #b9d6a3; background: var(--vw-pine-soft); color: var(--vw-pine-dark); } + .vw-fe-symbol.is-warnung { border-color: #ecc77a; background: var(--vw-warn-soft); color: var(--vw-warn); } + .vw-fe-symbol.is-gefahr:hover { border-color: var(--vw-error); background: var(--vw-error-soft); color: var(--vw-error); } + .vw-fe-symbol.is-versteckt { visibility: hidden; } + .vw-fe-zaehler { position: absolute; right: -0.15rem; top: -0.3rem; min-width: 1.1rem; padding: 0 0.25rem; border-radius: 999px; background: var(--vw-pine); color: #fff; font-size: 0.7rem; font-weight: 700; line-height: 1.1rem; text-align: center; } + .vw-fe-symbol.is-warnung .vw-fe-zaehler { background: var(--vw-warn); } + + .vw-fe-inhalt { position: relative; display: grid; gap: 0.5rem; padding: 0.9rem; min-height: 4.5rem; align-content: start; } + .vw-fe-feld { background: #fff; border: 1px solid var(--vw-line); border-radius: var(--vw-radius-small); padding: 0.4rem 0.5rem 0.4rem 0.3rem; } + .vw-fe-feld.is-ungueltig { border-color: var(--vw-error); } + .vw-fe-zeile { + display: grid; gap: 0.4rem 0.6rem; align-items: center; + grid-template-columns: auto minmax(0, 1fr) 13rem 5.6rem auto; grid-template-areas: "griff frage typ pflicht symbole"; + } + .vw-fe-zeile > .vw-fe-griff { grid-area: griff; } + .vw-fe-frage { grid-area: frage; min-width: 0; } + .vw-fe-typ { grid-area: typ; min-width: 0; } + .vw-fe-pflicht { grid-area: pflicht; display: inline-flex; align-items: center; gap: 0.4rem; white-space: nowrap; font-size: var(--vw-small); font-weight: 600; cursor: pointer; } + .vw-fe-pflicht input { width: 1.1rem; height: 1.1rem; accent-color: var(--vw-pine); } + .vw-fe-zeile > .vw-fe-symbole { grid-area: symbole; } + @container fe (max-width: 46rem) { + .vw-fe-zeile { grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "griff frage frage" ". typ typ" ". pflicht symbole"; } + .vw-fe-zeile > .vw-fe-symbole { justify-self: end; } + } + @container fe (max-width: 30rem) { + .vw-fe-zeile { grid-template-columns: auto minmax(0, 1fr); grid-template-areas: "griff frage" ". typ" ". pflicht" ". symbole"; } + .vw-fe-zeile > .vw-fe-symbole { justify-self: start; } + } + .vw-fe-bedingung { display: flex; align-items: flex-start; gap: 0.4rem; margin: 0.4rem 0.4rem 0.1rem 2.4rem; padding: 0.3rem 0.6rem; border: 1px solid var(--vw-info-line); border-radius: var(--vw-radius-small); background: var(--vw-info); color: var(--vw-quiet); font-size: var(--vw-small); } + .vw-fe-bedingung svg { width: 1rem; height: 1rem; flex: none; margin-top: 0.15rem; color: var(--vw-select-line); } + .vw-fe-bedingung.is-info { background: var(--vw-paper); border-color: var(--vw-line); } + .vw-fe-bereich > .vw-fe-bedingung { margin: 0.6rem 0.9rem 0 0.9rem; } + .vw-fe-teil > .vw-fe-bedingung { margin: 0.1rem 0.7rem 0.3rem 2.6rem; background: #fff; } + + .vw-fe-anliegen .vw-fe-anliegen-text { display: grid; flex: 1 1 auto; min-width: 0; } + .vw-fe-anliegen .vw-fe-anliegen-text span { color: var(--vw-quiet); font-size: var(--vw-small); } + .vw-fe-anliegen { display: flex; align-items: center; gap: 0.5rem; background: var(--vw-paper); } + + .vw-fe-teil { border: 1px solid #c8dbec; border-left: 5px solid var(--vw-select-line); border-radius: var(--vw-radius); background: #f3f8fc; } + .vw-fe-teil-kopf { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem 0.5rem; padding: 0.5rem 0.6rem 0.4rem 0.3rem; } + .vw-fe-art { display: inline-flex; align-items: center; gap: 0.3rem; flex: none; color: var(--vw-select-line); font-size: var(--vw-small); font-weight: 700; } + .vw-fe-art svg { width: 1.15rem; height: 1.15rem; } + .vw-fe-teil-inhalt { position: relative; display: grid; gap: 0.5rem; padding: 0.2rem 0.7rem 0.7rem 1.4rem; min-height: 4.5rem; align-content: start; } + .vw-fe-teil .vw-fe-fuss { border-top: 0; padding: 0 0.7rem 0.7rem 1.4rem; } + .vw-fe-notiz { color: var(--vw-quiet); font-size: var(--vw-small); } + .vw-fe-teil > .vw-fe-notiz { margin: 0 0.7rem 0.4rem 2.6rem; } + .vw-fe-notiz.is-warnung { color: var(--vw-warn); font-weight: 600; } + + .vw-fe-fuss { display: flex; flex-wrap: wrap; gap: 0.5rem; padding: 0.7rem 0.9rem; border-top: 1px dashed var(--vw-line-strong); } + .vw-fe-inhalt[data-leer]::before, .vw-fe-teil-inhalt[data-leer]::before { + content: attr(data-leer); display: grid; place-items: center; min-height: 3.5rem; padding: 0.5rem; border: 2px dashed var(--vw-line-strong); border-radius: var(--vw-radius-small); + color: var(--vw-muted); font-size: var(--vw-small); text-align: center; pointer-events: none; + } + .vw-fe-leer-bereich { padding: 1.5rem; border: 2px dashed var(--vw-line-strong); border-radius: var(--vw-radius); color: var(--vw-muted); text-align: center; } + .vw-fe-ende { display: flex; } + + .vw-fe-geist { background: rgb(252 209 10 / 24%); outline: 2px dashed var(--vw-yellow); outline-offset: 2px; border-radius: var(--vw-radius-small); } + .vw-fe-geist > * { opacity: 0.5; } + .vw-fe-gezogen { box-shadow: 0 10px 28px rgb(3 37 81 / 22%); background: #fff; } + .vw-fe-gegriffen { cursor: grabbing; } + + /* Dialog für Hilfetext, Auswahlwerte, Bedingung, weitere Einstellungen und Katalog */ + .vw-fe-dialog { margin: auto; width: min(44rem, calc(100vw - 2rem)); max-height: calc(100vh - 2rem); max-height: calc(100dvh - 2rem); padding: 0; border: 0; border-radius: 0.75rem; background: var(--vw-surface); color: var(--vw-ink); box-shadow: 0 24px 60px rgb(3 37 81 / 30%); } + .vw-fe-dialog::backdrop { background: rgb(3 37 81 / 42%); } + .vw-fe-dialog-karte { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; max-height: calc(100vh - 2rem); max-height: calc(100dvh - 2rem); } + .vw-fe-dialog-kopf { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; padding: 1.1rem 1.25rem 0.6rem; } + .vw-fe-dialog-kopf h2 { font-size: 1.3rem; } + .vw-fe-dialog-inhalt { min-height: 0; overflow: auto; padding: 0.4rem 1.25rem 1rem; } + .vw-fe-dialog-fuss { display: flex; justify-content: flex-end; padding: 0.75rem 1.25rem 1rem; border-top: 1px solid var(--vw-line); } + .vw-fe-formular { display: grid; gap: 0.9rem; } + .vw-fe-etikett { display: grid; gap: 0.3rem; font-weight: 650; } + .vw-fe-werte { display: grid; gap: 0.4rem; margin: 0; padding: 0; list-style: none; } + .vw-fe-wert { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; gap: 0.3rem; align-items: center; } + .vw-fe-bed { display: grid; gap: 0.6rem; margin: 0; padding: 0.4rem 0.8rem 0.8rem; border: 1px solid var(--vw-line-strong); border-radius: var(--vw-radius-small); } + .vw-fe-bed.is-ungueltig { border-color: var(--vw-warn); background: var(--vw-warn-soft); } + .vw-fe-bed legend { padding: 0 0.3rem; font-weight: 700; } + .vw-fe-bed-zeile { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) auto; gap: 0.5rem; align-items: end; } + .vw-fe-werteliste { display: flex; flex-wrap: wrap; gap: 0.4rem; } + .vw-fe-wahl { display: inline-flex; align-items: center; gap: 0.45rem; min-height: 2.25rem; padding: 0.25rem 0.8rem; border: 1px solid var(--vw-line-strong); border-radius: 999px; background: #fff; cursor: pointer; } + .vw-fe-wahl:has(input:checked) { border-color: var(--vw-pine); background: var(--vw-pine-soft); color: var(--vw-pine-dark); font-weight: 650; } + .vw-fe-wahl input { accent-color: var(--vw-pine); } + .vw-fe-katalog { display: grid; gap: 0.3rem; max-height: 22rem; margin: 0; padding: 0; overflow: auto; list-style: none; } + .vw-fe-katalog-eintrag { display: grid; gap: 0.1rem; width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--vw-line); border-radius: var(--vw-radius-small); background: #fff; color: var(--vw-ink); font: inherit; text-align: left; cursor: pointer; } + .vw-fe-katalog-eintrag:hover { border-color: var(--vw-pine); background: var(--vw-pine-soft); } + .vw-fe-katalog-eintrag span { color: var(--vw-quiet); font-size: var(--vw-small); } + @media (max-width: 40rem) { + .vw-fe-bed-zeile { grid-template-columns: minmax(0, 1fr) auto; } + .vw-fe-bed-zeile > :nth-child(2) { grid-column: 1; } + .vw-fe-dialog { width: calc(100vw - 1rem); } + } diff --git a/resources/views/mail/communication-test.blade.php b/resources/views/mail/communication-test.blade.php new file mode 100644 index 0000000..a519b83 --- /dev/null +++ b/resources/views/mail/communication-test.blade.php @@ -0,0 +1,4 @@ +Das ist eine Testnachricht der Kommunikationsverwaltung. + +Wenn Sie diese Nachricht lesen, erreichen Sie auch die Benachrichtigungen über neue Anfragen. +Die Testnachricht enthält keine Anfragedaten. diff --git a/resources/views/mail/inquiry-received.blade.php b/resources/views/mail/inquiry-received.blade.php new file mode 100644 index 0000000..1cf2fc5 --- /dev/null +++ b/resources/views/mail/inquiry-received.blade.php @@ -0,0 +1,11 @@ +Neue Anfrage {{ $reference }} + +Eingegangen: {{ $received }} +@if ($issue !== '') +Anliegen: {{ $issue }} +@endif + +Die Angaben stehen in der Verwaltung (Anmeldung erforderlich): +{{ $url }} + +Diese Nachricht enthält absichtlich keine Kontaktdaten und keine Antworten. diff --git a/resources/views/widgets/inquiry.blade.php b/resources/views/widgets/inquiry.blade.php new file mode 100644 index 0000000..0c65808 --- /dev/null +++ b/resources/views/widgets/inquiry.blade.php @@ -0,0 +1,45 @@ +@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) + + @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 +@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 diff --git a/routes/web.php b/routes/web.php index c534843..de208cb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -8,6 +8,8 @@ use App\Http\Controllers\ContentPreviewController; use App\Http\Controllers\DocumentPreviewController; use App\Http\Controllers\EditorialPreviewController; +use App\Http\Controllers\InquiryFormController; +use App\Http\Controllers\InquiryPreviewController; use App\Http\Controllers\Member\CheckoutController; use App\Http\Controllers\Member\DocumentController; use App\Http\Controllers\Member\ExerciseController; @@ -68,6 +70,29 @@ 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'); + Route::post('/senden', [InquiryFormController::class, 'submit'])->middleware('throttle:inquiry-submit')->name('submit'); +}); + +Route::middleware('auth:staff')->prefix('redaktion/anfrage')->name('communication.preview.')->group(function () { + Route::get('/vorlage/{template}', [InquiryPreviewController::class, 'template'])->whereNumber('template')->name('template'); + Route::get('/vorlage/{template}/formular', [InquiryPreviewController::class, 'templateDefinition'])->whereNumber('template')->name('template.definition'); + Route::post('/vorlage/{template}/zustand', [InquiryPreviewController::class, 'templateState'])->whereNumber('template')->name('template.state'); + Route::get('/einstieg/{entry}', [InquiryPreviewController::class, 'entry'])->whereNumber('entry')->name('entry'); + Route::get('/einstieg/{entry}/formular', [InquiryPreviewController::class, 'entryDefinition'])->whereNumber('entry')->name('entry.definition'); + Route::post('/einstieg/{entry}/zustand', [InquiryPreviewController::class, 'entryState'])->whereNumber('entry')->name('entry.state'); +}); + Route::middleware('guest')->group(function () { Route::get('/registrieren', [RegistrationController::class, 'create'])->name('register'); Route::post('/registrieren', [RegistrationController::class, 'store']); diff --git a/tests/Feature/CommunicationAdminTest.php b/tests/Feature/CommunicationAdminTest.php new file mode 100644 index 0000000..9907f48 --- /dev/null +++ b/tests/Feature/CommunicationAdminTest.php @@ -0,0 +1,483 @@ +{$role}()->create(); + $user->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $user; + } + + private function inquiry(): Inquiry + { + config(['communication.min_fill_seconds' => 0]); + $entry = InquiryEntry::query()->where('key', 'kurse_workshops')->firstOrFail(); + app(InquiryService::class)->submit($entry, [ + 'token' => FormToken::issue($entry->id, $entry->template->published_version_id), + 'source' => '/kurse', + 'values' => [ + 'anliegen' => 'kurse', 'unteranliegen' => 'kursinfo', 'kursformat' => 'schul_ag', 'region' => 'Hannover', + 'vorname' => 'Mira', 'nachname' => 'Beispiel', 'email' => 'mira@example.org', 'nachricht' => 'Bitte um Rückruf.', + ], + ]); + + return Inquiry::query()->firstOrFail(); + } + + public function test_the_issue_list_opens_for_the_editor_and_shows_the_hierarchy(): void + { + app(ExampleConfiguration::class)->install(); + + $this->actingAs($this->staff('redakteur'), 'staff') + ->get('/verwaltung/kommunikation/anliegen') + ->assertOk() + ->assertSee('Kurse & Workshops', false) + ->assertSee('Konkretes Kursvorhaben'); + } + + public function test_every_configuration_area_and_its_object_pages_open(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + + foreach ([ + '/verwaltung/kommunikation/anliegen/'.InquiryIssue::query()->first()->id, + '/verwaltung/kommunikation/felder', + '/verwaltung/kommunikation/felder/'.InquiryField::query()->where('key', 'kursformat')->value('id'), + '/verwaltung/kommunikation/feldgruppen', + '/verwaltung/kommunikation/feldgruppen/'.InquiryFieldGroup::query()->first()->id, + '/verwaltung/kommunikation/vorlagen', + '/verwaltung/kommunikation/vorlagen/'.InquiryTemplate::query()->where('key', 'kursanfragen')->value('id'), + '/verwaltung/kommunikation/einstiege', + '/verwaltung/kommunikation/einstiege/'.InquiryEntry::query()->where('key', 'schul_ag')->value('id'), + ] as $url) { + $this->actingAs($editor, 'staff')->get($url)->assertOk(); + } + + $this->actingAs($editor, 'staff')->get('/verwaltung/kommunikation/vorlagen/'.InquiryTemplate::query()->where('key', 'kursanfragen')->value('id')) + ->assertSee('Kursanfragen') + ->assertSee('Fassungen'); + } + + public function test_customer_service_reads_inquiries_but_cannot_configure_and_editors_cannot_read_inquiries(): void + { + app(ExampleConfiguration::class)->install(); + $inquiry = $this->inquiry(); + + $this->actingAs($this->staff('kundenbetreuung'), 'staff')->get('/verwaltung/kommunikation/vorlagen')->assertForbidden(); + $this->actingAs($this->staff('kundenbetreuung'), 'staff')->get('/verwaltung/anfragen')->assertOk()->assertSee('Mira Beispiel'); + $this->actingAs($this->staff('kundenbetreuung'), 'staff')->get('/verwaltung/anfragen/'.$inquiry->id)->assertOk(); + + // D10: Redaktion und Katalogverwaltung sehen keine personenbezogenen Anfragen. + foreach (['redakteur', 'katalogverwalter'] as $role) { + $this->actingAs($this->staff($role), 'staff')->get('/verwaltung/anfragen')->assertForbidden(); + $this->actingAs($this->staff($role), 'staff')->get('/verwaltung/anfragen/'.$inquiry->id)->assertForbidden(); + $this->actingAs($this->staff($role), 'staff')->get('/verwaltung/kommunikation/einstellungen')->assertForbidden(); + } + } + + public function test_guests_are_sent_to_the_login(): void + { + $this->get('/verwaltung/kommunikation/anliegen')->assertRedirect('/verwaltung/login'); + $this->get('/verwaltung/anfragen')->assertRedirect('/verwaltung/login'); + } + + public function test_the_inbox_shows_structured_answers_readably_and_the_source(): void + { + app(ExampleConfiguration::class)->install(); + $inquiry = $this->inquiry(); + + $this->actingAs($this->staff('kundenbetreuung'), 'staff')->get('/verwaltung/anfragen/'.$inquiry->id) + ->assertOk() + ->assertSee('Welches Format interessiert Sie?') + ->assertSee('Schul-AG') + ->assertSee('Hannover') + ->assertSee('Bitte um Rückruf.') + ->assertSee('/kurse') + ->assertSee('mira@example.org') + ->assertSee('Kurse & Workshops › Allgemeine Kursinformation', false) + ->assertSee('Fassung 1'); + } + + public function test_status_and_notes_are_maintained_by_hand(): void + { + app(ExampleConfiguration::class)->install(); + $inquiry = $this->inquiry(); + $user = $this->staff('kundenbetreuung'); + + $this->assertSame(InquiryStatus::Neu, $inquiry->status); + + Livewire::actingAs($user, 'staff')->test(ViewInquiry::class, ['record' => $inquiry->id]) + ->callAction('status', ['status' => 'in_bearbeitung']) + ->assertHasNoActionErrors(); + + Livewire::actingAs($user, 'staff')->test(ViewInquiry::class, ['record' => $inquiry->id]) + ->callAction('note', ['body' => 'Rückruf am Donnerstag vereinbart.']) + ->assertHasNoActionErrors(); + + $this->assertSame(InquiryStatus::InBearbeitung, $inquiry->fresh()->status); + $note = InquiryNote::query()->firstOrFail(); + $this->assertSame('Rückruf am Donnerstag vereinbart.', $note->body); + $this->assertSame($user->id, $note->user_id); + + $this->actingAs($user, 'staff')->get('/verwaltung/anfragen/'.$inquiry->id)->assertSee('Rückruf am Donnerstag vereinbart.'); + } + + public function test_the_inbox_list_searches_filters_and_sorts(): void + { + app(ExampleConfiguration::class)->install(); + $first = $this->inquiry(); + $user = $this->staff('kundenbetreuung'); + + Livewire::actingAs($user, 'staff')->test(ListInquiries::class) + ->assertSee('Mira Beispiel') + ->set('suche', 'mira@example.org') + ->assertSee('Mira Beispiel') + ->set('suche', 'gibtsnicht') + ->assertDontSee('Mira Beispiel') + ->call('resetFilters') + ->set('zustand', 'erledigt') + ->assertDontSee('Mira Beispiel') + ->set('zustand', 'neu') + ->assertSee('Mira Beispiel') + ->set('anliegen', 'kurse') + ->assertSee('Mira Beispiel') + ->set('anliegen', 'allgemein') + ->assertDontSee('Mira Beispiel'); + + $this->assertSame($first->id, Inquiry::query()->firstOrFail()->id); + } + + public function test_only_system_administration_may_delete_an_inquiry(): void + { + app(ExampleConfiguration::class)->install(); + $inquiry = $this->inquiry(); + + Livewire::actingAs($this->staff('kundenbetreuung'), 'staff')->test(ViewInquiry::class, ['record' => $inquiry->id]) + ->assertActionHidden('erase'); + + Livewire::actingAs($this->staff('systemverwalter'), 'staff')->test(ViewInquiry::class, ['record' => $inquiry->id]) + ->callAction('erase'); + + $this->assertSame(0, Inquiry::query()->count()); + } + + public function test_a_failed_notification_can_be_repeated_from_the_inbox(): void + { + app(ExampleConfiguration::class)->install(); + $inquiry = $this->inquiry(); + $this->assertStringContainsString('keine Empfänger', (string) $inquiry->notification_error); + + Mail::fake(); + CommunicationSettings::current()->update(['recipients' => ['team@example.org']]); + + Livewire::actingAs($this->staff('kundenbetreuung'), 'staff')->test(ViewInquiry::class, ['record' => $inquiry->id]) + ->callAction('resend'); + + $this->assertNotNull($inquiry->fresh()->notified_at); + $this->assertNull($inquiry->fresh()->notification_error); + } + + public function test_the_settings_save_recipients_and_send_a_test_message(): void + { + Mail::fake(); + $user = $this->staff('kundenbetreuung'); + + Livewire::actingAs($user, 'staff')->test(KommunikationEinstellungen::class) + ->fillForm(['recipients' => "team@example.org\n kein-mail"]) + ->call('save') + ->assertHasFormErrors(['recipients']); + + Livewire::actingAs($user, 'staff')->test(KommunikationEinstellungen::class) + ->fillForm(['recipients' => "team@example.org\nbuero@example.org", 'retention_months' => 24]) + ->call('save') + ->assertHasNoFormErrors(); + + $settings = CommunicationSettings::current(); + $this->assertSame(['team@example.org', 'buero@example.org'], $settings->recipientList()); + $this->assertSame(24, $settings->retention_months); + + Livewire::actingAs($user, 'staff')->test(KommunikationEinstellungen::class)->callAction('test'); + Mail::assertSent(CommunicationTestMail::class, fn ($mail): bool => $mail->hasTo('buero@example.org')); + } + + public function test_the_example_configuration_is_created_on_request_and_only_in_an_empty_area(): void + { + $user = $this->staff('systemverwalter'); + + Livewire::actingAs($user, 'staff')->test(KommunikationEinstellungen::class)->callAction('example'); + $this->assertSame(5, InquiryEntry::query()->live()->count()); + + Livewire::actingAs($user, 'staff')->test(KommunikationEinstellungen::class)->assertActionHidden('example'); + } + + public function test_an_issue_can_be_created_with_a_sub_issue_and_stays_unique(): void + { + $editor = $this->staff('redakteur'); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryIssues::class) + ->callAction('create', ['label' => 'Fördermittel', 'parent_id' => null]) + ->assertHasNoActionErrors(); + $parent = InquiryIssue::query()->where('label', 'Fördermittel')->firstOrFail(); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryIssues::class) + ->callAction('create', ['label' => 'Fördermittel', 'parent_id' => $parent->id]); + + $keys = InquiryIssue::query()->pluck('key')->all(); + $this->assertSame(['foerdermittel', 'foerdermittel_2'], $keys); + $this->assertSame($parent->id, InquiryIssue::query()->where('key', 'foerdermittel_2')->value('parent_id')); + } + + public function test_a_choice_field_is_created_with_stable_option_keys_that_survive_renaming(): void + { + $editor = $this->staff('redakteur'); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryFields::class) + ->callAction('create', ['name' => 'Einrichtungstyp', 'label' => 'Einrichtungstyp', 'type' => 'select', 'options' => [['label' => 'Grundschule'], ['label' => 'Verein']]]) + ->assertHasNoActionErrors(); + + $field = InquiryField::query()->where('key', 'einrichtungstyp')->firstOrFail(); + $this->assertSame([['key' => 'grundschule', 'label' => 'Grundschule'], ['key' => 'verein', 'label' => 'Verein']], $field->optionList()); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryField::class, ['record' => $field->id]) + ->fillForm(['options' => [['key' => 'grundschule', 'label' => 'Primarschule'], ['key' => 'verein', 'label' => 'Verein'], ['label' => 'Sonstiges']]]) + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertSame( + [['key' => 'grundschule', 'label' => 'Primarschule'], ['key' => 'verein', 'label' => 'Verein'], ['key' => 'sonstiges', 'label' => 'Sonstiges']], + $field->fresh()->optionList(), + ); + } + + public function test_a_purpose_must_fit_the_field_type(): void + { + $editor = $this->staff('redakteur'); + Livewire::actingAs($editor, 'staff')->test(ListInquiryFields::class)->callAction('create', ['name' => 'Zahl', 'label' => 'Zahl', 'type' => 'number']); + $field = InquiryField::query()->firstOrFail(); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryField::class, ['record' => $field->id]) + ->fillForm(['purpose' => 'email']) + ->call('save') + ->assertHasFormErrors(['purpose']); + } + + public function test_a_field_group_keeps_the_chosen_order(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryFieldGroups::class)->callAction('create', ['name' => 'Neue Gruppe']); + $group = InquiryFieldGroup::query()->where('key', 'neue_gruppe')->firstOrFail(); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryFieldGroup::class, ['record' => $group->id]) + ->fillForm(['items' => [['field' => 'email', 'required' => true], ['field' => 'telefon', 'required' => false]]]) + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertSame(['email', 'telefon'], array_column($group->fresh()->itemList(), 'field')); + } + + public function test_a_template_is_edited_checked_published_and_restored_through_the_interface(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + $template = InquiryTemplate::query()->where('key', 'allgemein')->firstOrFail(); + $firstVersion = $template->published_version_id; + + $component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]); + $component->fillForm(['draft.texts.heading' => 'Anders überschrieben'])->call('save')->assertHasNoFormErrors(); + + $this->assertSame('Anders überschrieben', $template->fresh()->draft['texts']['heading']); + $this->assertTrue($template->fresh()->hasUnpublishedChanges()); + + $component->callAction('check')->assertNotified(); + $component->callAction('publish', ['note' => 'Neue Überschrift'])->assertHasNoActionErrors(); + + $template->refresh(); + $this->assertNotSame($firstVersion, $template->published_version_id); + $this->assertSame('Neue Überschrift', $template->publishedVersion->note); + $this->assertSame($editor->id, $template->publishedVersion->published_by); + $this->assertSame('Anders überschrieben', $template->publishedVersion->definition['texts']['heading']); + + // Rückkehr zur ersten Fassung über die Fassungsliste. + $old = $template->versions()->where('version', 1)->firstOrFail(); + Livewire::actingAs($editor, 'staff')->test(VersionsRelationManager::class, ['ownerRecord' => $template, 'pageClass' => EditInquiryTemplate::class]) + ->callTableAction('restore', $old); + + $this->assertSame($old->id, $template->fresh()->published_version_id); + } + + public function test_the_template_editor_keeps_steps_items_and_rules_as_clean_lists(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + $template = InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail(); + $before = $template->draft; + + Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]) + ->call('save') + ->assertHasNoFormErrors(); + + $after = $template->fresh()->draft; + $this->assertTrue(array_is_list($after['steps'])); + $this->assertTrue(array_is_list($after['steps'][1]['items'])); + $this->assertTrue(array_is_list($after['rules'])); + $this->assertSame(count($before['rules']), count($after['rules'])); + $this->assertSame($before['steps'][1]['items'], $after['steps'][1]['items']); + $this->assertFalse($template->fresh()->hasUnpublishedChanges(), 'Speichern ohne Änderung erzeugt keine unveröffentlichten Änderungen.'); + } + + public function test_an_entry_is_configured_checked_published_and_withdrawn(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + $entry = InquiryEntry::query()->where('key', 'schul_ag')->firstOrFail(); + + $component = Livewire::actingAs($editor, 'staff')->test(EditInquiryEntry::class, ['record' => $entry->id]); + $component->assertFormSet(['config.mode' => 'wizard']); + $component->fillForm(['config.texts.heading' => 'Schul-AG: jetzt anfragen', 'config.preselect' => [['field' => 'kursformat', 'value' => 'vertiefung']]])->call('save'); + + $entry->refresh(); + $this->assertSame('vertiefung', $entry->config['defaults']['kursformat']); + $this->assertTrue($entry->hasUnpublishedChanges()); + $this->assertSame('schul_ag', $entry->published_config['defaults']['kursformat'], 'Der veröffentlichte Stand ändert sich erst mit „Veröffentlichen“.'); + + $component->callAction('publish')->assertNotified(); + $this->assertSame('vertiefung', $entry->fresh()->published_config['defaults']['kursformat']); + + $component->callAction('withdraw'); + $this->assertFalse($entry->fresh()->isLive()); + $this->assertNotNull($entry->fresh()->config); + + $component->callAction('publish'); + $this->assertTrue($entry->fresh()->isLive()); + } + + public function test_an_entry_cannot_be_published_with_a_value_the_template_does_not_know(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + $entry = InquiryEntry::query()->where('key', 'schul_ag')->firstOrFail(); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryEntry::class, ['record' => $entry->id]) + ->fillForm(['config.preselect' => [['field' => 'kursformat', 'value' => 'gibt_es_nicht']]]) + ->call('save') + ->callAction('publish'); + + $this->assertSame('schul_ag', $entry->fresh()->published_config['defaults']['kursformat']); + } + + public function test_templates_and_entries_can_be_archived_only_when_nothing_live_depends_on_them(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + $template = InquiryTemplate::query()->where('key', 'kooperationsanfragen')->firstOrFail(); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id])->callAction('archive'); + $this->assertNull($template->fresh()->archived_at, 'Ein veröffentlichter Einstieg verwendet die Vorlage noch.'); + + $entry = InquiryEntry::query()->where('key', 'kooperation')->firstOrFail(); + Livewire::actingAs($editor, 'staff')->test(EditInquiryEntry::class, ['record' => $entry->id])->callAction('archive'); + $this->assertNotNull($entry->fresh()->archived_at); + $this->assertFalse($entry->fresh()->isLive()); + + Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id])->callAction('archive'); + $this->assertNotNull($template->fresh()->archived_at); + } + + public function test_the_lists_search_and_filter_by_state(): void + { + app(ExampleConfiguration::class)->install(); + $editor = $this->staff('redakteur'); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryEntries::class) + ->assertSee('Schul-AG') + ->set('suche', 'Kooperation') + ->assertSee('Kooperation') + ->assertDontSee('Schul-AG') + ->call('resetFilters') + ->set('zustand', 'archiviert') + ->assertDontSee('Schul-AG'); + + Livewire::actingAs($editor, 'staff')->test(ListInquiryTemplates::class) + ->assertSee('Kursanfragen') + ->assertSee('Fassung 1 gültig'); + } + + public function test_the_preview_shows_the_form_for_the_editor_only(): void + { + app(ExampleConfiguration::class)->install(); + $template = InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail(); + $entry = InquiryEntry::query()->where('key', 'schul_ag')->firstOrFail(); + $editor = $this->staff('redakteur'); + + $this->actingAs($editor, 'staff')->get(route('communication.preview.template', $template))->assertOk()->assertSee('data-preview="1"', false); + $this->actingAs($editor, 'staff')->get(route('communication.preview.template', ['template' => $template, 'modus' => 'wizard']))->assertOk()->assertSee('data-inquiry', false); + $this->actingAs($editor, 'staff')->get(route('communication.preview.entry', $entry))->assertOk()->assertSee('data-preview="1"', false); + $this->actingAs($editor, 'staff')->getJson(route('communication.preview.entry.definition', $entry))->assertOk()->assertJsonPath('mode', 'wizard'); + $this->actingAs($editor, 'staff')->postJson(route('communication.preview.template.state', $template), ['values' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursinfo']])->assertOk()->assertJsonPath('steps.skurs2', false); + + $this->actingAs($this->staff('kundenbetreuung'), 'staff')->get(route('communication.preview.template', $template))->assertForbidden(); + } + + public function test_the_preview_is_closed_to_guests(): void + { + app(ExampleConfiguration::class)->install(); + $template = InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail(); + + $this->get(route('communication.preview.template', $template))->assertRedirect(); + } + + public function test_the_preview_reports_configuration_problems_instead_of_a_broken_form(): void + { + app(ExampleConfiguration::class)->install(); + $template = InquiryTemplate::query()->where('key', 'allgemein')->firstOrFail(); + $draft = $template->draft; + $draft['steps'][0]['items'] = [['kind' => 'issue']]; + $template->update(['draft' => $draft]); + + $this->actingAs($this->staff('redakteur'), 'staff')->get(route('communication.preview.template', $template)) + ->assertOk() + ->assertSee('Die Vorschau ist nicht möglich') + ->assertSee('E-Mail-Adresse für Rückfragen'); + } +} diff --git a/tests/Feature/CommunicationEditorTest.php b/tests/Feature/CommunicationEditorTest.php new file mode 100644 index 0000000..d3625c1 --- /dev/null +++ b/tests/Feature/CommunicationEditorTest.php @@ -0,0 +1,403 @@ +install(); + } + + /** + * @param array $draft + * @return array + */ + 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' => []]]]]); + } + + /** + * @param array $overrides + * @return array + */ + private function newField(string $label, array $overrides = []): array + { + return ['kind' => 'field', 'key' => FormEditor::temporaryKey(), 'label' => $label, 'type' => 'text', 'required' => false, 'purpose' => null, 'options' => [], 'cond' => [], ...$overrides]; + } + + /** + * @param list> $items + */ + private function setTree($component, array $items): void + { + $tree = json_decode((string) $component->get('data.editor_json'), true); + $tree['areas'][0]['items'] = $items; + $component->set('data.editor_json', json_encode($tree)); + } + + public function test_the_tree_view_nests_fields_in_their_section_and_converts_back_without_loss(): void + { + $editor = app(FormEditor::class); + + foreach (InquiryTemplate::query()->get() as $template) { + $draft = (array) $template->draft; + $view = $editor->expand($draft); + $tree = FormEditor::toTree($view); + + foreach ($tree['areas'] as $area) { + foreach ($area['items'] as $item) { + $this->assertContains($item['kind'], ['field', 'section', 'issue'], 'Im Baum gibt es keine Ende-Markierung: '.$template->name); + } + } + + $fieldsBefore = InquiryField::query()->get()->map->getAttributes()->all(); + $groupsBefore = InquiryFieldGroup::query()->get()->map->getAttributes()->all(); + $saved = $editor->persist(FormEditor::fromTree(json_decode((string) json_encode($tree), true))); + + $this->assertSame($this->structure($draft), $this->structure($saved), 'Über den Baum 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); + } + + $courses = FormEditor::toTree($editor->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft)); + $sections = collect($courses['areas'])->flatMap(fn (array $area) => $area['items'])->where('kind', 'section'); + $this->assertTrue($sections->isNotEmpty()); + $this->assertTrue($sections->every(fn (array $section): bool => $section['items'] !== []), 'Ein Teilbereich trägt seine Felder selbst.'); + } + + public function test_a_field_after_a_section_stays_outside_it_and_a_second_section_ends_the_first(): void + { + $editor = app(FormEditor::class); + $tree = ['areas' => [['key' => 'sx1', 'title' => 'Eins', 'intro' => null, 'cond' => [], 'items' => [ + ['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => 'Erster Teil', 'items' => [$this->newField('Frage A'), $this->newField('Frage B')]], + ['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => 'Zweiter Teil', 'items' => [$this->newField('Frage C')]], + $this->newField('Frage D'), + ]]]]; + + $this->assertSame([], $editor->validateTree($tree)); + $draft = $editor->persist(FormEditor::fromTree($tree)); + + $items = $draft['steps'][0]['items']; + $this->assertSame(['group', 'group', 'field'], array_column($items, 'kind')); + $this->assertSame(['frage_a', 'frage_b'], array_column(InquiryFieldGroup::query()->where('label', 'Erster Teil')->firstOrFail()->itemList(), 'field')); + $this->assertSame(['frage_c'], array_column(InquiryFieldGroup::query()->where('label', 'Zweiter Teil')->firstOrFail()->itemList(), 'field')); + $this->assertSame('frage_d', $items[2]['field']); + } + + public function test_the_tree_is_checked_before_saving_and_missing_details_are_named(): void + { + $editor = app(FormEditor::class); + $tree = ['areas' => [ + ['key' => 'sx1', 'title' => '', 'items' => [ + $this->newField(''), + $this->newField('Welche Art?', ['type' => 'select', 'options' => [['key' => '', 'label' => ' ']]]), + ['kind' => 'section', 'key' => FormEditor::temporaryKey(), 'label' => '', 'items' => []], + ['kind' => 'issue', 'issues' => []], + ['kind' => 'issue', 'issues' => []], + ]], + ]]; + + $errors = implode("\n", $editor->validateTree($tree)); + + $this->assertStringContainsString('Der Titel fehlt', $errors); + $this->assertStringContainsString('keine Frage oder Beschriftung', $errors); + $this->assertStringContainsString('Bei „Welche Art?“ fehlen die Auswahlwerte', $errors); + $this->assertStringContainsString('keine Überschrift', $errors); + $this->assertStringContainsString('nur einmal', $errors); + + $same = $this->newField('Doppelt', ['key' => 'email']); + $twice = ['areas' => [['key' => 'sx1', 'title' => 'Eins', 'items' => [$same, $same]]]]; + $this->assertStringContainsString('steht mehrfach im Formular', implode("\n", $editor->validateTree($twice))); + } + + public function test_the_client_configuration_lists_types_catalog_issues_and_effects(): void + { + $config = app(FormEditor::class)->clientConfig(); + + $this->assertContains('select', array_column($config['types'], 'value')); + $this->assertContains('email', array_column($config['catalog'], 'key')); + $this->assertSame(['show', 'hide', 'skip'], array_keys($config['effects']['step'])); + $this->assertArrayHasKey('eq', $config['operators']); + $this->assertNotEmpty($config['issues']); + } + + public function test_the_form_view_renders_the_areas_without_the_builder_blocks(): void + { + $template = InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail(); + + $html = Livewire::actingAs($this->staff(), 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id])->html(); + + $this->assertStringContainsString('data-fe-root', $html); + $this->assertStringContainsString('Bereich hinzufügen', $html); + $this->assertStringContainsString('Vorhandenes Feld einfügen', $html); + $this->assertStringNotContainsString('fi-fo-builder', $html); + } + + 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]); + $tree = json_decode((string) $component->get('data.editor_json'), true); + $this->assertCount(1, $tree['areas']); + + $this->setTree($component, [ + $this->newField('Ihr Rufname', ['required' => true, 'purpose' => 'name']), + $this->newField('Ihre Mailadresse zur Antwort', ['type' => 'email', 'required' => true, 'purpose' => 'email']), + ]); + $component->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')); + + // Nach dem Speichern trägt der Baum die festen Kennungen; ein zweites Speichern legt nichts doppelt an. + $saved = json_decode((string) $component->get('data.editor_json'), true); + $this->assertSame('ihr_rufname', $saved['areas'][0]['items'][0]['key']); + $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_incomplete_tree_is_rejected_with_the_reasons_and_changes_nothing(): void + { + $editor = $this->staff(); + $template = $this->emptyForm('luecken'); + $fieldsBefore = InquiryField::query()->count(); + $component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]); + + $this->setTree($component, [$this->newField('Mit Frage'), $this->newField('')]); + $component->call('save')->assertHasErrors(['data.editor_json']); + + $this->assertSame($fieldsBefore, InquiryField::query()->count(), 'Nichts wird angelegt, solange etwas fehlt.'); + $this->assertSame([], $template->fresh()->draft['steps'][0]['items']); + } + + 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]); + + $this->setTree($component, [$this->newField('Ihr Name', ['required' => true])]); + $component->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 & 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'])); + } +} diff --git a/tests/Feature/CommunicationInquiryTest.php b/tests/Feature/CommunicationInquiryTest.php new file mode 100644 index 0000000..734f0b2 --- /dev/null +++ b/tests/Feature/CommunicationInquiryTest.php @@ -0,0 +1,438 @@ + 0]); + app(ExampleConfiguration::class)->install(); + } + + private function entry(string $key): InquiryEntry + { + return InquiryEntry::query()->where('key', $key)->firstOrFail(); + } + + /** + * @param array $values + * @return array{reference: string, created: bool} + */ + private function send(InquiryEntry $entry, array $values, array $extra = []): array + { + $version = $entry->template->publishedVersion; + + return app(InquiryService::class)->submit($entry, array_merge([ + 'token' => FormToken::issue($entry->id, $version->id), + 'values' => $values, + ], $extra)); + } + + /** @return array */ + private function infoRequest(): array + { + return [ + 'anliegen' => 'kurse', + 'unteranliegen' => 'kursinfo', + 'kursformat' => 'schul_ag', + 'region' => 'Hannover', + 'vorname' => 'Mira', + 'nachname' => 'Beispiel', + 'email' => 'mira@example.org', + 'nachricht' => 'Wir möchten gern mehr erfahren.', + ]; + } + + public function test_the_example_configuration_is_published_and_only_installs_into_an_empty_area(): void + { + $this->assertSame(5, InquiryEntry::query()->live()->count()); + $this->assertSame(4, InquiryTemplate::query()->whereNotNull('published_version_id')->count()); + + $this->expectException(\RuntimeException::class); + app(ExampleConfiguration::class)->install(); + } + + public function test_an_information_request_asks_only_for_few_details_and_stores_readable_answers(): void + { + $result = $this->send($this->entry('kurse_workshops'), $this->infoRequest()); + + $this->assertTrue($result['created']); + + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertSame($result['reference'], $inquiry->reference); + $this->assertSame('Kurse & Workshops › Allgemeine Kursinformation', $inquiry->issueTitle()); + $this->assertSame('Mira Beispiel', $inquiry->contact_name); + $this->assertSame('mira@example.org', $inquiry->contact_email); + $this->assertSame('Wir möchten gern mehr erfahren.', $inquiry->message); + $this->assertSame(InquiryStatus::Neu, $inquiry->status); + + $answers = collect($inquiry->answers)->keyBy('key'); + $this->assertSame('Schul-AG', $answers['kursformat']['display']); + $this->assertSame('Welches Format interessiert Sie?', $answers['kursformat']['label']); + $this->assertSame('Ihre Kontaktdaten', $answers['email']['group']); + $this->assertArrayNotHasKey('einrichtung_name', $answers->all()); + } + + public function test_values_of_fields_that_are_not_relevant_are_never_stored(): void + { + // Besucher hat erst „konkretes Vorhaben“ ausgefüllt, dann auf „Information“ gewechselt: Schritt 2 entfällt. + $values = $this->infoRequest() + [ + 'einrichtung_name' => 'Altschule', + 'einrichtungstyp' => 'grundschule', + 'anzahl_kinder' => '24', + ]; + + $this->send($this->entry('kurse_workshops'), $values); + + $keys = collect(Inquiry::query()->firstOrFail()->answers)->pluck('key')->all(); + $this->assertNotContains('einrichtung_name', $keys); + $this->assertNotContains('anzahl_kinder', $keys); + $this->assertContains('region', $keys); + } + + public function test_a_concrete_course_request_needs_the_additional_planning_details_and_shows_follow_up_fields(): void + { + $values = [ + 'anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag', + 'einrichtung_name' => 'Grundschule Süd', 'einrichtungstyp' => 'grundschule', + 'einrichtung_strasse' => 'Schulweg 1', 'einrichtung_plz' => '30159', 'einrichtung_ort' => 'Hannover', + 'traeger_abweichend' => 'nein', 'ort_abweichend' => 'nein', + 'alter' => '8 bis 10 Jahre', 'anzahl_kinder' => '20', + 'vorname' => 'Mira', 'nachname' => 'Beispiel', 'email' => 'mira@example.org', + ]; + + $entry = $this->entry('schul_ag'); + + // Fehlt etwas Bedingtes, wird es angemahnt: Schulart bei Grundschule, Laufzeit und Häufigkeit bei Schul-AG. + try { + $this->send($entry, $values); + $this->fail('Erwartet: Zurückweisung wegen bedingter Pflichtfelder.'); + } catch (SubmissionException $e) { + $this->assertEqualsCanonicalizing(['schulart', 'laufzeit', 'haeufigkeit'], array_keys($e->fields)); + } + + $this->assertSame(0, Inquiry::query()->count()); + + $values += ['schulart' => 'gs', 'laufzeit' => 'halbjahr', 'haeufigkeit' => 'woechentlich']; + $this->send($entry, $values); + + $answers = collect(Inquiry::query()->firstOrFail()->answers)->keyBy('key'); + $this->assertSame('Ein Schulhalbjahr', $answers['laufzeit']['display']); + $this->assertArrayNotHasKey('traeger_name', $answers->all()); + $this->assertSame('Ihr Vorhaben', $answers['alter']['step']); + } + + public function test_a_deviating_provider_and_venue_make_their_fields_required(): void + { + $values = [ + 'anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'kompakt', + 'einrichtung_name' => 'Verein X', 'einrichtungstyp' => 'verein', + 'einrichtung_strasse' => 'Weg 2', 'einrichtung_plz' => '30159', 'einrichtung_ort' => 'Hannover', + 'traeger_abweichend' => 'ja', 'ort_abweichend' => 'ja', + 'alter' => '9', 'anzahl_kinder' => '12', + 'vorname' => 'A', 'nachname' => 'B', 'email' => 'a@example.org', + ]; + + try { + $this->send($this->entry('kurse_workshops'), $values); + $this->fail('Erwartet: Zurückweisung.'); + } catch (SubmissionException $e) { + $this->assertEqualsCanonicalizing(['traeger_name', 'ort_strasse', 'ort_plz', 'ort_ort'], array_keys($e->fields)); + } + } + + public function test_manipulated_issues_options_and_unknown_fields_are_rejected(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $good = ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']; + + foreach ([ + ['anliegen' => 'kurse'] + $good, // Anliegen außerhalb des Einstiegs (nur „allgemein“ zugelassen) + $good + ['unbekannt' => 'x'], // Feld, das es nicht gibt + ['email' => 'kein-mail'] + $good, // ungültiger Wert + ] as $values) { + try { + $this->send($entry, $values); + $this->fail('Erwartet: Zurückweisung für '.json_encode($values)); + } catch (SubmissionException $e) { + $this->assertSame(422, $e->getCode()); + } + } + + $course = $this->entry('kurse_workshops'); + try { + $this->send($course, ['kursformat' => 'gibt_es_nicht'] + $this->infoRequest()); + $this->fail('Erwartet: Zurückweisung eines nicht angebotenen Auswahlwerts.'); + } catch (SubmissionException $e) { + $this->assertArrayHasKey('kursformat', $e->fields); + } + + $this->assertSame(0, Inquiry::query()->count()); + } + + public function test_a_single_allowed_issue_is_not_asked_but_still_recorded(): void + { + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertSame('allgemein', $inquiry->issue_key); + $this->assertNull($inquiry->subissue_key); + } + + public function test_a_second_submission_with_the_same_token_creates_no_second_inquiry(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $token = FormToken::issue($entry->id, $entry->template->published_version_id); + $payload = ['token' => $token, 'values' => ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']]; + + $first = app(InquiryService::class)->submit($entry, $payload); + $second = app(InquiryService::class)->submit($entry, $payload); + + $this->assertTrue($first['created']); + $this->assertFalse($second['created']); + $this->assertSame($first['reference'], $second['reference']); + $this->assertSame(1, Inquiry::query()->count()); + } + + public function test_bots_are_caught_by_the_decoy_field_and_by_a_too_fast_submission(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $values = ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']; + + $result = $this->send($entry, $values, ['website' => 'http://spam.example']); + $this->assertFalse($result['created']); + $this->assertSame(0, Inquiry::query()->count()); + + config(['communication.min_fill_seconds' => 3]); + + try { + $this->send($entry, $values); + $this->fail('Erwartet: zu schnelle Absendung.'); + } catch (SubmissionException $e) { + $this->assertSame(429, $e->getCode()); + } + + $this->travel(5)->seconds(); + $token = FormToken::issue($entry->id, $entry->template->published_version_id); + $this->travel(5)->seconds(); + $this->assertTrue(app(InquiryService::class)->submit($entry, ['token' => $token, 'values' => $values])['created']); + } + + public function test_a_forged_or_foreign_token_is_refused(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $other = $this->entry('kooperation'); + + foreach (['x', '', FormToken::issue($other->id, $other->template->published_version_id)] as $token) { + try { + app(InquiryService::class)->submit($entry, ['token' => $token, 'values' => ['name' => 'a', 'email' => 'a@example.org', 'nachricht' => 'b']]); + $this->fail('Erwartet: Token abgelehnt.'); + } catch (SubmissionException $e) { + $this->assertSame(419, $e->getCode()); + } + } + } + + public function test_the_internal_notification_is_sent_to_the_recipients_without_personal_data(): void + { + Mail::fake(); + CommunicationSettings::current()->update(['recipients' => ['team@example.org']]); + + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira Geheim', 'email' => 'mira@example.org', 'nachricht' => 'Vertraulich']); + + Mail::assertSent(InquiryReceived::class, function (InquiryReceived $mail): bool { + $text = $mail->render(); + + return $mail->hasTo('team@example.org') + && ! str_contains($text, 'Mira Geheim') + && ! str_contains($text, 'mira@example.org') + && ! str_contains($text, 'Vertraulich') + && str_contains($text, $mail->inquiry->reference); + }); + + $this->assertNotNull(Inquiry::query()->firstOrFail()->notified_at); + } + + public function test_a_failing_mail_server_does_not_lose_the_inquiry(): void + { + CommunicationSettings::current()->update(['recipients' => ['team@example.org']]); + Mail::shouldReceive('to')->andThrow(new \RuntimeException('smtp down')); + + $result = $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $this->assertTrue($result['created']); + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertNull($inquiry->notified_at); + $this->assertStringContainsString('smtp down', (string) $inquiry->notification_error); + } + + public function test_missing_recipients_are_recorded_instead_of_silently_dropped(): void + { + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $this->assertStringContainsString('keine Empfänger', (string) Inquiry::query()->firstOrFail()->notification_error); + } + + public function test_changing_the_catalog_or_republishing_never_reinterprets_an_old_inquiry(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $this->send($entry, ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + InquiryField::query()->where('key', 'nachricht')->update(['label' => 'Etwas ganz anderes']); + $template = $entry->template; + app(Publisher::class)->publishTemplate($template, null, 'Neue Bezeichnung'); + + $inquiry = Inquiry::query()->firstOrFail(); + $label = collect($inquiry->answers)->firstWhere('key', 'nachricht')['label']; + $this->assertSame('Ihre Nachricht', $label); + $this->assertSame(1, $inquiry->templateVersion->version); + $this->assertSame(2, $template->fresh()->publishedVersion->version); + } + + public function test_a_draft_stays_invisible_until_the_template_is_deliberately_published(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $template = $entry->template; + $version = $template->publishedVersion; + + $draft = $template->draft; + $draft['texts']['heading'] = 'Ganz neue Überschrift'; + $template->update(['draft' => $draft]); + + $this->assertTrue($template->fresh()->hasUnpublishedChanges()); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Schreiben Sie uns', $delivered['form']['texts']['heading']); + + app(Publisher::class)->publishTemplate($template); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Ganz neue Überschrift', $delivered['form']['texts']['heading']); + + // Rückkehr zur früheren Fassung. + app(Publisher::class)->restoreVersion($template->fresh(), $version); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Schreiben Sie uns', $delivered['form']['texts']['heading']); + } + + public function test_published_versions_are_immutable(): void + { + $version = $this->entry('allgemeiner_kontakt')->template->publishedVersion; + + $version->definition = ['v' => 1]; + $this->assertFalse($version->save()); + $this->assertFalse($version->delete()); + } + + public function test_an_entry_can_only_be_published_against_a_published_template_and_a_fitting_configuration(): void + { + $template = InquiryTemplate::query()->create(['key' => 'neu', 'name' => 'Neu', 'draft' => InquiryTemplate::emptyDraft()]); + $entry = InquiryEntry::query()->create(['key' => 'x', 'name' => 'X', 'template_id' => $template->id, 'config' => InquiryEntry::emptyConfig()]); + + try { + app(Publisher::class)->publishEntry($entry); + $this->fail('Erwartet: Vorlage nicht veröffentlicht.'); + } catch (ValidationException $e) { + $this->assertStringContainsString('noch nicht veröffentlicht', $e->errors()['config'][0]); + } + + $good = $this->entry('kurse_workshops'); + $good->config = array_merge((array) $good->config, ['defaults' => ['kursformat' => 'gibt_es_nicht']]); + $this->expectException(ValidationException::class); + app(Publisher::class)->publishEntry($good); + } + + public function test_publishing_a_template_is_blocked_when_the_draft_is_invalid_and_names_the_problems(): void + { + $template = $this->entry('kurse_workshops')->template; + $draft = $template->draft; + // Bedingung verweist auf ein Feld, das erst nach dem Ziel steht. + $draft['rules'][] = ['effect' => 'show', 'target' => 'field:kursformat', 'match' => 'all', 'conditions' => [['source' => 'einrichtungstyp', 'op' => 'eq', 'values' => ['verein']]], 'value' => null]; + $template->update(['draft' => $draft]); + + try { + app(Publisher::class)->publishTemplate($template); + $this->fail('Erwartet: Zurückweisung.'); + } catch (ValidationException $e) { + $this->assertStringContainsString('vor ihrem Ziel stehen', implode(' ', $e->errors()['draft'])); + } + + $this->assertSame(1, InquiryTemplateVersion::query()->where('template_id', $template->id)->count()); + } + + public function test_the_evaluator_shows_groups_and_skips_steps_from_the_choice(): void + { + $entry = $this->entry('kurse_workshops'); + $delivered = app(InquiryService::class)->deliver($entry); + $form = $delivered['form']; + $evaluator = app(FormEvaluator::class); + + $info = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursinfo']); + $this->assertFalse($info['steps']['skurs2']); + $this->assertFalse($info['fields']['einrichtung_name']); + $this->assertTrue($info['fields']['region']); + + $plan = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag', 'ort_abweichend' => 'ja']); + $this->assertTrue($plan['steps']['skurs2']); + $this->assertTrue($plan['groups']['schul_ag']); + $this->assertTrue($plan['groups']['ort_angaben']); + $this->assertFalse($plan['groups']['traeger_angaben']); + $this->assertFalse($plan['fields']['region']); + + // Wechsel des Formats blendet die Zusatzfragen wieder aus. + $other = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'kompakt']); + $this->assertFalse($other['groups']['schul_ag']); + } + + public function test_an_entry_can_limit_the_offered_issues_and_preselect_values(): void + { + $factory = app(FormFactory::class); + $definition = $this->entry('kurse_workshops')->template->publishedVersion->definition; + + $form = $factory->effective($definition, ['allowed_subissues' => ['kursvorhaben'], 'defaults' => ['kursformat' => 'schul_ag', 'anliegen' => 'kurse', 'nonsens' => 'x']]); + + $this->assertSame(['kursvorhaben'], array_column($form['issues'][0]['children'], 'key')); + $this->assertEquals(['kursformat' => 'schul_ag', 'anliegen' => 'kurse'], $form['defaults']); + $this->assertContains('unteranliegen', $form['controls']); + } + + public function test_the_example_schul_ag_entry_preselects_the_format(): void + { + $delivered = app(InquiryService::class)->deliver($this->entry('schul_ag')); + + $this->assertSame('schul_ag', $delivered['form']['defaults']['kursformat']); + $this->assertSame('wizard', $delivered['form']['mode']); + $this->assertSame('Schul-AG anfragen', $delivered['form']['texts']['heading']); + } + + public function test_a_withdrawn_or_archived_entry_is_not_delivered(): void + { + $entry = $this->entry('kooperation'); + app(Publisher::class)->withdrawEntry($entry); + + $this->assertNull(app(InquiryService::class)->deliver($entry->fresh())); + } +} diff --git a/tests/Feature/CommunicationPublicTest.php b/tests/Feature/CommunicationPublicTest.php new file mode 100644 index 0000000..2fe234b --- /dev/null +++ b/tests/Feature/CommunicationPublicTest.php @@ -0,0 +1,268 @@ + 0]); + app(ExampleConfiguration::class)->install(); + } + + private function entry(string $key): InquiryEntry + { + return InquiryEntry::query()->where('key', $key)->firstOrFail(); + } + + private function pageWith(string $path, ?InquiryEntry $entry, string $anchor = 'anfrage'): Page + { + $page = Page::query()->create(['path' => $path]); + $revision = app(PageService::class)->saveRevision($page, [[ + 'name' => 'Anfrage', 'anchor' => $anchor, 'layout' => 'u4', + 'slots' => [['type' => 'inquiry', 'v' => 1, 'variant' => 'standard', 'data' => [], 'refs' => ['entry' => $entry?->id]]], + ]], null, null, null); + app(PageService::class)->publish($page, $revision); + + return $page->fresh(); + } + + public function test_the_definition_contains_the_form_a_token_and_the_first_state_but_no_rules(): void + { + $entry = $this->entry('schul_ag'); + + $response = $this->getJson(route('inquiry.definition', $entry))->assertOk(); + $response->assertHeader('Cache-Control'); + + $json = $response->json(); + $this->assertSame('wizard', $json['mode']); + $this->assertSame('Schul-AG anfragen', $json['texts']['heading']); + $this->assertSame('schul_ag', $json['defaults']['kursformat']); + $this->assertNotEmpty($json['token']); + $this->assertNotEmpty($json['csrf']); + $this->assertArrayNotHasKey('rules', $json); + $this->assertArrayNotHasKey('purpose', $json['fields']['email']); + } + + public function test_the_first_state_follows_the_preselection(): void + { + $json = $this->getJson(route('inquiry.definition', $this->entry('schul_ag')))->json(); + + $this->assertTrue($json['state']['steps']['skurs2']); + $this->assertTrue($json['state']['groups']['schul_ag']); + $this->assertSame('kursvorhaben', $json['state']['subissue']); + } + + public function test_an_unpublished_or_archived_entry_is_not_delivered(): void + { + $entry = $this->entry('kooperation'); + app(Publisher::class)->withdrawEntry($entry); + + $this->getJson(route('inquiry.definition', $entry))->assertNotFound(); + $this->postJson(route('inquiry.state', $entry), ['values' => []])->assertNotFound(); + $this->postJson(route('inquiry.submit', $entry), ['values' => [], 'token' => 'x'])->assertStatus(419); + } + + public function test_the_server_decides_which_fields_are_visible(): void + { + $entry = $this->entry('kurse_workshops'); + + $this->postJson(route('inquiry.state', $entry), ['values' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursinfo']]) + ->assertOk() + ->assertJsonPath('steps.skurs2', false) + ->assertJsonPath('fields.region', true) + ->assertJsonPath('fields.einrichtung_name', false); + + $this->postJson(route('inquiry.state', $entry), ['values' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag', 'ort_abweichend' => 'ja']]) + ->assertOk() + ->assertJsonPath('groups.schul_ag', true) + ->assertJsonPath('groups.ort_angaben', true) + ->assertJsonPath('required.laufzeit', true); + + $this->postJson(route('inquiry.state', $entry), ['values' => 'kaputt'])->assertStatus(422); + } + + public function test_a_visitor_sends_an_inquiry_without_an_account(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $token = $this->getJson(route('inquiry.definition', $entry))->json('token'); + + $this->postJson(route('inquiry.submit', $entry), [ + 'token' => $token, + 'source' => '/kontakt', + 'values' => ['name' => 'Mira Beispiel', 'email' => 'mira@example.org', 'nachricht' => 'Hallo zusammen'], + ])->assertCreated()->assertJsonStructure(['reference']); + + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertSame('/kontakt', $inquiry->source_path); + $this->assertSame('Mira Beispiel', $inquiry->contact_name); + $this->assertNull(Inquiry::query()->first()->templateVersion->published_by); + } + + public function test_validation_errors_name_the_fields_and_keep_the_inquiry_out_of_the_database(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $token = $this->getJson(route('inquiry.definition', $entry))->json('token'); + + $this->postJson(route('inquiry.submit', $entry), ['token' => $token, 'values' => ['name' => 'Mira', 'email' => 'falsch']]) + ->assertStatus(422) + ->assertJsonPath('fields.email', 'Bitte geben Sie eine gültige E-Mail-Adresse ein.') + ->assertJsonPath('fields.nachricht', 'Bitte füllen Sie dieses Feld aus.'); + + $this->assertSame(0, Inquiry::query()->count()); + } + + public function test_submissions_are_rate_limited_per_address(): void + { + RateLimiter::clear('inq-m|127.0.0.1'); + $entry = $this->entry('allgemeiner_kontakt'); + $token = $this->getJson(route('inquiry.definition', $entry))->json('token'); + $values = ['values' => ['name' => 'M', 'email' => 'x', 'nachricht' => 'y'], 'token' => $token]; + + $statuses = []; + for ($i = 0; $i < 7; $i++) { + $statuses[] = $this->postJson(route('inquiry.submit', $entry), $values)->status(); + } + + $this->assertContains(429, $statuses); + $this->assertSame(422, $statuses[0]); + } + + public function test_the_widget_mounts_a_published_entry_on_two_pages_without_any_form_content(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $this->pageWith('/kontakt', $entry); + $this->pageWith('/hilfe', $entry); + + foreach (['/kontakt', '/hilfe'] as $path) { + $html = $this->get($path)->assertOk() + ->assertSee('data-inquiry', false) + ->assertSee('data-definition-url="'.route('inquiry.definition', $entry).'"', false) + ->assertSee('id="anfrage"', false) + ->getContent(); + + // Nichts aus der Konfiguration steht in der gespeicherten Seite. + $this->assertStringNotContainsString('Schreiben Sie uns', $html); + $this->assertStringNotContainsString('nachricht', $html); + } + + // 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']['reasons']); + } + + public function test_a_central_change_reaches_every_page_without_touching_the_pages(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $this->pageWith('/kontakt', $entry); + $revisionId = Page::query()->where('path', '/kontakt')->value('published_revision_id'); + + $template = $entry->template; + $draft = $template->draft; + $draft['texts']['heading'] = 'Neue zentrale Überschrift'; + $template->update(['draft' => $draft]); + + $this->getJson(route('inquiry.definition', $entry))->assertJsonPath('texts.heading', 'Schreiben Sie uns'); + + app(Publisher::class)->publishTemplate($template); + + $this->getJson(route('inquiry.definition', $entry))->assertJsonPath('texts.heading', 'Neue zentrale Überschrift'); + $this->assertSame($revisionId, Page::query()->where('path', '/kontakt')->value('published_revision_id'), 'Die Seite bleibt unverändert.'); + } + + public function test_a_withdrawn_entry_leaves_the_page_valid_and_the_public_view_empty(): void + { + $entry = $this->entry('kooperation'); + $this->pageWith('/partner', $entry); + app(Publisher::class)->withdrawEntry($entry); + + $this->get('/partner')->assertOk()->assertDontSee('data-inquiry', false); + } + + public function test_the_page_editor_rejects_an_unknown_entry_but_a_withdrawn_one_never_blocks_saving(): void + { + $entry = $this->entry('kooperation'); + $page = $this->pageWith('/partner', $entry); + $widget = fn (int $id): array => [['layout' => 'u4', 'slots' => [['type' => 'inquiry', 'v' => 1, 'variant' => 'standard', 'data' => [], 'refs' => ['entry' => $id]]]]]; + + try { + app(PageService::class)->saveRevision($page, $widget(999999), null, null, null); + $this->fail('Erwartet: unbekannter Einstieg abgelehnt.'); + } catch (ValidationException $e) { + $this->assertNotEmpty($e->errors()); + } + + // Zurückgezogen oder archiviert: die Seite bleibt speicherbar (nur die Auswahl im Editor bietet ihn nicht mehr an). + app(Publisher::class)->withdrawEntry($entry); + $entry->forceFill(['archived_at' => now()])->save(); + + $this->assertNotNull(app(PageService::class)->saveRevision($page, $widget($entry->id), 'Anderer Titel', null, null)); + } + + public function test_the_notification_link_is_built_from_the_web_request_not_inside_the_worker(): void + { + Queue::fake(); + $entry = $this->entry('allgemeiner_kontakt'); + $token = $this->getJson(route('inquiry.definition', $entry))->json('token'); + + $this->postJson('http://anfrage-test.example:3011/anfrage/'.$entry->id.'/senden', [ + 'token' => $token, + 'values' => ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo'], + ])->assertCreated(); + + 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_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(['reasons', 'question', 'open_label'], array_map(fn ($field): string => $field->getName(), $type->dataFields())); + $this->assertSame(['entry'], array_keys($type->refRules())); + $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 + { + $entry = $this->entry('kooperation'); + $page = $this->pageWith('/partner', $entry); + app(Publisher::class)->withdrawEntry($entry); + + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + $this->actingAs($editor, 'staff') + ->get(route('pages.preview', $page->publishedRevision)) + ->assertOk() + ->assertSee('nicht veröffentlicht', false); + } +} diff --git a/tests/Feature/CommunicationPurgeTest.php b/tests/Feature/CommunicationPurgeTest.php new file mode 100644 index 0000000..68a8616 --- /dev/null +++ b/tests/Feature/CommunicationPurgeTest.php @@ -0,0 +1,56 @@ + 0]); + $entry = InquiryEntry::query()->where('key', 'allgemeiner_kontakt')->firstOrFail(); + $result = app(InquiryService::class)->submit($entry, [ + 'token' => FormToken::issue($entry->id, $entry->template->published_version_id), + 'values' => ['name' => 'Mira', 'email' => $email, 'nachricht' => 'Hallo'], + ]); + + return Inquiry::query()->where('reference', $result['reference'])->firstOrFail(); + } + + public function test_nothing_is_deleted_without_a_retention_period(): void + { + app(ExampleConfiguration::class)->install(); + $old = $this->inquiry('alt@example.org'); + $old->forceFill(['created_at' => now()->subYears(5)])->save(); + + $this->artisan('communication:purge')->expectsOutputToContain('nichts gelöscht')->assertSuccessful(); + + $this->assertSame(1, Inquiry::query()->count()); + } + + public function test_only_inquiries_older_than_the_retention_period_are_deleted(): void + { + app(ExampleConfiguration::class)->install(); + CommunicationSettings::current()->update(['retention_months' => 12]); + $old = $this->inquiry('alt@example.org'); + $old->forceFill(['created_at' => now()->subMonths(13)])->save(); + $this->inquiry('neu@example.org'); + + $this->artisan('communication:purge', ['--pretend' => true])->expectsOutputToContain('1 Anfragen wären älter')->assertSuccessful(); + $this->assertSame(2, Inquiry::query()->count()); + + $this->artisan('communication:purge')->expectsOutputToContain('1 Anfragen gelöscht')->assertSuccessful(); + + $this->assertSame(['neu@example.org'], Inquiry::query()->pluck('contact_email')->all()); + } +} 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']); + } +} diff --git a/tests/Unit/WidgetRegistryTest.php b/tests/Unit/WidgetRegistryTest.php index a53ea75..62619a9 100644 --- a/tests/Unit/WidgetRegistryTest.php +++ b/tests/Unit/WidgetRegistryTest.php @@ -28,7 +28,7 @@ public function test_all_configured_widgets_are_registered_with_complete_contrac $types = $this->registry()->all(); $this->assertSame( - ['hero', 'heading', 'prose', 'notice', 'image_text', 'cards', 'features', 'catalog_cards', 'topic_card', 'media_card', 'program_card', 'call_to_action', 'faq', 'shop_products'], + ['hero', 'heading', 'prose', 'notice', 'image_text', 'cards', 'features', 'catalog_cards', 'topic_card', 'media_card', 'program_card', 'call_to_action', 'faq', 'shop_products', 'inquiry'], array_keys($types), ); @@ -39,7 +39,8 @@ public function test_all_configured_widgets_are_registered_with_complete_contrac $this->assertGreaterThanOrEqual(1, $type->version()); $this->assertNotEmpty($type->variants()); $this->assertArrayHasKey($type->defaultVariant(), $type->variants()); - $this->assertNotEmpty($type->dataRules()); + // Ein Widget darf allein aus einem Verweis bestehen (zum Beispiel „inquiry“: nur die Kennung eines Anfrage-Einstiegs). + $this->assertNotEmpty(array_merge($type->dataRules(), $type->refRules())); $this->assertNotEmpty($type->editorSchema()); $this->assertTrue(view()->exists($type->view()), "Ansicht für $key fehlt"); } diff --git a/vite.config.js b/vite.config.js index 9270b47..2fe327e 100644 --- a/vite.config.js +++ b/vite.config.js @@ -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.