diff --git a/app/Domain/Cms/Widgets/Types/InquiryWidget.php b/app/Domain/Cms/Widgets/Types/InquiryWidget.php new file mode 100644 index 0000000..ce1469d --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/InquiryWidget.php @@ -0,0 +1,118 @@ + 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art stehen auf breiten Plätzen nebeneinander']; + } + + public function schematic(): array + { + return [[6, 4, 24, 3, 'ink'], [6, 10, 48, 5, 'line'], [6, 18, 48, 5, 'line'], [6, 26, 18, 5, 'accent']]; + } + + public function dataRules(): array + { + return []; + } + + public function dataFields(): array + { + return []; + } + + public function refRules(): array + { + return [ + 'entry' => [ + 'required', + 'integer', + Rule::exists('inquiry_entries', 'id')->where(fn ($query) => $query->whereNotNull('published_at')->whereNull('archived_at')), + ], + ]; + } + + public function refFields(): array + { + return [ + Select::make('entry') + ->label('Anfrage-Einstieg') + ->required() + ->searchable() + ->options(fn (): array => InquiryEntry::query()->live()->orderBy('name')->pluck('name', 'id')->all()) + ->helperText('Nur veröffentlichte Einstiege stehen zur Auswahl. Anliegen, Felder, Bedingungen, Texte und Empfänger pflegst du in der Kommunikationsverwaltung („Kommunikation → Anfrage-Einstiege“), nicht hier. Eine Änderung dort gilt sofort auf allen Seiten, die diesen Einstieg verwenden.'), + Text::make('Ein Einstieg ist die konkrete Nutzungsvariante einer Anfragevorlage. Mehrere Seiten können denselben Einstieg einbinden.'), + ]; + } + + public function editorSchema(): array + { + return parent::editorSchema(); + } + + public function resolve(array $widget, RenderContext $context): array + { + $id = $widget['refs']['entry'] ?? null; + $entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null; + + return ['entry' => $entry, 'entryLive' => $entry?->isLive() ?? false]; + } + + public function summary(array $widget): string + { + $id = $widget['refs']['entry'] ?? null; + $name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null; + + return $name !== null ? 'Anfrage: '.$name : 'Kein Anfrage-Einstieg gewählt'; + } +} 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/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/Keys.php b/app/Domain/Communication/Keys.php index a9398f2..b7f5750 100644 --- a/app/Domain/Communication/Keys.php +++ b/app/Domain/Communication/Keys.php @@ -45,4 +45,45 @@ public static function from(string $label, array $taken = []): string 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/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..26fbac7 --- /dev/null +++ b/app/Filament/Pages/KommunikationEinstellungen.php @@ -0,0 +1,176 @@ +|null */ + public ?array $data = []; + + public static function canAccess(): bool + { + return CommunicationAccess::inbox(); + } + + public function getTitle(): string|Htmlable + { + return 'Kommunikation: Einstellungen'; + } + + public function getSubheading(): string|Htmlable|null + { + return 'Wer bei einer neuen Anfrage benachrichtigt wird und wie lange Anfragen aufbewahrt werden.'; + } + + public function mount(): void + { + $settings = CommunicationSettings::current(); + + $this->form->fill([ + 'recipients' => implode("\n", (array) $settings->recipients), + 'retention_months' => $settings->retention_months, + ]); + } + + public function form(Schema $schema): Schema + { + return $schema + ->components([ + Section::make('Benachrichtigung')->schema([ + Textarea::make('recipients')->label('Empfänger der internen Benachrichtigung')->rows(4) + ->helperText('Eine E-Mail-Adresse je Zeile. Die Benachrichtigung nennt nur Kennzeichen und Anliegen, nie Kontaktdaten oder Antworten. Ohne Empfänger werden Anfragen trotzdem gespeichert; der Posteingang weist dann auf die fehlende Benachrichtigung hin.') + ->rule(fn (): \Closure => function (string $attribute, mixed $value, \Closure $fail): void { + foreach (self::lines((string) $value) as $address) { + if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) { + $fail('„'.$address.'“ ist keine gültige E-Mail-Adresse.'); + + return; + } + } + + if (count(self::lines((string) $value)) > 10) { + $fail('Bitte höchstens zehn Empfänger.'); + } + }), + ]), + Section::make('Aufbewahrung')->schema([ + TextInput::make('retention_months')->label('Anfragen löschen nach … Monaten')->numeric()->minValue(1)->maxValue(120) + ->helperText('Leer: Anfragen werden nicht automatisch gelöscht. Der Befehl „php artisan communication:purge“ löscht Anfragen, die älter sind. Einzelne Anfragen lassen sich jederzeit im Posteingang löschen. Die Dauer ist mit dem Datenschutzkonzept abzustimmen.'), + ]), + ]) + ->statePath('data'); + } + + public function content(Schema $schema): Schema + { + return $schema->components([ + Form::make([EmbeddedSchema::make('form')]) + ->id('form') + ->livewireSubmitHandler('save') + ->footer([Actions::make([Action::make('save')->label('Einstellungen speichern')->submit('save')->keyBindings(['mod+s'])])]), + ]); + } + + public function save(): void + { + $data = $this->form->getState(); + + CommunicationSettings::current()->update([ + 'recipients' => self::lines((string) ($data['recipients'] ?? '')), + 'retention_months' => filled($data['retention_months'] ?? null) ? (int) $data['retention_months'] : null, + ]); + + Notification::make()->title('Die Einstellungen sind gespeichert.')->success()->send(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('test') + ->label('Testnachricht senden') + ->icon('heroicon-o-envelope') + ->color('gray') + ->requiresConfirmation() + ->modalDescription('Sendet eine Testnachricht an die gespeicherten Empfänger. Sie enthält keine Anfragedaten.') + ->action(function (): void { + $recipients = CommunicationSettings::current()->recipientList(); + + if ($recipients === []) { + Notification::make()->title('Es sind noch keine Empfänger gespeichert.')->warning()->send(); + + return; + } + + try { + Mail::to($recipients)->send(new CommunicationTestMail); + } catch (Throwable $e) { + report($e); + Notification::make()->title('Der Versand ist fehlgeschlagen.')->body($e->getMessage())->danger()->send(); + + return; + } + + Notification::make()->title('Die Testnachricht ist abgesendet.')->body('Der Mailserver hat sie angenommen. Ob sie ankommt, zeigt dein Postfach.')->success()->send(); + }), + Action::make('example') + ->label('Beispielkonfiguration anlegen') + ->icon('heroicon-o-sparkles') + ->color('gray') + ->visible(fn (): bool => ExampleConfiguration::isEmpty()) + ->requiresConfirmation() + ->modalHeading('Beispielkonfiguration anlegen?') + ->modalDescription('Legt Anliegen, Felder, Feldgruppen, vier Anfragevorlagen und fünf Anfrage-Einstiege (Allgemeiner Kontakt, Kurse & Workshops, Schul-AG, Programme & Materialien, Kooperation) an und veröffentlicht sie. Alles lässt sich danach ändern. Das geht nur, solange die Kommunikationsverwaltung noch leer ist.') + ->action(function (): void { + try { + app(ExampleConfiguration::class)->install(CommunicationAccess::user()); + } catch (RuntimeException $e) { + Notification::make()->title($e->getMessage())->danger()->send(); + + return; + } + + Notification::make()->title('Die Beispielkonfiguration ist angelegt und veröffentlicht.')->success()->send(); + $this->redirect(static::getUrl()); + }), + ]; + } + + /** + * @return list + */ + 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..f014c6c --- /dev/null +++ b/app/Filament/Resources/Communication/Fields/InquiryFieldResource.php @@ -0,0 +1,120 @@ + + */ + 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..7992bd3 --- /dev/null +++ b/app/Filament/Resources/Communication/Groups/InquiryFieldGroupResource.php @@ -0,0 +1,80 @@ +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..587e52f --- /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('entry.name')->label('Anfrage-Einstieg')->placeholder('Gelöscht'), + TextEntry::make('source_path')->label('Quellseite')->placeholder('Unbekannt'), + TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i'), + TextEntry::make('reference')->label('Kennzeichen')->copyable(), + TextEntry::make('version')->label('Formularfassung') + ->state(fn (Inquiry $record): string => 'Vorlage „'.($record->templateVersion->template->name ?? '').'“, Fassung '.($record->templateVersion->version ?? '')), + TextEntry::make('notification')->label('Benachrichtigung') + ->state(fn (Inquiry $record): string => $record->notified_at !== null ? 'Gesendet am '.$record->notified_at->format('d.m.Y H:i') : ($record->notification_error ?: 'Noch nicht gesendet')) + ->color(fn (Inquiry $record): ?string => $record->notified_at === null && $record->notification_error !== null ? 'danger' : null), + ]), + Section::make('Antworten')->schema([ + ViewEntry::make('answers')->hiddenLabel()->view('filament.communication.answers'), + ]), + Section::make('Nachricht')->visible(fn (Inquiry $record): bool => filled($record->message))->schema([ + TextEntry::make('message')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']), + ]), + Section::make('Interne Notizen')->schema([ + RepeatableEntry::make('notes')->hiddenLabel()->placeholder('Noch keine Notizen.')->schema([ + TextEntry::make('body')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']), + TextEntry::make('meta')->hiddenLabel()->color('gray') + ->state(fn ($record): string => ($record->author->name ?? 'Unbekannt').' · '.$record->created_at->format('d.m.Y H:i')), + ]), + ]), + ]); + } + + public static function form(Schema $schema): Schema + { + return $schema; + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('reference')->label('Kennzeichen')]); + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiries::route('/'), + 'view' => ViewInquiry::route('/{record}'), + ]; + } +} 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..6f9f185 --- /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'); + + if ($this->anliegen !== 'alle') { + $query->where('issue_key', $this->anliegen); + } + + $inquiries = match ($this->sortierung) { + 'alt' => $query->orderBy('created_at')->orderBy('id')->get(), + 'name' => $query->get()->sortBy(fn (Inquiry $i): string => mb_strtolower($i->contactTitle()), SORT_NATURAL)->values(), + 'status' => $query->get()->sortBy(fn (Inquiry $i): string => array_search($i->status, InquiryStatus::cases(), true).'-'.(PHP_INT_MAX - $i->created_at->getTimestamp()))->values(), + default => $query->orderByDesc('created_at')->orderByDesc('id')->get(), + }; + + $rows = []; + + foreach ($inquiries as $inquiry) { + $url = InquiryResource::getUrl('view', ['record' => $inquiry]); + $failed = $inquiry->notified_at === null && $inquiry->notification_error !== null; + $rows[] = [ + 'schluessel' => 'q'.$inquiry->id, + 'titel' => $inquiry->contactTitle().($inquiry->organisation ? ' · '.$inquiry->organisation : ''), + 'meta' => $inquiry->created_at->format('d.m.Y H:i').' · '.($inquiry->issueTitle() ?: 'Ohne Anliegen').' · '.($inquiry->entry->name ?? 'Einstieg gelöscht'), + 'text' => Str::limit((string) $inquiry->message, 180), + 'suchtext' => implode(' ', array_filter([$inquiry->contact_email, $inquiry->reference, $inquiry->contact_phone])), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + ['label' => $inquiry->status->label(), 'ton' => match ($inquiry->status) { + InquiryStatus::Neu => 'offen', + InquiryStatus::RueckfrageOffen => 'achtung', + InquiryStatus::Erledigt => 'gut', + default => 'neutral', + }], + $failed ? ['label' => 'Benachrichtigung fehlgeschlagen', 'ton' => 'achtung'] : null, + ])), + 'zustand' => array_values(array_filter([$inquiry->status->value, $inquiry->status !== InquiryStatus::Erledigt ? 'offen' : null, $failed ? 'mailfehler' : null])), + 'aktionen' => [['label' => 'Öffnen', 'href' => $url]], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Status', + 'offen' => 'Nicht erledigt', + ...InquiryStatus::options(), + 'mailfehler' => 'Benachrichtigung fehlgeschlagen', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Name, E-Mail, Organisation, Nachricht oder Kennzeichen'; + } + + protected function einheit(): array + { + return ['Anfrage', 'Anfragen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Anfragen', 'text' => 'Sobald jemand über einen Anfrage-Einstieg eine Anfrage sendet, erscheint sie hier.']; + } +} 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..60d1a74 --- /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); + $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..13b4695 --- /dev/null +++ b/app/Filament/Resources/Communication/Issues/InquiryIssueResource.php @@ -0,0 +1,66 @@ +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..6cc7e19 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/InquiryTemplateResource.php @@ -0,0 +1,57 @@ +components(TemplateEditor::schema()); + } + + public static function table(Table $table): Table + { + return $table->columns([TextColumn::make('name')->label('Bezeichnung')]); + } + + public static function getRelations(): array + { + return [VersionsRelationManager::class]; + } + + public static function getPages(): array + { + return [ + 'index' => ListInquiryTemplates::route('/'), + 'edit' => EditInquiryTemplate::route('/{record}'), + ]; + } +} 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..a1ddee0 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/Pages/EditInquiryTemplate.php @@ -0,0 +1,151 @@ +getRecord(); + + if ($template->archived_at !== null) { + return 'Archiviert.'; + } + + if (! $template->isPublished()) { + return 'Noch nicht veröffentlicht. Besucher sehen diese Vorlage erst nach „Veröffentlichen“.'; + } + + $version = $template->publishedVersion; + + return 'Gültig ist Fassung '.$version->version.' (veröffentlicht am '.$version->published_at->format('d.m.Y').').' + .($template->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : ' Der Entwurf entspricht der gültigen Fassung.'); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('preview') + ->label('Vorschau') + ->icon('heroicon-o-eye') + ->color('gray') + ->tooltip('Zeigt den zuletzt gespeicherten Entwurf als Besucher mit allen Bedingungen. Es wird nichts gesendet.') + ->url(fn (): string => route('communication.preview.template', $this->getRecord())) + ->openUrlInNewTab(), + Action::make('check') + ->label('Konfiguration prüfen') + ->color('gray') + ->action(function (): void { + $this->save(shouldRedirect: false, shouldSendSavedNotification: false); + $result = app(TemplateCompiler::class)->compile(TemplateDraft::clean((array) $this->getRecord()->draft)); + + if ($result['errors'] === []) { + Notification::make()->title('Die Konfiguration ist in Ordnung.')->body('Der Entwurf wurde gespeichert und lässt sich veröffentlichen.')->success()->send(); + + return; + } + + Notification::make()->title('Die Konfiguration hat Probleme')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $result['errors'])))->danger()->persistent()->send(); + }), + Action::make('publish') + ->label('Veröffentlichen') + ->color('primary') + ->visible(fn (): bool => $this->getRecord()->archived_at === null) + ->modalHeading('Neue Fassung veröffentlichen') + ->modalSubmitActionLabel('Jetzt veröffentlichen') + ->modalWidth('2xl') + ->schema(fn (): array => [ + Text::make($this->affectedText()), + Textarea::make('note')->label('Bemerkung zur Fassung (optional)')->rows(2)->maxLength(300), + ]) + ->action(function (array $data): void { + $this->save(shouldRedirect: false, shouldSendSavedNotification: false); + + try { + $version = app(Publisher::class)->publishTemplate($this->getRecord(), auth('staff')->user() instanceof User ? auth('staff')->user() : null, $data['note'] ?? null); + } catch (ValidationException $e) { + Notification::make()->title('Die Vorlage lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send(); + + return; + } + + Notification::make()->title('Fassung '.$version->version.' ist veröffentlicht.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getRecord()])); + }), + ...$this->archiveActions(), + ]; + } + + /** Einstiege, die diese Vorlage verwenden und von einer neuen Fassung betroffen sind. */ + private function affectedText(): string + { + $rows = app(Publisher::class)->affected($this->getRecord()); + + if ($rows === []) { + return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Noch kein Anfrage-Einstieg verwendet diese Vorlage.'; + } + + $names = array_map(fn (array $row): string => $row['entry']->name.($row['entry']->published_config !== null ? ' (veröffentlicht)' : ' (Entwurf)'), $rows); + + return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sofort betroffen sind diese Anfrage-Einstiege und damit alle Seiten, die sie einbinden: '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.'; + } + + protected function archiveNote(): string + { + return 'Die Vorlage wird archiviert. Anfrage-Einstiege, die sie verwenden, liefern dann kein Formular mehr aus. Eingegangene Anfragen bleiben unverändert.'; + } + + protected function archiveAttributes(): array + { + return ['archived_at' => now()]; + } + + protected function indexUrl(): string + { + return InquiryTemplateResource::getUrl('index'); + } + + protected function archiveBlocked(): ?string + { + $live = $this->getRecord()->entries()->live()->count(); + + return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit dieser Vorlage. Bitte zuerst zurückziehen oder auf eine andere Vorlage umstellen." : null; + } + + protected function mutateFormDataBeforeSave(array $data): array + { + $data['draft'] = TemplateDraft::clean((array) ($data['draft'] ?? [])); + + return $data; + } + + protected function getRedirectUrl(): ?string + { + return null; + } +} 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..4af9cb9 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/Pages/ListInquiryTemplates.php @@ -0,0 +1,114 @@ +label('Vorlage anlegen') + ->modalHeading('Neue Anfragevorlage') + ->modalDescription('Der Aufbau entsteht danach auf der Seite der Vorlage.') + ->modalSubmitActionLabel('Vorlage anlegen') + ->schema([ + TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120), + Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400), + ]) + ->action(function (array $data): void { + $draft = InquiryTemplate::emptyDraft(); + $draft['steps'] = [['key' => 's'.Str::lower(Str::random(6)), 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]]; + + $template = InquiryTemplate::query()->create([ + 'key' => Keys::from($data['name'], InquiryTemplate::query()->pluck('key')->all()), + 'name' => $data['name'], + 'description' => $data['description'] ?? null, + 'draft' => $draft, + ]); + + Notification::make()->title('Die Vorlage ist angelegt.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template])); + }), + ]; + } + + protected function catalogRows(): array + { + $rows = []; + + foreach (InquiryTemplate::query()->with('publishedVersion')->withCount('entries')->orderBy('name')->get() as $template) { + $url = InquiryTemplateResource::getUrl('edit', ['record' => $template]); + $archived = $template->archived_at !== null; + $published = $template->isPublished(); + $changes = $published && $template->hasUnpublishedChanges(); + $steps = count((array) ($template->draft['steps'] ?? [])); + + $rows[] = [ + 'schluessel' => 't'.$template->id, + 'titel' => $template->name, + 'meta' => 'Anfragevorlage · '.$steps.' '.($steps === 1 ? 'Schritt' : 'Schritte').' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege'), + 'text' => (string) ($template->description ?? ''), + 'symbol' => 'modul', + 'url' => $url, + 'chips' => array_values(array_filter([ + $archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($published + ? ['label' => 'Fassung '.$template->publishedVersion->version.' gültig', 'ton' => 'gut'] + : ['label' => 'Noch nicht veröffentlicht', 'ton' => 'offen']), + $changes ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null, + ])), + 'zustand' => [$archived ? 'archiviert' : ($published ? 'veroeffentlicht' : 'entwurf'), ...($changes ? ['aenderungen'] : [])], + 'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Zustand', + 'veroeffentlicht' => 'Veröffentlicht', + 'entwurf' => 'Noch nicht veröffentlicht', + 'aenderungen' => 'Mit unveröffentlichten Änderungen', + 'archiviert' => 'Archiviert', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Bezeichnung oder Beschreibung'; + } + + protected function einheit(): array + { + return ['Anfragevorlage', 'Anfragevorlagen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Anfragevorlagen', 'text' => 'Mit „Vorlage anlegen“ oben entsteht die erste Vorlage. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.']; + } +} 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..fe20b15 --- /dev/null +++ b/app/Filament/Resources/Communication/Templates/RelationManagers/VersionsRelationManager.php @@ -0,0 +1,78 @@ +getOwnerRecord(); + + return $table + ->columns([ + TextColumn::make('version')->label('Fassung')->prefix('Nr. '), + TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i'), + TextColumn::make('published_by')->label('Von')->state(fn (InquiryTemplateVersion $record): string => (string) User::query()->whereKey($record->published_by)->value('name')), + TextColumn::make('note')->label('Bemerkung')->placeholder('–'), + TextColumn::make('state')->label('Zustand')->badge() + ->color(fn (string $state): string => $state === 'Gültig' ? 'success' : 'gray') + ->state(fn (InquiryTemplateVersion $record): string => $record->id === $this->getOwnerRecord()->published_version_id ? 'Gültig' : 'Früher'), + TextColumn::make('inquiries')->label('Anfragen')->state(fn (InquiryTemplateVersion $record): int => Inquiry::query()->where('template_version_id', $record->id)->count()), + ]) + ->recordActions([ + Action::make('restore') + ->label('Wieder in Kraft setzen') + ->visible(fn (InquiryTemplateVersion $record): bool => $record->id !== $template->fresh()->published_version_id) + ->requiresConfirmation() + ->modalDescription('Besucher sehen danach wieder diese Fassung. Der Entwurf bleibt unverändert. Eingegangene Anfragen bleiben ihrer damaligen Fassung zugeordnet.') + ->action(function (InquiryTemplateVersion $record): void { + try { + app(Publisher::class)->restoreVersion($this->getOwnerRecord(), $record); + } catch (ValidationException $e) { + Notification::make()->title('Nicht möglich')->body(implode(' ', $e->errors()['draft'] ?? []))->danger()->send(); + + return; + } + + Notification::make()->title('Fassung '.$record->version.' ist wieder gültig.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()])); + }), + Action::make('load') + ->label('Als Entwurf laden') + ->color('gray') + ->requiresConfirmation() + ->modalDescription('Der aktuelle Entwurf wird durch den Stand dieser Fassung ersetzt. Veröffentlicht wird dadurch nichts.') + ->action(function (InquiryTemplateVersion $record): void { + $this->getOwnerRecord()->forceFill(['draft' => $record->source])->save(); + Notification::make()->title('Der Entwurf entspricht jetzt Fassung '.$record->version.'.')->success()->send(); + $this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()])); + }), + ]) + ->defaultSort('version', 'desc') + ->paginated(false); + } +} 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..86ad2a1 --- /dev/null +++ b/app/Filament/Support/TemplateEditor.php @@ -0,0 +1,319 @@ + + */ + public static function schema(): array + { + return [ + TextInput::make('name')->label('Bezeichnung der Vorlage')->required()->maxLength(120), + Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400), + Tabs::make('vorlage')->persistTabInQueryString('bereich')->tabs([ + Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure()), + Tab::make('Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()), + Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()), + ]), + ]; + } + + /** + * @return list + */ + private static function structure(): array + { + return [ + Select::make('draft.issues')->label('Unterstützte Anliegen')->multiple()->live() + ->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all()) + ->helperText('Welche Anliegen diese Vorlage kennt. Leer: alle angebotenen. Ein Anfrage-Einstieg kann daraus weiter auswählen.'), + Repeater::make('draft.steps') + ->label('Schritte') + ->helperText('Jeder Schritt ist im mehrstufigen Dialog eine Seite. Im Kompaktformular stehen alle Schritte untereinander. Die Reihenfolge von oben nach unten ist die Reihenfolge der Fragen und zugleich die Reihenfolge, in der Bedingungen ausgewertet werden.') + ->schema([ + Hidden::make('key')->default(fn (): string => 's'.Str::lower(Str::random(6))), + TextInput::make('title')->label('Titel des Schritts')->required()->maxLength(120)->live(onBlur: true), + Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(600), + Repeater::make('items') + ->label('Inhalt des Schritts') + ->schema([ + Select::make('kind')->label('Art')->required()->live()->options([ + 'issue' => 'Auswahl des Anliegens', + 'group' => 'Feldgruppe', + 'field' => 'Einzelnes Feld', + ]), + Select::make('group')->label('Feldgruppe')->searchable()->live() + ->options(fn (): array => InquiryFieldGroup::query()->offered()->orderBy('sort_order')->pluck('name', 'key')->all()) + ->visible(fn (Get $get): bool => $get('kind') === 'group')->required(fn (Get $get): bool => $get('kind') === 'group'), + Select::make('field')->label('Feld')->searchable()->live() + ->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->pluck('name', 'key')->all()) + ->visible(fn (Get $get): bool => $get('kind') === 'field')->required(fn (Get $get): bool => $get('kind') === 'field'), + Toggle::make('required')->label('Pflichtfeld') + ->visible(fn (Get $get): bool => $get('kind') === 'field'), + ]) + ->reorderableWithButtons() + ->addActionLabel('Baustein hinzufügen') + ->itemLabel(fn (array $state): string => match ($state['kind'] ?? null) { + 'issue' => 'Auswahl des Anliegens', + 'group' => 'Feldgruppe: '.(InquiryFieldGroup::query()->where('key', $state['group'] ?? '')->value('name') ?? '…'), + 'field' => 'Feld: '.(InquiryField::query()->where('key', $state['field'] ?? '')->value('name') ?? '…'), + default => 'Neuer Baustein', + }), + ]) + ->reorderableWithButtons() + ->collapsible() + ->addActionLabel('Schritt hinzufügen') + ->live() + ->itemLabel(fn (array $state): string => $state['title'] ?? 'Neuer Schritt'), + ]; + } + + /** + * @return list + */ + private static function rules(): array + { + return [ + Section::make()->schema([ + Repeater::make('draft.rules') + ->label('Regeln') + ->helperText('Eine Regel verändert ein Feld, eine Feldgruppe oder einen Schritt abhängig von Auswahlen davor. Bedingungen können nur auf Felder verweisen, die im Aufbau vor dem Ziel stehen; so entstehen keine Zirkelbezüge.') + ->schema([ + Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS), + Select::make('target')->label('Ziel')->required()->live()->searchable() + ->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['draft'] ?? []), (string) $get('effect'))), + Select::make('value')->label('Vorbelegen mit')->live() + ->options(fn ($livewire, Get $get): array => self::targetValues((array) ($livewire->data['draft'] ?? []), (string) $get('target'))) + ->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'), + Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')->required(), + Repeater::make('conditions') + ->label('Bedingungen') + ->schema([ + Select::make('source')->label('Wenn …')->required()->live()->searchable() + ->options(fn ($livewire): array => self::sources((array) ($livewire->data['draft'] ?? []))), + Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(), + Select::make('values')->label('Wert')->required()->multiple() + ->options(fn ($livewire, Get $get): array => self::sourceValues((array) ($livewire->data['draft'] ?? []), (string) $get('source'))), + ]) + ->minItems(1) + ->addActionLabel('Bedingung hinzufügen'), + ]) + ->collapsible() + ->addActionLabel('Regel hinzufügen') + ->itemLabel(fn (array $state): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').($state['target'] ?? null ? ' → '.self::targetName((string) $state['target']) : '')), + ]), + ]; + } + + /** + * @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 und in den Anfrage-Einstiegen gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext. Ein Anfrage-Einstieg kann einzelne Texte überschreiben.') + ->schema($fields), + ]; + } + + /** + * Felder des Entwurfs in Reihenfolge: [Schlüssel => Name], dazu die Bausteine, aus denen sie stammen. + * + * @param array $draft + * @return array{steps: array, groups: array, fields: array, hasIssue: bool} + */ + private static function inventory(array $draft): array + { + $steps = []; + $groups = []; + $fields = []; + $hasIssue = false; + $names = InquiryField::query()->pluck('name', 'key')->all(); + $groupNames = InquiryFieldGroup::query()->get()->keyBy('key'); + + foreach (array_values((array) ($draft['steps'] ?? [])) as $step) { + $key = (string) ($step['key'] ?? ''); + + if ($key !== '') { + $steps[$key] = (string) (($step['title'] ?? '') ?: 'Schritt'); + } + + foreach (array_values((array) ($step['items'] ?? [])) as $item) { + $kind = $item['kind'] ?? null; + + if ($kind === 'issue') { + $hasIssue = true; + } elseif ($kind === 'group' && isset($groupNames[$item['group'] ?? ''])) { + $group = $groupNames[$item['group']]; + $groups[$group->key] = $group->name; + + foreach ($group->itemList() as $row) { + $fields[$row['field']] = (string) ($names[$row['field']] ?? $row['field']); + } + } elseif ($kind === 'field' && filled($item['field'] ?? null)) { + $fields[$item['field']] = (string) ($names[$item['field']] ?? $item['field']); + } + } + } + + return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue]; + } + + /** + * @param array $draft + * @return array + */ + private static function targets(array $draft, string $effect): array + { + $inventory = self::inventory($draft); + $steps = []; + foreach ($inventory['steps'] as $key => $title) { + $steps["step:$key"] = 'Schritt: '.$title; + } + $groups = []; + foreach ($inventory['groups'] as $key => $name) { + $groups["group:$key"] = 'Feldgruppe: '.$name; + } + $fields = []; + foreach ($inventory['fields'] as $key => $name) { + $fields["field:$key"] = 'Feld: '.$name; + } + + return match ($effect) { + 'skip' => $steps, + 'require', 'preset' => $fields, + 'show', 'hide' => ['Feldgruppen' => $groups, 'Felder' => $fields], + default => ['Schritte' => $steps, 'Feldgruppen' => $groups, 'Felder' => $fields], + }; + } + + private static function targetName(string $target): string + { + [$kind, $key] = array_pad(explode(':', $target, 2), 2, ''); + + return match ($kind) { + 'field' => (string) (InquiryField::query()->where('key', $key)->value('name') ?? $key), + 'group' => (string) (InquiryFieldGroup::query()->where('key', $key)->value('name') ?? $key), + default => $key, + }; + } + + /** + * Felder, auf deren Wert sich eine Bedingung stützen darf. + * + * @param array $draft + * @return array + */ + private static function sources(array $draft): array + { + $inventory = self::inventory($draft); + $sources = []; + + if ($inventory['hasIssue']) { + $sources['anliegen'] = 'Anliegen'; + $sources['unteranliegen'] = 'Unteranliegen'; + } + + $catalog = InquiryField::query()->whereIn('key', array_keys($inventory['fields']))->get()->keyBy('key'); + + foreach ($inventory['fields'] as $key => $name) { + if (isset($catalog[$key]) && $catalog[$key]->type->canControl()) { + $sources[$key] = $name; + } + } + + return $sources; + } + + /** + * @param array $draft + * @return array + */ + private static function sourceValues(array $draft, string $source): array + { + if ($source === 'anliegen' || $source === 'unteranliegen') { + $only = array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')); + $options = []; + + foreach (InquiryIssue::tree() as $issue) { + if ($only !== [] && ! in_array($issue['key'], $only, true)) { + continue; + } + + if ($source === 'anliegen') { + $options[$issue['key']] = $issue['label']; + + continue; + } + + foreach ($issue['children'] as $child) { + $options[$child['key']] = $issue['label'].' › '.$child['label']; + } + } + + return $options; + } + + return self::fieldValues($source); + } + + /** + * @param array $draft + * @return array + */ + private static function targetValues(array $draft, string $target): array + { + return str_starts_with($target, 'field:') ? self::fieldValues(substr($target, 6)) : []; + } + + /** + * @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..85948b0 --- /dev/null +++ b/app/Http/Controllers/InquiryFormController.php @@ -0,0 +1,78 @@ +service->deliver($entry); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + return $this->json([ + ...FormPayload::definition($delivered['form'], $this->evaluator), + 'token' => FormToken::issue($entry->id, $delivered['version']->id), + 'csrf' => csrf_token(), + ]); + } + + public function state(Request $request, InquiryEntry $entry): JsonResponse + { + $delivered = $this->service->deliver($entry); + + if ($delivered === null) { + return $this->json(['message' => 'Dieses Anfrageformular ist zurzeit nicht verfügbar.'], 404); + } + + $values = $request->input('values'); + + if (! is_array($values) || strlen((string) json_encode($values)) > 40000) { + return $this->json(['message' => 'Die Eingaben sind ungültig.'], 422); + } + + return $this->json(FormPayload::state($delivered['form'], $values, $this->evaluator)); + } + + public function submit(Request $request, InquiryEntry $entry): JsonResponse + { + try { + $result = $this->service->submit($entry, [ + 'token' => $request->input('token'), + 'values' => $request->input('values'), + 'website' => $request->input('website'), + 'source' => $request->input('source'), + ]); + } catch (SubmissionException $e) { + return $this->json(['message' => $e->getMessage(), 'fields' => (object) $e->fields], $e->getCode() ?: 422); + } + + return $this->json(['reference' => $result['reference']], 201); + } + + /** + * @param array $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/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 @@ + 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/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..fa9d1e0 --- /dev/null +++ b/resources/css/components/lf-anfrage.css @@ -0,0 +1,444 @@ +/* + * 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; + gap: var(--space-2); +} + +.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; + } +} diff --git a/resources/js/app.js b/resources/js/app.js index 66bb9d5..ce561e0 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -3,6 +3,7 @@ import './site-nav.js'; import './card-clip.js'; import './notice.js'; import './hero-video.js'; +import './inquiry-form.js'; import './member-nav.js'; function attachPlayback(video) { diff --git a/resources/js/inquiry-form.js b/resources/js/inquiry-form.js new file mode 100644 index 0000000..4088aad --- /dev/null +++ b/resources/js/inquiry-form.js @@ -0,0 +1,942 @@ +/* + * 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) { + 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.pending = this.pending.then(async () => { + if (run !== this.sequence) { + return; + } + + try { + 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. + } + }); + + 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; + 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/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..eb82c60 --- /dev/null +++ b/resources/views/components/inquiry/mount.blade.php @@ -0,0 +1,11 @@ +@props(['definitionUrl', 'stateUrl', 'submitUrl' => null, 'preview' => false, 'source' => 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. --}} +
+

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..65bf8ff --- /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/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/widgets/inquiry.blade.php b/resources/views/widgets/inquiry.blade.php new file mode 100644 index 0000000..b3efd3a --- /dev/null +++ b/resources/views/widgets/inquiry.blade.php @@ -0,0 +1,18 @@ +@php + /** @var \App\Domain\Communication\InquiryEntry|null $entry */ +@endphp +@if ($entryLive) + +@elseif ($context->preview) +

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

+@endif diff --git a/routes/web.php b/routes/web.php index c534843..c6d91a5 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,22 @@ Route::post('/stripe/webhook', StripeWebhookController::class)->name('stripe.webhook'); +// Anfrage-Einstiege der Kommunikationsverwaltung (ADR-60): Formular, Auswertung der Bedingungen und Annahme. +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/CommunicationPublicTest.php b/tests/Feature/CommunicationPublicTest.php new file mode 100644 index 0000000..99cb402 --- /dev/null +++ b/tests/Feature/CommunicationPublicTest.php @@ -0,0 +1,243 @@ + 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. + $blocks = Page::query()->where('path', '/kontakt')->firstOrFail()->publishedRevision->blocks; + $this->assertSame(['entry' => $entry->id], $blocks[0]['refs']); + $this->assertSame([], $blocks[0]['data']); + } + + 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_unpublished_entry_and_accepts_a_published_one(): void + { + $page = Page::query()->create(['path' => '/neu']); + $draft = new InquiryEntry(['key' => 'entwurf', 'name' => 'Entwurf', 'template_id' => InquiryTemplate::query()->first()->id, 'config' => InquiryEntry::emptyConfig()]); + $draft->save(); + + $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($draft->id), null, null, null); + $this->fail('Erwartet: unveröffentlichter Einstieg abgelehnt.'); + } catch (ValidationException $e) { + $this->assertNotEmpty($e->errors()); + } + + $this->assertNotNull(app(PageService::class)->saveRevision($page, $widget($this->entry('kooperation')->id), null, null, null)); + } + + public function test_the_widget_offers_nothing_but_the_entry_choice_in_the_cms(): void + { + $type = app(WidgetRegistry::class)->get('inquiry'); + + $this->assertSame([], $type->dataRules()); + $this->assertSame([], $type->dataFields()); + $this->assertSame(['entry'], array_keys($type->refRules())); + $this->assertSame([], $type->settings()); + } + + 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); + } +}