diff --git a/app/Domain/Communication/CommunicationSettings.php b/app/Domain/Communication/CommunicationSettings.php new file mode 100644 index 0000000..8bebe35 --- /dev/null +++ b/app/Domain/Communication/CommunicationSettings.php @@ -0,0 +1,35 @@ + 'array', 'retention_months' => 'integer']; + } + + public static function current(): self + { + return self::query()->first() ?? self::query()->create(['recipients' => []]); + } + + /** + * @return list + */ + public function recipientList(): array + { + return array_values(array_filter( + (array) $this->recipients, + fn (mixed $address): bool => is_string($address) && filter_var($address, FILTER_VALIDATE_EMAIL) !== false, + )); + } +} diff --git a/app/Domain/Communication/ExampleConfiguration.php b/app/Domain/Communication/ExampleConfiguration.php new file mode 100644 index 0000000..9ec15a5 --- /dev/null +++ b/app/Domain/Communication/ExampleConfiguration.php @@ -0,0 +1,268 @@ +exists() && ! InquiryField::query()->exists() && ! InquiryTemplate::query()->exists(); + } + + public function install(?User $by = null): void + { + if (! self::isEmpty()) { + throw new RuntimeException('Die Kommunikationsverwaltung enthält bereits Konfiguration; die Beispiele werden nicht daneben angelegt.'); + } + + DB::transaction(function () use ($by): void { + $this->issues(); + $this->fields(); + $this->groups(); + $templates = $this->templates(); + $this->entries($templates, $by); + }); + } + + private function issues(): void + { + $tree = [ + ['allgemein', 'Allgemeine Informationen', 'Allgemeine Fragen zu Lara & Felix, dem Trainingskonzept oder Sonstiges.', []], + ['kurse', 'Kurse & Workshops', 'Präsenzkurse und individuelle Kursvorhaben.', [ + ['kursinfo', 'Allgemeine Kursinformation', 'Ich möchte mich zunächst informieren.'], + ['kursvorhaben', 'Konkretes Kursvorhaben', 'Ich plane ein konkretes Kursvorhaben.'], + ]], + ['materialien', 'Programme & Materialien', 'Trainingsprogramme, Module, Filmgeschichten, Übungen, Materialien und Nutzungsrechte.', []], + ['kooperation', 'Kooperationen', 'Anfragen möglicher Trainer, Institutionen und anderer Kooperationspartner.', []], + ]; + + foreach ($tree as $i => [$key, $label, $description, $children]) { + $parent = InquiryIssue::query()->create(['key' => $key, 'label' => $label, 'description' => $description, 'sort_order' => ($i + 1) * 10]); + + foreach ($children as $j => [$childKey, $childLabel, $childDescription]) { + InquiryIssue::query()->create(['parent_id' => $parent->id, 'key' => $childKey, 'label' => $childLabel, 'description' => $childDescription, 'sort_order' => ($j + 1) * 10]); + } + } + } + + private function fields(): void + { + $text = fn (string $key, string $name, string $label, ?string $purpose = null, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'text', 'purpose' => $purpose, 'help' => $help]; + $select = fn (string $key, string $name, string $label, array $options, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'select', 'help' => $help, 'options' => array_map(fn (string $k, string $l): array => ['key' => $k, 'label' => $l], array_keys($options), $options)]; + $yesNo = fn (string $key, string $name, string $label): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'boolean']; + $number = fn (string $key, string $name, string $label, int $min = 1, int $max = 1000): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'number', 'settings' => ['min' => $min, 'max' => $max]]; + + $fields = [ + $text('name', 'Name (ein Feld)', 'Ihr Name', 'name'), + ['key' => 'email', 'name' => 'E-Mail-Adresse', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'purpose' => 'email'], + ['key' => 'nachricht', 'name' => 'Nachricht', 'label' => 'Ihre Nachricht', 'type' => 'textarea', 'purpose' => 'nachricht', 'help' => 'Bitte nennen Sie hier keine Namen oder persönlichen Daten einzelner Kinder.'], + $text('vorname', 'Vorname', 'Vorname', 'vorname'), + $text('nachname', 'Nachname', 'Nachname', 'nachname'), + ['key' => 'telefon', 'name' => 'Telefonnummer', 'label' => 'Telefonnummer (optional)', 'type' => 'phone', 'purpose' => 'telefon'], + $text('funktion', 'Funktion / Rolle', 'Ihre Funktion oder Rolle', null, 'Zum Beispiel Schulleitung, Lehrkraft, Vereinsvorstand.'), + $text('region', 'Region / Ort', 'Region oder Ort', null, 'Wo würde das Angebot stattfinden? Die Region genügt.'), + $text('einrichtung_name', 'Name der Einrichtung', 'Name der Schule oder Einrichtung', 'organisation'), + $select('einrichtungstyp', 'Einrichtungstyp', 'Einrichtungstyp', [ + 'grundschule' => 'Grundschule', 'weiterfuehrend' => 'Weiterführende Schule', 'verein' => 'Verein', + 'jugendeinrichtung' => 'Kinder- oder Jugendeinrichtung', 'bildungstraeger' => 'Sonstiger Bildungsträger', 'sonstiges' => 'Sonstiges', + ]), + $select('schulart', 'Schulart', 'Schulart', ['gs' => 'Grundschule', 'foerder' => 'Förderschule', 'gemeinschaft' => 'Gemeinschaftsschule', 'sek' => 'Sekundarschule', 'gym' => 'Gymnasium', 'andere' => 'Andere']), + $text('einrichtung_strasse', 'Straße und Hausnummer (Einrichtung)', 'Straße und Hausnummer'), + $text('einrichtung_plz', 'Postleitzahl (Einrichtung)', 'Postleitzahl'), + $text('einrichtung_ort', 'Ort (Einrichtung)', 'Ort'), + $yesNo('traeger_abweichend', 'Träger weicht von der Einrichtung ab', 'Weicht der Bildungsträger bzw. Auftraggeber von der Einrichtung ab?'), + $text('traeger_name', 'Name des Trägers', 'Name des Trägers oder Auftraggebers'), + $select('traeger_art', 'Art des Trägers', 'Art des Trägers', ['kommune' => 'Kommune oder Land', 'freier' => 'Freier Träger', 'verein' => 'Verein', 'sonstiges' => 'Sonstiges']), + $text('traeger_ansprechpartner', 'Ansprechpartner beim Träger', 'Ansprechpartner beim Träger (optional)'), + $yesNo('ort_abweichend', 'Abweichender Durchführungsort', 'Findet der Kurs an einem anderen Ort statt als in der Einrichtung?'), + $text('ort_strasse', 'Straße und Hausnummer (Durchführungsort)', 'Straße und Hausnummer des Durchführungsorts'), + $text('ort_plz', 'Postleitzahl (Durchführungsort)', 'Postleitzahl des Durchführungsorts'), + $text('ort_ort', 'Ort (Durchführungsort)', 'Ort des Durchführungsorts'), + ['key' => 'ort_hinweise', 'name' => 'Hinweise zum Durchführungsort', 'label' => 'Organisatorische Hinweise zum Ort (optional)', 'type' => 'textarea'], + $text('alter', 'Alter / Altersbereich', 'Alter oder Altersbereich der Kinder', null, 'Zum Beispiel 8 bis 10 Jahre.'), + $text('klassenstufe', 'Klassenstufe', 'Klassenstufe (falls zutreffend)'), + $number('anzahl_kinder', 'Anzahl der Kinder', 'Anzahl der Kinder insgesamt'), + $number('anzahl_gruppen', 'Anzahl der Gruppen oder Klassen', 'Anzahl der Gruppen oder Klassen', 1, 100), + ['key' => 'besonderheiten', 'name' => 'Organisatorische Anforderungen', 'label' => 'Besondere organisatorische Anforderungen (optional)', 'type' => 'textarea', 'help' => 'Bitte keine Angaben zu einzelnen Kindern.'], + $select('kursformat', 'Kursformat', 'Welches Format interessiert Sie?', [ + 'kompakt' => 'Kompakttraining', 'vertiefung' => 'Vertiefungsprogramm', 'schul_ag' => 'Schul-AG', 'unentschieden' => 'Noch unentschieden', + ], 'Kompakttraining: kurzes, individuell abgestimmtes Schultraining mit wenigen Terminen. Vertiefungsprogramm: mehrere aufeinander aufbauende Einheiten über einen längeren Zeitraum. Schul-AG: regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Die Formate sind Arbeitsvorschläge; Termine, Preise und Umfang werden erst im Gespräch festgelegt.'), + ['key' => 'zeitraum', 'name' => 'Geplanter Zeitraum', 'label' => 'Geplanter Zeitraum', 'type' => 'period'], + $text('zeitwuensche', 'Zeitwünsche', 'Zeitwünsche (optional)', null, 'Zum Beispiel Wochentage oder Tageszeiten.'), + $number('einheiten', 'Anzahl geplanter Einheiten', 'Anzahl geplanter Einheiten (optional)', 1, 200), + $select('haeufigkeit', 'Gewünschte Häufigkeit', 'Gewünschte Häufigkeit', ['woechentlich' => 'Einmal pro Woche', 'zweiwoechentlich' => 'Alle zwei Wochen', 'absprache' => 'Nach Absprache']), + $select('laufzeit', 'Laufzeit der Schul-AG', 'Gewünschte Laufzeit', ['halbjahr' => 'Ein Schulhalbjahr', 'schuljahr' => 'Ein Schuljahr', 'absprache' => 'Nach Absprache']), + ['key' => 'kurs_hinweise', 'name' => 'Ergänzende Informationen (Kurs)', 'label' => 'Ergänzende Informationen (optional)', 'type' => 'textarea'], + $select('material_interesse', 'Interesse an Materialien', 'Wofür interessieren Sie sich?', [ + 'programme' => 'Trainingsprogramme', 'module' => 'Module', 'filmgeschichten' => 'Filmgeschichten', 'uebungen' => 'Übungen', + 'materialien' => 'Materialien', 'rechte' => 'Nutzungsrechte', + ]), + $select('koop_art', 'Art der Kooperation', 'Wer sind Sie?', ['trainer' => 'Trainerin oder Trainer', 'institution' => 'Institution', 'sonstiges' => 'Sonstiges']), + $text('koop_organisation', 'Organisation (Kooperation)', 'Organisation (optional)', 'organisation'), + ]; + + foreach ($fields as $i => $field) { + InquiryField::query()->create([ + 'key' => $field['key'], + 'name' => $field['name'], + 'label' => $field['label'], + 'help' => $field['help'] ?? null, + 'type' => $field['type'], + 'options' => $field['options'] ?? null, + 'settings' => $field['settings'] ?? null, + 'purpose' => $field['purpose'] ?? null, + ]); + } + } + + private function groups(): void + { + $groups = [ + ['kontakt_einfach', 'Kontakt (einfach)', 'Ihre Kontaktdaten', [['name', true], ['email', true]]], + ['ansprechpartner', 'Ansprechpartner', 'Ihre Kontaktdaten', [['vorname', true], ['nachname', true], ['email', true], ['telefon', false], ['funktion', false]]], + ['einrichtung', 'Einrichtung', 'Ihre Einrichtung', [['einrichtung_name', true], ['einrichtungstyp', true], ['schulart', false], ['einrichtung_strasse', true], ['einrichtung_plz', true], ['einrichtung_ort', true]]], + ['traeger_frage', 'Träger', 'Bildungsträger oder Auftraggeber', [['traeger_abweichend', true]]], + ['traeger_angaben', 'Trägerangaben', 'Angaben zum Träger', [['traeger_name', true], ['traeger_art', false], ['traeger_ansprechpartner', false]]], + ['ort_frage', 'Durchführungsort', 'Wo soll der Kurs stattfinden?', [['ort_abweichend', true]]], + ['ort_angaben', 'Abweichender Durchführungsort', 'Adresse des Durchführungsorts', [['ort_strasse', true], ['ort_plz', true], ['ort_ort', true], ['ort_hinweise', false]]], + ['kindergruppe', 'Kindergruppe', 'Die Kindergruppe', [['alter', true], ['klassenstufe', false], ['anzahl_kinder', true], ['anzahl_gruppen', false], ['besonderheiten', false]]], + ['kursplanung', 'Kursplanung', 'Ihre Planung', [['zeitraum', false], ['zeitwuensche', false], ['einheiten', false], ['kurs_hinweise', false]]], + ['schul_ag', 'Schul-AG', 'Zur Schul-AG', [['laufzeit', true], ['haeufigkeit', true]]], + ['material', 'Programm- und Materialbezug', 'Ihr Interesse', [['material_interesse', true]]], + ['kooperation', 'Kooperation', 'Zu Ihrer Kooperationsanfrage', [['koop_art', true], ['koop_organisation', false]]], + ]; + + foreach ($groups as $i => [$key, $name, $label, $items]) { + InquiryFieldGroup::query()->create([ + 'key' => $key, + 'name' => $name, + 'label' => $label, + 'items' => array_map(fn (array $row): array => ['field' => $row[0], 'required' => $row[1]], $items), + 'sort_order' => ($i + 1) * 10, + ]); + } + } + + /** + * @return array + */ + private function templates(): array + { + $cond = fn (string $source, string $op, string ...$values): array => ['source' => $source, 'op' => $op, 'values' => $values]; + $rule = fn (string $effect, string $target, array $conditions, ?string $value = null): array => ['effect' => $effect, 'target' => $target, 'match' => 'all', 'conditions' => $conditions, 'value' => $value]; + $group = fn (string $key): array => ['kind' => 'group', 'group' => $key]; + + $general = [ + 'texts' => ['heading' => 'Schreiben Sie uns', 'intro' => 'Wir freuen uns über Ihre Frage.', 'success_text' => 'Danke, wir melden uns in der Regel innerhalb weniger Werktage.'], + 'issues' => ['allgemein'], + 'steps' => [['key' => 'sallg1', 'title' => 'Ihre Nachricht', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $courses = [ + 'texts' => [ + 'heading' => 'Kursanfrage', + 'intro' => 'Beschreiben Sie uns, was Sie planen. Alle Angaben sind unverbindlich; Termine, Preise und Umfang besprechen wir gemeinsam.', + 'privacy_note' => 'Wir verwenden Ihre Angaben ausschließlich, um Ihre Anfrage zu beantworten. Bitte nennen Sie keine Namen oder persönlichen Daten einzelner Kinder.', + 'success_text' => 'Wir haben Ihre Kursanfrage erhalten und melden uns bei Ihnen. Eine Buchung ist damit noch nicht verbunden.', + ], + 'issues' => ['kurse'], + 'steps' => [ + ['key' => 'skurs1', 'title' => 'Ihr Anliegen', 'intro' => null, 'items' => [['kind' => 'issue'], ['kind' => 'field', 'field' => 'kursformat', 'required' => false]]], + ['key' => 'skurs2', 'title' => 'Ihr Vorhaben', 'intro' => 'Einrichtung, Träger, Standort, Zielgruppe und Planung.', 'items' => [ + $group('einrichtung'), $group('traeger_frage'), $group('traeger_angaben'), $group('ort_frage'), $group('ort_angaben'), + $group('kindergruppe'), $group('schul_ag'), $group('kursplanung'), + ]], + ['key' => 'skurs3', 'title' => 'Kontakt und Zusammenfassung', 'intro' => null, 'items' => [ + ['kind' => 'field', 'field' => 'region', 'required' => true], $group('ansprechpartner'), ['kind' => 'field', 'field' => 'nachricht', 'required' => false], + ]], + ], + 'rules' => [ + $rule('show', 'field:kursformat', [$cond('anliegen', 'eq', 'kurse')]), + $rule('skip', 'step:skurs2', [$cond('unteranliegen', 'eq', 'kursinfo')]), + $rule('show', 'group:traeger_angaben', [$cond('traeger_abweichend', 'eq', 'ja')]), + $rule('show', 'group:ort_angaben', [$cond('ort_abweichend', 'eq', 'ja')]), + $rule('show', 'group:schul_ag', [$cond('kursformat', 'eq', 'schul_ag')]), + $rule('show', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]), + $rule('require', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]), + $rule('show', 'field:region', [$cond('unteranliegen', 'eq', 'kursinfo')]), + ], + ]; + + $materials = [ + 'texts' => ['heading' => 'Frage zu Programmen und Materialien', 'intro' => 'Zu Trainingsprogrammen, Modulen, Filmgeschichten, Übungen, Materialien und Nutzungsrechten.'], + 'issues' => ['materialien'], + 'steps' => [['key' => 'smat1', 'title' => 'Ihre Frage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('material'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $cooperation = [ + 'texts' => ['heading' => 'Kooperation anfragen', 'intro' => 'Für Trainerinnen, Trainer, Institutionen und weitere Partner.'], + 'issues' => ['kooperation'], + 'steps' => [['key' => 'skoop1', 'title' => 'Ihre Anfrage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kooperation'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]], + 'rules' => [], + ]; + + $templates = []; + + foreach ([ + ['allgemein', 'Allgemeine Kontaktaufnahme', $general], + ['kursanfragen', 'Kursanfragen', $courses], + ['materialanfragen', 'Materialanfragen', $materials], + ['kooperationsanfragen', 'Kooperationsanfragen', $cooperation], + ] as [$key, $name, $draft]) { + $templates[$key] = InquiryTemplate::query()->create(['key' => $key, 'name' => $name, 'draft' => $draft]); + } + + return $templates; + } + + /** + * @param array $templates + */ + private function entries(array $templates, ?User $by): void + { + foreach ($templates as $template) { + $result = $this->publisher->publishTemplate($template, $by, 'Beispielkonfiguration'); + $template->refresh(); + } + + $entries = [ + ['allgemeiner_kontakt', 'Allgemeiner Kontakt', 'allgemein', ['mode' => 'compact', 'allowed_issues' => ['allgemein']]], + ['kurse_workshops', 'Kurse & Workshops', 'kursanfragen', [ + 'mode' => 'wizard', 'allowed_issues' => ['kurse'], + 'texts' => ['heading' => 'Kurse & Workshops anfragen'], + ]], + ['schul_ag', 'Schul-AG', 'kursanfragen', [ + 'mode' => 'wizard', 'allowed_issues' => ['kurse'], + 'defaults' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag'], + 'texts' => ['heading' => 'Schul-AG anfragen', 'intro' => 'Regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Alle Angaben sind unverbindlich.'], + ]], + ['programme_materialien', 'Programme & Materialien', 'materialanfragen', ['mode' => 'compact', 'allowed_issues' => ['materialien']]], + ['kooperation', 'Kooperation', 'kooperationsanfragen', ['mode' => 'compact', 'allowed_issues' => ['kooperation']]], + ]; + + foreach ($entries as [$key, $name, $template, $config]) { + $entry = InquiryEntry::query()->create([ + 'key' => $key, + 'name' => $name, + 'template_id' => $templates[$template]->id, + 'config' => array_merge(InquiryEntry::emptyConfig(), $config), + ]); + + $this->publisher->publishEntry($entry); + } + } +} diff --git a/app/Domain/Communication/FieldPurpose.php b/app/Domain/Communication/FieldPurpose.php new file mode 100644 index 0000000..3b7132d --- /dev/null +++ b/app/Domain/Communication/FieldPurpose.php @@ -0,0 +1,56 @@ + 'Vorname des Ansprechpartners', + self::LastName => 'Nachname des Ansprechpartners', + self::FullName => 'Name des Ansprechpartners', + self::Email => 'E-Mail-Adresse für Rückfragen', + self::Phone => 'Telefonnummer', + self::Organisation => 'Organisation oder Einrichtung', + self::Message => 'Nachricht', + }; + } + + /** @return list */ + public function types(): array + { + return match ($this) { + self::Email => [FieldType::Email], + self::Phone => [FieldType::Phone], + self::Message => [FieldType::Textarea, FieldType::Text], + default => [FieldType::Text], + }; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/FieldType.php b/app/Domain/Communication/FieldType.php new file mode 100644 index 0000000..f631164 --- /dev/null +++ b/app/Domain/Communication/FieldType.php @@ -0,0 +1,62 @@ + 'Text, einzeilig', + self::Textarea => 'Text, mehrzeilig', + self::Email => 'E-Mail-Adresse', + self::Phone => 'Telefonnummer', + self::Number => 'Zahl', + self::Select => 'Einfachauswahl', + self::Multiselect => 'Mehrfachauswahl', + self::Boolean => 'Ja/Nein', + self::Date => 'Datum', + self::Period => 'Zeitraum (von – bis)', + }; + } + + public function hasOptions(): bool + { + return in_array($this, [self::Select, self::Multiselect], true); + } + + /** Ob Bedingungen auf den Wert dieses Feldes aufbauen dürfen. */ + public function canControl(): bool + { + return $this === self::Select || $this === self::Multiselect || $this === self::Boolean; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/FieldValue.php b/app/Domain/Communication/FieldValue.php new file mode 100644 index 0000000..05388b2 --- /dev/null +++ b/app/Domain/Communication/FieldValue.php @@ -0,0 +1,286 @@ + $field + */ + public static function forRules(array $field, mixed $raw): string|array|null + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + + return match ($type) { + FieldType::Select => self::option($field, $raw), + FieldType::Multiselect => self::options($field, $raw) ?: null, + FieldType::Boolean => self::yesNo($raw), + default => null, + }; + } + + /** + * @param array $field + * @return array{0: mixed, 1: ?string} bereinigter Wert (null = nicht beantwortet) und Fehlermeldung + */ + public static function check(array $field, mixed $raw, bool $required): array + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + $label = (string) ($field['label'] ?? 'Dieses Feld'); + $settings = (array) ($field['settings'] ?? []); + $missing = 'Bitte füllen Sie dieses Feld aus.'; + + if ($type === null) { + return [null, 'Dieses Feld ist nicht verfügbar.']; + } + + if (is_string($raw)) { + $raw = str_replace(["\r\n", "\r"], "\n", $raw); + $raw = preg_replace('/[^\P{C}\n\t]/u', '', $raw) ?? ''; + $raw = trim($raw); + } + + $empty = $raw === null || $raw === '' || $raw === [] || (is_array($raw) && $type === FieldType::Period && trim((string) ($raw['von'] ?? '')) === '' && trim((string) ($raw['bis'] ?? '')) === ''); + + if ($empty) { + return [null, $required ? $missing : null]; + } + + switch ($type) { + case FieldType::Text: + case FieldType::Textarea: + if (! is_string($raw)) { + return [null, 'Bitte geben Sie einen Text ein.']; + } + + $max = (int) ($settings['max_length'] ?? ($type === FieldType::Text ? self::TEXT_MAX : self::TEXTAREA_MAX)); + $max = max(1, min($max, $type === FieldType::Text ? 500 : 8000)); + + if ($type === FieldType::Text) { + $raw = preg_replace('/\s*\n\s*/', ' ', $raw) ?? $raw; + } + + if (mb_strlen($raw) > $max) { + return [null, "Bitte höchstens $max Zeichen."]; + } + + return [$raw, null]; + + case FieldType::Email: + if (! is_string($raw) || mb_strlen($raw) > 200 || filter_var($raw, FILTER_VALIDATE_EMAIL) === false) { + return [null, 'Bitte geben Sie eine gültige E-Mail-Adresse ein.']; + } + + return [$raw, null]; + + case FieldType::Phone: + if (! is_string($raw) || preg_match('/^\+?[0-9][0-9 ()\/.\-]{3,28}[0-9]$/', $raw) !== 1) { + return [null, 'Bitte geben Sie eine gültige Telefonnummer ein.']; + } + + return [$raw, null]; + + case FieldType::Number: + if (is_string($raw)) { + $raw = str_replace(',', '.', $raw); + } + + if (! is_numeric($raw) || is_nan((float) $raw) || is_infinite((float) $raw)) { + return [null, 'Bitte geben Sie eine Zahl ein.']; + } + + $number = $raw + 0; + + if (isset($settings['min']) && $settings['min'] !== '' && $number < (float) $settings['min']) { + return [null, 'Bitte mindestens '.self::plain($settings['min']).'.']; + } + + if (isset($settings['max']) && $settings['max'] !== '' && $number > (float) $settings['max']) { + return [null, 'Bitte höchstens '.self::plain($settings['max']).'.']; + } + + return [$number, null]; + + case FieldType::Select: + $option = self::option($field, $raw); + + return $option === null ? [null, 'Bitte wählen Sie einen der angebotenen Werte.'] : [$option, null]; + + case FieldType::Multiselect: + if (! is_array($raw)) { + return [null, 'Bitte wählen Sie aus den angebotenen Werten.']; + } + + $values = self::options($field, $raw); + + if ($values === [] || count($values) !== count(array_unique(array_filter($raw, 'is_string')))) { + return [null, 'Bitte wählen Sie aus den angebotenen Werten.']; + } + + return [$values, null]; + + case FieldType::Boolean: + $answer = self::yesNo($raw); + + return $answer === null ? [null, 'Bitte antworten Sie mit Ja oder Nein.'] : [$answer, null]; + + case FieldType::Date: + $date = self::date($raw); + + return $date === null ? [null, 'Bitte geben Sie ein gültiges Datum ein.'] : [$date, null]; + + case FieldType::Period: + if (! is_array($raw)) { + return [null, 'Bitte geben Sie einen Zeitraum an.']; + } + + $from = trim((string) ($raw['von'] ?? '')) === '' ? null : self::date($raw['von']); + $to = trim((string) ($raw['bis'] ?? '')) === '' ? null : self::date($raw['bis']); + + if ((trim((string) ($raw['von'] ?? '')) !== '' && $from === null) || (trim((string) ($raw['bis'] ?? '')) !== '' && $to === null)) { + return [null, 'Bitte geben Sie gültige Daten ein.']; + } + + if ($required && ($from === null || $to === null)) { + return [null, 'Bitte geben Sie Beginn und Ende an.']; + } + + if ($from !== null && $to !== null && $to < $from) { + return [null, 'Das Ende liegt vor dem Beginn.']; + } + + return [['von' => $from, 'bis' => $to], null]; + } + + return [null, "$label ist nicht verfügbar."]; + } + + /** + * Lesbare Darstellung eines bereinigten Wertes, wie sie in der Anfrage gespeichert wird. + * + * @param array $field + */ + public static function display(array $field, mixed $value): string + { + $type = FieldType::tryFrom((string) ($field['type'] ?? '')); + $labels = []; + + foreach ((array) ($field['options'] ?? []) as $option) { + $labels[$option['key']] = $option['label']; + } + + return match ($type) { + FieldType::Select => (string) ($labels[$value] ?? $value), + FieldType::Multiselect => implode(', ', array_map(fn (string $key): string => (string) ($labels[$key] ?? $key), (array) $value)), + FieldType::Boolean => $value === 'ja' ? 'Ja' : 'Nein', + FieldType::Date => Carbon::parse((string) $value)->format('d.m.Y'), + FieldType::Period => self::periodText((array) $value), + default => (string) $value, + }; + } + + /** + * @param array $field + */ + private static function option(array $field, mixed $raw): ?string + { + if (! is_string($raw)) { + return null; + } + + foreach ((array) ($field['options'] ?? []) as $option) { + if (($option['key'] ?? null) === $raw) { + return $raw; + } + } + + return null; + } + + /** + * @param array $field + * @return list + */ + private static function options(array $field, mixed $raw): array + { + if (! is_array($raw)) { + return []; + } + + $values = []; + + foreach ($raw as $item) { + $option = self::option($field, $item); + + if ($option === null) { + return []; + } + + $values[$option] = $option; + } + + return array_values($values); + } + + private static function yesNo(mixed $raw): ?string + { + return match (true) { + $raw === true, $raw === 'ja', $raw === '1', $raw === 'true', $raw === 1 => 'ja', + $raw === false, $raw === 'nein', $raw === '0', $raw === 'false', $raw === 0 => 'nein', + default => null, + }; + } + + private static function date(mixed $raw): ?string + { + if (! is_string($raw) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $raw) !== 1) { + return null; + } + + try { + $date = Carbon::createFromFormat('!Y-m-d', $raw); + } catch (Throwable) { + return null; + } + + if ($date === false || $date->format('Y-m-d') !== $raw || $date->year < 1900 || $date->year > 2200) { + return null; + } + + return $raw; + } + + /** + * @param array $value + */ + private static function periodText(array $value): string + { + $from = isset($value['von']) ? Carbon::parse($value['von'])->format('d.m.Y') : null; + $to = isset($value['bis']) ? Carbon::parse($value['bis'])->format('d.m.Y') : null; + + return match (true) { + $from !== null && $to !== null => "$from bis $to", + $from !== null => "ab $from", + $to !== null => "bis $to", + default => '', + }; + } + + private static function plain(mixed $number): string + { + return rtrim(rtrim(number_format((float) $number, 4, ',', ''), '0'), ','); + } +} diff --git a/app/Domain/Communication/FormEvaluator.php b/app/Domain/Communication/FormEvaluator.php new file mode 100644 index 0000000..d665d2e --- /dev/null +++ b/app/Domain/Communication/FormEvaluator.php @@ -0,0 +1,210 @@ + $form wirksames Formular (FormFactory::effective) + * @param array $values Eingaben des Besuchers, nach Feldkennung + * @return array{steps: array, groups: array, fields: array, required: array, presets: array, issue: ?string, subissue: ?string, issue_active: bool} + */ + public function evaluate(array $form, array $values): array + { + $state = ['steps' => [], 'groups' => [], 'fields' => [], 'required' => [], 'presets' => [], 'issue' => null, 'subissue' => null, 'issue_active' => false]; + $context = []; + $byTarget = []; + + foreach ((array) ($form['rules'] ?? []) as $rule) { + $byTarget[$rule['target']][] = $rule; + } + + foreach ((array) $form['steps'] as $step) { + $stepVisible = ! $this->any($byTarget['step:'.$step['key']] ?? [], 'skip', $context); + $state['steps'][$step['key']] = $stepVisible; + + foreach ($step['items'] as $item) { + if ($item['kind'] === 'issue') { + $this->issue($form, $values, $stepVisible, $state, $context); + + continue; + } + + $groupVisible = $stepVisible && ($item['key'] === null || $this->visible($byTarget['group:'.$item['key']] ?? [], $context)); + + if ($item['key'] !== null) { + $state['groups'][$item['key']] = $groupVisible; + } + + foreach ($item['fields'] as $row) { + $key = $row['field']; + $rules = $byTarget["field:$key"] ?? []; + $visible = $groupVisible && $this->visible($rules, $context); + $state['fields'][$key] = $visible; + $state['required'][$key] = $visible && ($row['required'] || $this->any($rules, 'require', $context)); + + if (! $visible) { + continue; + } + + $context[$key] = FieldValue::forRules($form['fields'][$key], $values[$key] ?? null); + + foreach ($rules as $rule) { + if ($rule['effect'] === 'preset' && $this->matches($rule, $context)) { + $state['presets'][$key] ??= (string) $rule['value']; + } + } + } + } + } + + return $state; + } + + /** + * @param array $form + * @param array $values + * @param array $state + * @param array|null> $context + */ + private function issue(array $form, array $values, bool $stepVisible, array &$state, array &$context): void + { + $state['fields']['anliegen'] = false; + $state['fields']['unteranliegen'] = false; + $state['required']['anliegen'] = false; + $state['required']['unteranliegen'] = false; + + if (! $stepVisible) { + return; + } + + $state['issue_active'] = true; + $tops = (array) $form['issues']; + $selected = null; + + if (count($tops) === 1) { + $selected = $tops[0]; + } else { + $state['fields']['anliegen'] = $tops !== []; + $state['required']['anliegen'] = $tops !== []; + $wanted = $values['anliegen'] ?? null; + + foreach ($tops as $top) { + if ($top['key'] === $wanted) { + $selected = $top; + } + } + } + + $context['anliegen'] = $selected['key'] ?? null; + $state['issue'] = $selected['key'] ?? null; + + if ($selected === null) { + return; + } + + $children = (array) $selected['children']; + $child = null; + + if (count($children) === 1) { + $child = $children[0]; + } elseif (count($children) > 1) { + $state['fields']['unteranliegen'] = true; + $state['required']['unteranliegen'] = true; + $wanted = $values['unteranliegen'] ?? null; + + foreach ($children as $candidate) { + if ($candidate['key'] === $wanted) { + $child = $candidate; + } + } + } + + $context['unteranliegen'] = $child['key'] ?? null; + $state['subissue'] = $child['key'] ?? null; + } + + /** + * Sichtbar, wenn keine „Anzeigen“-Regel besteht oder eine zutrifft, und keine „Ausblenden“-Regel zutrifft. + * + * @param list> $rules + * @param array $context + */ + private function visible(array $rules, array $context): bool + { + $show = array_filter($rules, fn (array $rule): bool => $rule['effect'] === 'show'); + + if ($show !== [] && ! $this->any($show, 'show', $context)) { + return false; + } + + return ! $this->any($rules, 'hide', $context); + } + + /** + * @param list> $rules + * @param array $context + */ + private function any(array $rules, string $effect, array $context): bool + { + foreach ($rules as $rule) { + if ($rule['effect'] === $effect && $this->matches($rule, $context)) { + return true; + } + } + + return false; + } + + /** + * @param array $rule + * @param array $context + */ + private function matches(array $rule, array $context): bool + { + $results = []; + + foreach ($rule['conditions'] as $condition) { + $results[] = $this->condition($condition, $context); + } + + if ($results === []) { + return false; + } + + return $rule['match'] === 'any' ? in_array(true, $results, true) : ! in_array(false, $results, true); + } + + /** + * Eine Bedingung auf einem nicht sichtbaren Feld ist nie erfüllt, auch nicht „ist nicht“. + * + * @param array $condition + * @param array $context + */ + private function condition(array $condition, array $context): bool + { + if (! array_key_exists($condition['source'], $context)) { + return false; + } + + $actual = $context[$condition['source']]; + $wanted = (array) $condition['values']; + $hit = is_array($actual) + ? array_intersect($actual, $wanted) !== [] + : ($actual !== null && in_array($actual, $wanted, true)); + + return match ($condition['op']) { + 'eq', 'in' => $hit, + 'neq', 'not_in' => ! $hit, + default => false, + }; + } +} diff --git a/app/Domain/Communication/FormFactory.php b/app/Domain/Communication/FormFactory.php new file mode 100644 index 0000000..3280c59 --- /dev/null +++ b/app/Domain/Communication/FormFactory.php @@ -0,0 +1,179 @@ + $definition aufgelöste Fassung (TemplateCompiler) + * @param array $config Konfiguration des Einstiegs (veröffentlichter Stand oder Entwurf) + * @return array + */ + public function effective(array $definition, array $config): array + { + $allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')); + $allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')); + $tree = []; + + foreach ((array) ($definition['issues'] ?? []) as $issue) { + if ($allowed !== [] && ! in_array($issue['key'], $allowed, true)) { + continue; + } + + $children = (array) $issue['children']; + $chosen = array_values(array_filter($children, fn (array $child): bool => in_array($child['key'], $allowedSub, true))); + $issue['children'] = $chosen !== [] ? $chosen : $children; + $tree[] = $issue; + } + + $form = $definition; + $form['issues'] = $tree; + $form['texts'] = FormTexts::merge((array) ($definition['texts'] ?? []), (array) ($config['texts'] ?? [])); + $form['mode'] = ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact'; + $form['open'] = ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline'; + $form['defaults'] = $this->defaults($form, (array) ($config['defaults'] ?? [])); + $form['controls'] = $this->controls($form); + + return $form; + } + + /** + * @param array $form + * @param array $wanted + * @return array + */ + private function defaults(array $form, array $wanted): array + { + $defaults = []; + $tops = array_column((array) $form['issues'], 'key'); + + if (isset($wanted['anliegen']) && in_array($wanted['anliegen'], $tops, true)) { + $defaults['anliegen'] = $wanted['anliegen']; + + foreach ($form['issues'] as $issue) { + if ($issue['key'] === $wanted['anliegen'] && isset($wanted['unteranliegen']) && in_array($wanted['unteranliegen'], array_column($issue['children'], 'key'), true)) { + $defaults['unteranliegen'] = $wanted['unteranliegen']; + } + } + } + + foreach ((array) $form['fields'] as $key => $field) { + $value = $wanted[$key] ?? null; + + if (! is_string($value) || ! in_array($field['type'], ['select', 'boolean'], true)) { + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + + if (in_array($value, $valid, true)) { + $defaults[$key] = $value; + } + } + + return $defaults; + } + + /** + * Felder, auf deren Änderung das Formular die Regeln neu auswerten lassen muss. + * + * @param array $form + * @return list + */ + private function controls(array $form): array + { + $controls = []; + + foreach ((array) $form['rules'] as $rule) { + foreach ($rule['conditions'] as $condition) { + $controls[$condition['source']] = true; + } + } + + return array_keys($controls); + } + + /** + * Prüft die Konfiguration eines Einstiegs gegen eine Fassung. Leere Liste: gültig. + * + * @param array $definition + * @param array $config + * @return list + */ + public function problems(array $definition, array $config): array + { + $problems = []; + $tops = array_column((array) ($definition['issues'] ?? []), 'key'); + $subs = []; + + foreach ((array) ($definition['issues'] ?? []) as $issue) { + foreach ($issue['children'] as $child) { + $subs[$child['key']] = $issue['key']; + } + } + + $allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')); + $allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')); + + foreach ($allowed as $key) { + if (! in_array($key, $tops, true)) { + $problems[] = "Das Anliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten."; + } + } + + foreach ($allowedSub as $key) { + if (! isset($subs[$key])) { + $problems[] = "Das Unteranliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten."; + } elseif ($allowed !== [] && ! in_array($subs[$key], $allowed, true)) { + $problems[] = "Das Unteranliegen „{$key}“ gehört zu einem Anliegen, das dieser Einstieg nicht zulässt."; + } + } + + if (($definition['has_issue'] ?? false) && $allowed !== [] && array_diff($allowed, $tops) === $allowed) { + $problems[] = 'Keines der zugelassenen Anliegen ist in der Vorlage vorhanden.'; + } + + foreach ((array) ($config['defaults'] ?? []) as $key => $value) { + if ($key === 'anliegen') { + if (! in_array($value, $allowed !== [] ? $allowed : $tops, true)) { + $problems[] = 'Das vorausgewählte Anliegen ist nicht zugelassen oder nicht in der Vorlage.'; + } + + continue; + } + + if ($key === 'unteranliegen') { + if (! isset($subs[$value])) { + $problems[] = 'Das vorausgewählte Unteranliegen ist nicht in der Vorlage.'; + } + + continue; + } + + $field = $definition['fields'][$key] ?? null; + + if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) { + $problems[] = "Die Vorbelegung für „{$key}“ ist in der veröffentlichten Vorlage nicht möglich."; + + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + + if (! in_array($value, $valid, true)) { + $problems[] = "Der vorausgewählte Wert für „{$field['label']}“ gibt es nicht mehr."; + } + } + + if (isset($config['mode']) && ! in_array($config['mode'], ['compact', 'wizard'], true)) { + $problems[] = 'Die Darstellung muss „kompakt“ oder „mehrstufig“ sein.'; + } + + return $problems; + } +} diff --git a/app/Domain/Communication/FormJson.php b/app/Domain/Communication/FormJson.php new file mode 100644 index 0000000..7ce6a0e --- /dev/null +++ b/app/Domain/Communication/FormJson.php @@ -0,0 +1,34 @@ + $value + * @return array + */ + public static function normalize(array $value): array + { + $isList = array_is_list($value); + + foreach ($value as $key => $item) { + if (is_array($item)) { + $value[$key] = self::normalize($item); + } elseif (is_int($item) || is_float($item)) { + $value[$key] = (string) $item; + } elseif (is_bool($item)) { + $value[$key] = $item ? '1' : '0'; + } + } + + if (! $isList) { + ksort($value); + } + + return $value; + } +} diff --git a/app/Domain/Communication/FormTexts.php b/app/Domain/Communication/FormTexts.php new file mode 100644 index 0000000..d45259d --- /dev/null +++ b/app/Domain/Communication/FormTexts.php @@ -0,0 +1,85 @@ + [Bezeichnung in der Verwaltung, Vorgabe, Hilfetext, mehrzeilig] */ + public const FIELDS = [ + 'heading' => ['Überschrift', 'Ihre Anfrage', 'Steht über dem Formular.', false], + 'intro' => ['Beschreibung', '', 'Kurzer Text unter der Überschrift.', true], + 'open_label' => ['Beschriftung der Öffnen-Schaltfläche', 'Anfrage stellen', 'Nur wenn der Einstieg zunächst eine Schaltfläche zeigt.', false], + 'issue_question' => ['Frage nach dem Anliegen', 'Wie können wir Ihnen helfen?', 'Steht über der Auswahl des Anliegens.', false], + 'privacy_note' => ['Hinweis zum Datenschutz', '', 'Steht über der Schaltfläche zum Absenden. Der rechtlich geprüfte Wortlaut wird hier gepflegt; es gibt keine Pflicht-Einwilligungsbox.', true], + 'back_label' => ['Schaltfläche „Zurück“', 'Zurück', null, false], + 'next_label' => ['Schaltfläche „Weiter“', 'Weiter', null, false], + 'summary_title' => ['Überschrift der Zusammenfassung', 'Ihre Angaben im Überblick', 'Letzter Schritt vor dem Absenden im mehrstufigen Dialog.', false], + 'edit_label' => ['Schaltfläche „Ändern“', 'Ändern', 'Steht in der Zusammenfassung neben jedem Schritt.', false], + 'submit_label' => ['Schaltfläche zum Absenden', 'Anfrage senden', null, false], + 'success_title' => ['Bestätigung: Überschrift', 'Vielen Dank für Ihre Anfrage', null, false], + 'success_text' => ['Bestätigung: Text', 'Wir haben Ihre Anfrage erhalten und melden uns bei Ihnen.', null, true], + 'error_text' => ['Meldung bei einem Fehler', 'Ihre Anfrage konnte nicht gesendet werden. Ihre Eingaben bleiben erhalten; bitte versuchen Sie es noch einmal.', null, true], + ]; + + /** + * @return array + */ + public static function defaults(): array + { + $defaults = []; + + foreach (self::FIELDS as $key => $field) { + $defaults[$key] = $field[1]; + } + + return $defaults; + } + + /** + * Setzt Vorgaben und eigene Texte zusammen; leere Eigenwerte fallen auf die Vorgabe zurück. + * + * @param array ...$layers von der schwächsten zur stärksten Schicht + * @return array + */ + public static function merge(array ...$layers): array + { + $texts = self::defaults(); + + foreach ($layers as $layer) { + foreach (array_keys(self::FIELDS) as $key) { + $value = $layer[$key] ?? null; + + if (is_string($value) && trim($value) !== '') { + $texts[$key] = trim($value); + } + } + } + + return $texts; + } + + /** + * Bereinigt eigene Texte aus der Verwaltung: nur bekannte Schlüssel, Länge begrenzt. + * + * @param array $texts + * @return array + */ + public static function clean(array $texts): array + { + $clean = []; + + foreach (self::FIELDS as $key => $field) { + $value = $texts[$key] ?? null; + + if (is_string($value) && trim($value) !== '') { + $clean[$key] = mb_substr(trim($value), 0, $field[3] ? 1500 : 200); + } + } + + return $clean; + } +} diff --git a/app/Domain/Communication/FormToken.php b/app/Domain/Communication/FormToken.php new file mode 100644 index 0000000..b886b26 --- /dev/null +++ b/app/Domain/Communication/FormToken.php @@ -0,0 +1,50 @@ + $entryId, + 'v' => $versionId, + 't' => now()->getTimestamp(), + 'n' => Str::random(32), + ], JSON_THROW_ON_ERROR)); + } + + /** + * @return array{e: int, v: int, t: int, n: string}|null + */ + public static function read(mixed $token): ?array + { + if (! is_string($token) || $token === '' || strlen($token) > 2000) { + return null; + } + + try { + $data = json_decode(Crypt::decryptString($token), true, 4, JSON_THROW_ON_ERROR); + } catch (DecryptException|\JsonException) { + return null; + } + + if (! is_array($data) || ! isset($data['e'], $data['v'], $data['t'], $data['n']) || ! is_string($data['n'])) { + return null; + } + + return ['e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']]; + } +} diff --git a/app/Domain/Communication/Inquiry.php b/app/Domain/Communication/Inquiry.php new file mode 100644 index 0000000..ee354bd --- /dev/null +++ b/app/Domain/Communication/Inquiry.php @@ -0,0 +1,51 @@ + 'array', 'status' => InquiryStatus::class, 'notified_at' => 'datetime']; + } + + public function entry(): BelongsTo + { + return $this->belongsTo(InquiryEntry::class, 'entry_id'); + } + + public function templateVersion(): BelongsTo + { + return $this->belongsTo(InquiryTemplateVersion::class, 'template_version_id'); + } + + public function notes(): HasMany + { + return $this->hasMany(InquiryNote::class)->orderByDesc('created_at')->orderByDesc('id'); + } + + /** Lesbare Bezeichnung des Anliegens, mit Unteranliegen. */ + public function issueTitle(): string + { + return trim(implode(' › ', array_filter([$this->issue_label, $this->subissue_label]))); + } + + public function contactTitle(): string + { + return $this->contact_name ?: ($this->contact_email ?: 'Unbekannt'); + } +} diff --git a/app/Domain/Communication/InquiryEntry.php b/app/Domain/Communication/InquiryEntry.php new file mode 100644 index 0000000..eb447ff --- /dev/null +++ b/app/Domain/Communication/InquiryEntry.php @@ -0,0 +1,64 @@ + 'array', 'published_config' => 'array', 'published_at' => 'datetime', 'archived_at' => 'datetime']; + } + + public function template(): BelongsTo + { + return $this->belongsTo(InquiryTemplate::class, 'template_id'); + } + + public function inquiries(): HasMany + { + return $this->hasMany(Inquiry::class, 'entry_id'); + } + + /** Einstiege, die Besuchern ausgeliefert werden können (Vorlage zusätzlich in isLive() prüfen). */ + public function scopeLive(Builder $query): Builder + { + return $query->whereNotNull('published_at')->whereNull('archived_at')->whereNotNull('published_config'); + } + + public function isLive(): bool + { + return $this->published_at !== null && $this->archived_at === null && $this->published_config !== null + && $this->template?->published_version_id !== null && $this->template->archived_at === null; + } + + public function hasUnpublishedChanges(): bool + { + return $this->published_config === null || FormJson::normalize($this->published_config) !== FormJson::normalize((array) $this->config); + } + + /** + * @return array + */ + public static function emptyConfig(): array + { + return [ + 'mode' => 'compact', + 'open' => 'inline', + 'allowed_issues' => [], + 'allowed_subissues' => [], + 'defaults' => [], + 'texts' => [], + ]; + } +} diff --git a/app/Domain/Communication/InquiryField.php b/app/Domain/Communication/InquiryField.php new file mode 100644 index 0000000..345373a --- /dev/null +++ b/app/Domain/Communication/InquiryField.php @@ -0,0 +1,75 @@ + FieldType::class, + 'purpose' => FieldPurpose::class, + 'options' => 'array', + 'settings' => 'array', + 'active' => 'boolean', + 'archived_at' => 'datetime', + ]; + } + + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + /** + * Auswahlwerte als Liste [{key, label}] in der gepflegten Reihenfolge. + * + * @return list + */ + public function optionList(): array + { + if ($this->type === FieldType::Boolean) { + return [['key' => 'ja', 'label' => 'Ja'], ['key' => 'nein', 'label' => 'Nein']]; + } + + if (! $this->type->hasOptions()) { + return []; + } + + $list = []; + + foreach ((array) $this->options as $option) { + if (is_array($option) && Keys::valid($option['key'] ?? null) && filled($option['label'] ?? null)) { + $list[] = ['key' => $option['key'], 'label' => (string) $option['label']]; + } + } + + return $list; + } + + /** + * Die Beschreibung des Feldes, wie sie in eine Fassung übernommen wird. + * + * @return array + */ + public function snapshot(): array + { + return [ + 'key' => $this->key, + 'label' => $this->label, + 'help' => $this->help, + 'type' => $this->type->value, + 'options' => $this->optionList(), + 'settings' => (array) $this->settings, + 'purpose' => $this->purpose?->value, + ]; + } +} diff --git a/app/Domain/Communication/InquiryFieldGroup.php b/app/Domain/Communication/InquiryFieldGroup.php new file mode 100644 index 0000000..fe22141 --- /dev/null +++ b/app/Domain/Communication/InquiryFieldGroup.php @@ -0,0 +1,40 @@ + 'array', 'active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer']; + } + + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + /** + * @return list + */ + public function itemList(): array + { + $list = []; + + foreach ((array) $this->items as $item) { + if (is_array($item) && Keys::valid($item['field'] ?? null)) { + $list[] = ['field' => $item['field'], 'required' => (bool) ($item['required'] ?? false)]; + } + } + + return $list; + } +} diff --git a/app/Domain/Communication/InquiryIssue.php b/app/Domain/Communication/InquiryIssue.php new file mode 100644 index 0000000..c4fa69a --- /dev/null +++ b/app/Domain/Communication/InquiryIssue.php @@ -0,0 +1,69 @@ + 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer']; + } + + public function parent(): BelongsTo + { + return $this->belongsTo(self::class, 'parent_id'); + } + + public function children(): HasMany + { + return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id'); + } + + /** Anliegen, die Besuchern angeboten werden können. */ + public function scopeOffered(Builder $query): Builder + { + return $query->where('active', true)->whereNull('archived_at'); + } + + public function isOffered(): bool + { + return $this->active && $this->archived_at === null; + } + + /** + * Baum aus angebotenen Anliegen mit ihren angebotenen Unteranliegen, wie er in eine Fassung übernommen wird. + * + * @return list}> + */ + public static function tree(): array + { + $all = self::query()->offered()->orderBy('sort_order')->orderBy('id')->get(); + $children = $all->whereNotNull('parent_id')->groupBy('parent_id'); + $tree = []; + + foreach ($all->whereNull('parent_id') as $issue) { + $tree[] = [ + 'key' => $issue->key, + 'label' => $issue->label, + 'description' => $issue->description, + 'children' => ($children[$issue->id] ?? collect())->map(fn (self $child): array => [ + 'key' => $child->key, + 'label' => $child->label, + 'description' => $child->description, + ])->values()->all(), + ]; + } + + return $tree; + } +} diff --git a/app/Domain/Communication/InquiryNote.php b/app/Domain/Communication/InquiryNote.php new file mode 100644 index 0000000..00068d2 --- /dev/null +++ b/app/Domain/Communication/InquiryNote.php @@ -0,0 +1,22 @@ +belongsTo(Inquiry::class); + } + + public function author(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } +} diff --git a/app/Domain/Communication/InquiryService.php b/app/Domain/Communication/InquiryService.php new file mode 100644 index 0000000..f1f0628 --- /dev/null +++ b/app/Domain/Communication/InquiryService.php @@ -0,0 +1,292 @@ +, version: InquiryTemplateVersion}|null + */ + public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array + { + $entry->loadMissing('template.publishedVersion'); + + if (! $entry->isLive()) { + return null; + } + + $version = $entry->template->publishedVersion; + + if ($versionId !== null && $versionId !== $version->id) { + $older = InquiryTemplateVersion::query()->where('template_id', $entry->template_id)->find($versionId); + $version = $older ?? $version; + } + + return ['form' => $this->factory->effective($version->definition, (array) $entry->published_config), 'version' => $version]; + } + + /** + * @param array $payload {values: {...}, token: string, website?: string, source?: string} + * @return array{reference: string, created: bool} + * + * @throws SubmissionException + */ + public function submit(InquiryEntry $entry, array $payload): array + { + $token = FormToken::read($payload['token'] ?? null); + + if ($token === null || $token['e'] !== $entry->id) { + throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419); + } + + $age = now()->getTimestamp() - $token['t']; + + if ($age > config('communication.token_ttl_hours', 24) * 3600) { + throw new SubmissionException('Das Formular war zu lange geöffnet. Bitte laden Sie die Seite neu.', [], 419); + } + + $existing = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->first(); + + if ($existing !== null) { + return ['reference' => $existing->reference, 'created' => false]; + } + + $delivered = $this->deliver($entry, $token['v']); + + if ($delivered === null) { + throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410); + } + + // Automaten: ausgefülltes Köderfeld oder zu schnelle Absendung. Keine Speicherung, keine Rückmeldung an das Programm. + $website = $payload['website'] ?? null; + + if ((is_string($website) && trim($website) !== '') || $age < (int) config('communication.min_fill_seconds', 3)) { + if (! (is_string($website) && trim($website) !== '')) { + throw new SubmissionException('Bitte nehmen Sie sich einen Moment Zeit und senden Sie noch einmal.', [], 429); + } + + return ['reference' => 'LF-'.now()->format('ymd').'-'.Str::upper(Str::random(5)), 'created' => false]; + } + + $values = $payload['values'] ?? null; + + if (! is_array($values) || strlen((string) json_encode($values)) > (int) config('communication.max_payload_chars', 40000)) { + throw new SubmissionException('Die Eingaben sind ungültig.'); + } + + $form = $delivered['form']; + $result = $this->process($form, $values); + + $source = $payload['source'] ?? null; + $source = is_string($source) && preg_match('#^/[A-Za-z0-9\-_/.]{0,250}$#', $source) === 1 ? $source : null; + + try { + $inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([ + 'reference' => $this->reference(), + 'entry_id' => $entry->id, + 'template_version_id' => $delivered['version']->id, + 'submission_token' => hash('sha256', $token['n']), + 'issue_key' => $result['issue']['key'] ?? null, + 'issue_label' => $result['issue']['label'] ?? null, + 'subissue_key' => $result['subissue']['key'] ?? null, + 'subissue_label' => $result['subissue']['label'] ?? null, + 'contact_name' => $result['contact']['name'] ?? null, + 'contact_email' => $result['contact']['email'] ?? null, + 'contact_phone' => $result['contact']['telefon'] ?? null, + 'organisation' => $result['contact']['organisation'] ?? null, + 'message' => $result['contact']['nachricht'] ?? null, + 'answers' => $result['answers'], + 'source_path' => $source, + 'status' => InquiryStatus::Neu->value, + ])); + } catch (UniqueConstraintViolationException) { + // Doppelt abgesendet, zwischen Prüfung und Speicherung: dieselbe Anfrage melden. + $again = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->firstOrFail(); + + return ['reference' => $again->reference, 'created' => false]; + } + + // Erst nach der Speicherung benachrichtigen. Ein Fehler hier verliert die Anfrage nie. + try { + SendInquiryNotification::dispatch($inquiry->id)->afterCommit(); + } catch (Throwable $e) { + report($e); + $inquiry->forceFill(['notification_error' => 'Die Benachrichtigung konnte nicht eingereiht werden: '.Str::limit($e->getMessage(), 300)])->save(); + } + + return ['reference' => $inquiry->reference, 'created' => true]; + } + + /** + * Wertet das Formular für Eingaben aus und prüft sie. Wird auch von der Vorschau verwendet. + * + * @param array $form + * @param array $values + * @return array{answers: list>, contact: array, issue: ?array, subissue: ?array} + * + * @throws SubmissionException + */ + public function process(array $form, array $values): array + { + $known = array_merge(array_keys((array) $form['fields']), ['anliegen', 'unteranliegen']); + + foreach (array_keys($values) as $key) { + if (! is_string($key) || ! in_array($key, $known, true)) { + throw new SubmissionException('Die Eingaben sind ungültig.'); + } + } + + $state = $this->evaluator->evaluate($form, $values); + $errors = []; + + // Anliegen: Auswahl aus dem zugelassenen Rahmen. Ein abweichender Wert ist eine Manipulation, auch wenn das Feld + // nicht sichtbar ist (zum Beispiel weil nur ein Anliegen zugelassen ist). + if ($state['issue_active']) { + foreach (['anliegen', 'unteranliegen'] as $key) { + $raw = $values[$key] ?? null; + $selected = $key === 'anliegen' ? $state['issue'] : $state['subissue']; + $filled = $raw !== null && $raw !== ''; + + if (! $filled && ($state['required'][$key] ?? false)) { + $errors[$key] = 'Bitte treffen Sie eine Auswahl.'; + } elseif ($filled && $raw !== $selected) { + $errors[$key] = 'Bitte wählen Sie einen der angebotenen Werte.'; + } + } + } + + $answers = []; + $contact = []; + $steps = []; + + foreach ((array) $form['steps'] as $step) { + foreach ($step['items'] as $item) { + if ($item['kind'] !== 'group') { + continue; + } + + foreach ($item['fields'] as $row) { + $key = $row['field']; + $steps[$key] = [$step['title'], $item['label']]; + + if (! ($state['fields'][$key] ?? false)) { + continue; + } + + $field = $form['fields'][$key]; + [$value, $error] = FieldValue::check($field, $values[$key] ?? null, (bool) ($state['required'][$key] ?? false)); + + if ($error !== null) { + $errors[$key] = $error; + + continue; + } + + if ($value === null) { + continue; + } + + $display = FieldValue::display($field, $value); + $answers[] = [ + 'key' => $key, + 'label' => $field['label'], + 'type' => $field['type'], + 'value' => $value, + 'display' => $display, + 'step' => $steps[$key][0], + 'group' => $steps[$key][1], + ]; + + if ($field['purpose'] !== null) { + $contact[$field['purpose']] = $display; + } + } + } + } + + if ($errors !== []) { + throw new SubmissionException('Bitte prüfen Sie Ihre Angaben.', $errors); + } + + $issue = $this->issueEntry($form, $state['issue']); + $subissue = $issue === null ? null : $this->subissueEntry($form, $state['issue'], $state['subissue']); + + $name = $contact['name'] ?? trim(($contact['vorname'] ?? '').' '.($contact['nachname'] ?? '')); + + return [ + 'answers' => $answers, + 'contact' => array_filter([ + 'name' => $name, + 'email' => $contact['email'] ?? null, + 'telefon' => $contact['telefon'] ?? null, + 'organisation' => $contact['organisation'] ?? null, + 'nachricht' => $contact['nachricht'] ?? null, + ], fn (?string $value): bool => $value !== null && $value !== ''), + 'issue' => $issue, + 'subissue' => $subissue, + ]; + } + + /** + * @param array $form + * @return ?array{key: string, label: string} + */ + private function issueEntry(array $form, ?string $key): ?array + { + foreach ((array) $form['issues'] as $issue) { + if ($issue['key'] === $key) { + return ['key' => $issue['key'], 'label' => $issue['label']]; + } + } + + return null; + } + + /** + * @param array $form + * @return ?array{key: string, label: string} + */ + private function subissueEntry(array $form, ?string $issue, ?string $key): ?array + { + foreach ((array) $form['issues'] as $top) { + if ($top['key'] !== $issue) { + continue; + } + + foreach ($top['children'] as $child) { + if ($child['key'] === $key) { + return ['key' => $child['key'], 'label' => $child['label']]; + } + } + } + + return null; + } + + private function reference(): string + { + do { + $reference = 'LF-'.now()->format('ymd').'-'.Str::upper(substr(str_replace(['0', 'O', '1', 'I', 'L'], '', Str::upper(Str::random(12))), 0, 5)); + } while (strlen($reference) < 12 || Inquiry::query()->where('reference', $reference)->exists()); + + return $reference; + } +} diff --git a/app/Domain/Communication/InquiryStatus.php b/app/Domain/Communication/InquiryStatus.php new file mode 100644 index 0000000..4badd04 --- /dev/null +++ b/app/Domain/Communication/InquiryStatus.php @@ -0,0 +1,45 @@ + 'Neu', + self::InBearbeitung => 'In Bearbeitung', + self::RueckfrageOffen => 'Rückfrage offen', + self::Erledigt => 'Erledigt', + }; + } + + public function color(): string + { + return match ($this) { + self::Neu => 'warning', + self::InBearbeitung => 'info', + self::RueckfrageOffen => 'danger', + self::Erledigt => 'success', + }; + } + + /** + * @return array + */ + public static function options(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->label(); + } + + return $options; + } +} diff --git a/app/Domain/Communication/InquiryTemplate.php b/app/Domain/Communication/InquiryTemplate.php new file mode 100644 index 0000000..ee2531a --- /dev/null +++ b/app/Domain/Communication/InquiryTemplate.php @@ -0,0 +1,61 @@ + 'array', 'archived_at' => 'datetime']; + } + + public function versions(): HasMany + { + return $this->hasMany(InquiryTemplateVersion::class, 'template_id')->orderByDesc('version'); + } + + public function publishedVersion(): BelongsTo + { + return $this->belongsTo(InquiryTemplateVersion::class, 'published_version_id'); + } + + public function entries(): HasMany + { + return $this->hasMany(InquiryEntry::class, 'template_id'); + } + + public function isPublished(): bool + { + return $this->published_version_id !== null; + } + + /** Ob der Entwurf von der veröffentlichten Fassung abweicht. */ + public function hasUnpublishedChanges(): bool + { + $version = $this->publishedVersion; + + return $version === null || FormJson::normalize($version->source) !== FormJson::normalize((array) $this->draft); + } + + /** + * @return array + */ + public static function emptyDraft(): array + { + return [ + 'texts' => [], + 'issues' => [], + 'steps' => [], + 'rules' => [], + ]; + } +} diff --git a/app/Domain/Communication/InquiryTemplateVersion.php b/app/Domain/Communication/InquiryTemplateVersion.php new file mode 100644 index 0000000..f6a09cb --- /dev/null +++ b/app/Domain/Communication/InquiryTemplateVersion.php @@ -0,0 +1,34 @@ + 'array', 'source' => 'array', 'published_at' => 'datetime', 'version' => 'integer']; + } + + public function template(): BelongsTo + { + return $this->belongsTo(InquiryTemplate::class, 'template_id'); + } + + protected static function booted(): void + { + // Nur die Bemerkung darf nachträglich ergänzt werden; Löschen ist ausgeschlossen. + static::updating(fn (self $version): bool => array_diff(array_keys($version->getDirty()), ['note']) === []); + static::deleting(fn (): bool => false); + } +} diff --git a/app/Domain/Communication/Keys.php b/app/Domain/Communication/Keys.php new file mode 100644 index 0000000..a9398f2 --- /dev/null +++ b/app/Domain/Communication/Keys.php @@ -0,0 +1,48 @@ + $taken + */ + public static function from(string $label, array $taken = []): string + { + $base = Str::slug($label, '_', 'de'); + $base = preg_replace('/^[^a-z]+/', '', $base) ?? ''; + $base = substr($base, 0, 50); + + if (strlen($base) < 2) { + $base = 'eintrag'; + } + + $taken = array_merge($taken, self::RESERVED); + $key = $base; + $n = 2; + + while (in_array($key, $taken, true)) { + $key = $base.'_'.$n++; + } + + return $key; + } +} diff --git a/app/Domain/Communication/Publisher.php b/app/Domain/Communication/Publisher.php new file mode 100644 index 0000000..773b378 --- /dev/null +++ b/app/Domain/Communication/Publisher.php @@ -0,0 +1,144 @@ + $definition + * @return list}> + */ + public function affected(InquiryTemplate $template, ?array $definition = null): array + { + $result = []; + + foreach ($template->entries()->whereNull('archived_at')->orderBy('name')->get() as $entry) { + $problems = $definition !== null && $entry->published_config !== null + ? $this->factory->problems($definition, (array) $entry->published_config) + : []; + + $result[] = ['entry' => $entry, 'problems' => $problems]; + } + + return $result; + } + + /** + * Veröffentlicht den Entwurf der Vorlage als neue Fassung. + * + * @throws ValidationException + */ + public function publishTemplate(InquiryTemplate $template, ?User $by = null, ?string $note = null): InquiryTemplateVersion + { + $compiled = $this->compiler->compile((array) $template->draft); + + if ($compiled['definition'] === null) { + throw ValidationException::withMessages(['draft' => $compiled['errors']]); + } + + $blocking = []; + foreach ($this->affected($template, $compiled['definition']) as $row) { + if ($row['entry']->published_config !== null && $row['problems'] !== []) { + $blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zur neuen Fassung: '.implode(' ', $row['problems']); + } + } + + if ($blocking !== []) { + throw ValidationException::withMessages(['draft' => $blocking]); + } + + return DB::transaction(function () use ($template, $compiled, $by, $note): InquiryTemplateVersion { + $template = InquiryTemplate::query()->lockForUpdate()->findOrFail($template->id); + $next = (int) InquiryTemplateVersion::query()->where('template_id', $template->id)->max('version') + 1; + + $version = InquiryTemplateVersion::query()->create([ + 'template_id' => $template->id, + 'version' => $next, + 'definition' => $compiled['definition'], + 'source' => (array) $template->draft, + 'note' => $note !== null && trim($note) !== '' ? mb_substr(trim($note), 0, 300) : null, + 'published_by' => $by?->id, + 'published_at' => now(), + ]); + + $template->forceFill(['published_version_id' => $version->id])->save(); + + return $version; + }); + } + + /** + * Setzt eine frühere Fassung wieder in Kraft (Rückkehr zu einer gültigen Konfiguration). Betroffene Einstiege + * müssen zur Fassung passen, sonst wird abgelehnt. + * + * @throws ValidationException + */ + public function restoreVersion(InquiryTemplate $template, InquiryTemplateVersion $version): void + { + abort_unless($version->template_id === $template->id, 404); + + $blocking = []; + foreach ($this->affected($template, (array) $version->definition) as $row) { + if ($row['entry']->published_config !== null && $row['problems'] !== []) { + $blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zu dieser Fassung: '.implode(' ', $row['problems']); + } + } + + if ($blocking !== []) { + throw ValidationException::withMessages(['draft' => $blocking]); + } + + $template->forceFill(['published_version_id' => $version->id])->save(); + } + + /** + * Veröffentlicht die Konfiguration eines Einstiegs. + * + * @throws ValidationException + */ + public function publishEntry(InquiryEntry $entry): void + { + $template = $entry->template()->with('publishedVersion')->firstOrFail(); + + if ($template->publishedVersion === null) { + throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist noch nicht veröffentlicht. Ein Einstieg kann nur eine veröffentlichte Vorlage verwenden.']]); + } + + if ($template->archived_at !== null) { + throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist archiviert.']]); + } + + $problems = $this->factory->problems((array) $template->publishedVersion->definition, (array) $entry->config); + + if ($problems !== []) { + throw ValidationException::withMessages(['config' => $problems]); + } + + $entry->forceFill([ + 'published_config' => $entry->config, + 'published_at' => $entry->published_at ?? now(), + 'archived_at' => null, + ])->save(); + } + + /** Nimmt einen Einstieg aus dem öffentlichen Angebot; die Konfiguration bleibt erhalten. */ + public function withdrawEntry(InquiryEntry $entry): void + { + $entry->forceFill(['published_config' => null, 'published_at' => null])->save(); + } +} diff --git a/app/Domain/Communication/SubmissionException.php b/app/Domain/Communication/SubmissionException.php new file mode 100644 index 0000000..2b84358 --- /dev/null +++ b/app/Domain/Communication/SubmissionException.php @@ -0,0 +1,19 @@ + Meldung. Der Code entspricht dem HTTP-Status. + */ +final class SubmissionException extends RuntimeException +{ + /** + * @param array $fields + */ + public function __construct(string $message, public readonly array $fields = [], int $code = 422) + { + parent::__construct($message, $code); + } +} diff --git a/app/Domain/Communication/TemplateCompiler.php b/app/Domain/Communication/TemplateCompiler.php new file mode 100644 index 0000000..5ef2dd2 --- /dev/null +++ b/app/Domain/Communication/TemplateCompiler.php @@ -0,0 +1,452 @@ + 'Anzeigen, wenn …', + 'hide' => 'Ausblenden, wenn …', + 'require' => 'Pflichtfeld, wenn …', + 'skip' => 'Schritt überspringen, wenn …', + 'preset' => 'Vorbelegen, wenn …', + ]; + + public const OPERATORS = [ + 'eq' => 'ist', + 'neq' => 'ist nicht', + 'in' => 'ist eines von', + 'not_in' => 'ist keines von', + ]; + + /** + * @param array $draft + * @return array{definition: ?array, errors: list} + */ + public function compile(array $draft): array + { + $errors = []; + + $fieldsByKey = InquiryField::query()->offered()->get()->keyBy('key'); + $groupsByKey = InquiryFieldGroup::query()->offered()->get()->keyBy('key'); + $tree = $this->issueTree((array) ($draft['issues'] ?? [])); + + $steps = []; + $fields = []; + $usedFields = []; + $usedGroups = []; + $hasIssue = false; + $position = []; + $order = 0; + $stepKeys = []; + + foreach (array_values((array) ($draft['steps'] ?? [])) as $index => $step) { + $number = $index + 1; + $step = is_array($step) ? $step : []; + $key = (string) ($step['key'] ?? ''); + $title = trim((string) ($step['title'] ?? '')); + + if (! Keys::valid($key) && ! preg_match('/^s[a-z0-9]{3,12}$/', $key)) { + $key = 's'.substr(md5($number.'|'.$title), 0, 6); + } + + if (in_array($key, $stepKeys, true)) { + $errors[] = "Schritt $number: Die Kennung des Schritts kommt doppelt vor."; + } + + $stepKeys[] = $key; + + if ($title === '') { + $title = "Schritt $number"; + } + + $position["step:$key"] = $order++; + $items = []; + + foreach (array_values((array) ($step['items'] ?? [])) as $item) { + $item = is_array($item) ? $item : []; + $kind = (string) ($item['kind'] ?? ''); + + if ($kind === 'issue') { + if ($hasIssue) { + $errors[] = "Schritt $number („{$title}“): Die Auswahl des Anliegens darf nur einmal vorkommen."; + + continue; + } + + $hasIssue = true; + $position['field:anliegen'] = $order++; + $position['field:unteranliegen'] = $order++; + $items[] = ['kind' => 'issue']; + + continue; + } + + if ($kind === 'group') { + $groupKey = (string) ($item['group'] ?? ''); + $group = $groupsByKey[$groupKey] ?? null; + + if ($group === null) { + $errors[] = "Schritt $number („{$title}“): Eine Feldgruppe ist nicht mehr verfügbar (gelöscht, deaktiviert oder archiviert)."; + + continue; + } + + if (isset($usedGroups[$groupKey])) { + $errors[] = "Die Feldgruppe „{$group->name}“ ist mehrfach eingebunden."; + + continue; + } + + $usedGroups[$groupKey] = true; + $position["group:$groupKey"] = $order++; + $rows = []; + + foreach ($group->itemList() as $row) { + $field = $fieldsByKey[$row['field']] ?? null; + + if ($field === null) { + $errors[] = "Die Feldgruppe „{$group->name}“ verwendet ein Feld, das nicht mehr verfügbar ist."; + + continue; + } + + if (isset($usedFields[$field->key])) { + $errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor."; + + continue; + } + + $usedFields[$field->key] = true; + $fields[$field->key] = $field->snapshot(); + $position['field:'.$field->key] = $order++; + $rows[] = ['field' => $field->key, 'required' => $row['required']]; + } + + $items[] = [ + 'kind' => 'group', + 'key' => $group->key, + 'label' => $group->label ?: $group->name, + 'description' => $group->description, + 'fields' => $rows, + ]; + + continue; + } + + if ($kind === 'field') { + $field = $fieldsByKey[(string) ($item['field'] ?? '')] ?? null; + + if ($field === null) { + $errors[] = "Schritt $number („{$title}“): Ein Einzelfeld ist nicht mehr verfügbar."; + + continue; + } + + if (isset($usedFields[$field->key])) { + $errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor."; + + continue; + } + + $usedFields[$field->key] = true; + $fields[$field->key] = $field->snapshot(); + $position['field:'.$field->key] = $order++; + $items[] = [ + 'kind' => 'group', + 'key' => null, + 'label' => null, + 'description' => null, + 'fields' => [['field' => $field->key, 'required' => (bool) ($item['required'] ?? false)]], + ]; + + continue; + } + + $errors[] = "Schritt $number („{$title}“): Ein Baustein hat keinen gültigen Typ."; + } + + if ($items === []) { + $errors[] = "Schritt $number („{$title}“) enthält nichts."; + } + + $steps[] = [ + 'key' => $key, + 'title' => mb_substr($title, 0, 120), + 'intro' => $this->text($step['intro'] ?? null, 600), + 'items' => $items, + ]; + } + + if ($steps === []) { + $errors[] = 'Die Vorlage hat noch keinen Schritt.'; + } + + $purposes = []; + foreach ($fields as $field) { + if ($field['purpose'] !== null) { + $purposes[$field['purpose']][] = $field['key']; + } + } + + if (! isset($purposes[FieldPurpose::Email->value])) { + $errors[] = 'Die Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“, sonst lässt sich eine Anfrage nicht beantworten.'; + } + + foreach ($purposes as $purpose => $keys) { + if (count($keys) > 1) { + $errors[] = 'Die Verwendung „'.FieldPurpose::from($purpose)->label().'“ ist mehreren Feldern zugeordnet.'; + } + } + + if ($hasIssue && $tree === []) { + $errors[] = 'Die Auswahl des Anliegens hat kein verfügbares Anliegen. Bitte Anliegen anlegen oder aktivieren.'; + } + + $rules = $this->rules((array) ($draft['rules'] ?? []), $fields, $tree, $hasIssue, $position, $stepKeys, $usedGroups, $errors); + + $definition = [ + 'v' => 1, + 'texts' => FormTexts::merge(FormTexts::clean((array) ($draft['texts'] ?? []))), + 'has_issue' => $hasIssue, + 'issues' => $hasIssue ? $tree : [], + 'fields' => $fields, + 'steps' => $steps, + 'rules' => $rules, + ]; + + return ['definition' => $errors === [] ? $definition : null, 'errors' => array_values(array_unique($errors))]; + } + + /** + * Vollständige Auflösung ohne Fehlerfreiheit: für die Vorschau eines unfertigen Entwurfs. + * + * @param array $draft + * @return array{definition: ?array, errors: list} + */ + public function preview(array $draft): array + { + return $this->compile($draft); + } + + /** + * @param list $only + * @return list}> + */ + private function issueTree(array $only): array + { + $tree = InquiryIssue::tree(); + + if ($only === []) { + return $tree; + } + + return array_values(array_filter($tree, fn (array $issue): bool => in_array($issue['key'], $only, true))); + } + + /** + * @param array $rules + * @param array> $fields + * @param list> $tree + * @param array $position + * @param list $stepKeys + * @param array $usedGroups + * @param list $errors + * @return list> + */ + private function rules(array $rules, array $fields, array $tree, bool $hasIssue, array $position, array $stepKeys, array $usedGroups, array &$errors): array + { + $normalized = []; + $issueKeys = array_column($tree, 'key'); + $subKeys = []; + foreach ($tree as $issue) { + foreach ($issue['children'] as $child) { + $subKeys[] = $child['key']; + } + } + + foreach (array_values($rules) as $index => $rule) { + $number = $index + 1; + $rule = is_array($rule) ? $rule : []; + $effect = (string) ($rule['effect'] ?? ''); + $target = (string) ($rule['target'] ?? ''); + + if (! isset(self::EFFECTS[$effect])) { + $errors[] = "Regel $number: Die Wirkung ist ungültig."; + + continue; + } + + [$targetKind] = array_pad(explode(':', $target, 2), 2, ''); + + if (! isset($position[$target])) { + $errors[] = "Regel $number: Das Ziel „{$target}“ gibt es in dieser Vorlage nicht."; + + continue; + } + + $kindOk = match ($effect) { + 'show', 'hide' => in_array($targetKind, ['group', 'field'], true), + 'require', 'preset' => $targetKind === 'field', + 'skip' => $targetKind === 'step', + default => false, + }; + + if (! $kindOk) { + $errors[] = "Regel $number: Die Wirkung „".self::EFFECTS[$effect].'“ passt nicht zum Ziel.'; + + continue; + } + + if (in_array($target, ['field:anliegen', 'field:unteranliegen'], true)) { + $errors[] = "Regel $number: Die Auswahl des Anliegens lässt sich nicht durch eine Regel steuern."; + + continue; + } + + $presetValue = null; + if ($effect === 'preset') { + $field = $fields[substr($target, 6)] ?? null; + $presetValue = $rule['value'] ?? null; + + if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) { + $errors[] = "Regel $number: Vorbelegt werden können nur Einfachauswahl- und Ja/Nein-Felder."; + + continue; + } + + $valid = array_column($field['options'] ?: [['key' => 'ja'], ['key' => 'nein']], 'key'); + if ($field['type'] === 'boolean') { + $valid = ['ja', 'nein']; + } + + if (! is_string($presetValue) || ! in_array($presetValue, $valid, true)) { + $errors[] = "Regel $number: Der Wert zum Vorbelegen ist kein Auswahlwert des Feldes."; + + continue; + } + } + + $match = ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all'; + $conditions = []; + + foreach (array_values((array) ($rule['conditions'] ?? [])) as $c => $condition) { + $condition = is_array($condition) ? $condition : []; + $source = (string) ($condition['source'] ?? ''); + $op = (string) ($condition['op'] ?? 'eq'); + $values = array_values(array_filter((array) ($condition['values'] ?? []), fn (mixed $v): bool => is_string($v) && $v !== '')); + + if (! isset(self::OPERATORS[$op])) { + $errors[] = "Regel $number, Bedingung ".($c + 1).': Der Vergleich ist ungültig.'; + + continue; + } + + if (in_array($op, ['eq', 'neq'], true)) { + $values = array_slice($values, 0, 1); + } + + if ($values === []) { + $errors[] = "Regel $number, Bedingung ".($c + 1).': Es fehlt ein Vergleichswert.'; + + continue; + } + + $sourceKey = "field:$source"; + + if ($source === 'anliegen' || $source === 'unteranliegen') { + if (! $hasIssue) { + $errors[] = "Regel $number: Die Vorlage hat keine Auswahl des Anliegens."; + + continue; + } + + $valid = $source === 'anliegen' ? $issueKeys : $subKeys; + } else { + $field = $fields[$source] ?? null; + + if ($field === null || ! isset($position[$sourceKey])) { + $errors[] = "Regel $number: Die Bedingung bezieht sich auf ein Feld, das es in der Vorlage nicht gibt."; + + continue; + } + + if (! FieldType::from($field['type'])->canControl()) { + $errors[] = "Regel $number: Bedingungen sind nur für Auswahlfelder und Ja/Nein-Felder möglich („{$field['label']}“)."; + + continue; + } + + $valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key'); + } + + if (array_diff($values, $valid) !== []) { + $errors[] = "Regel $number: Ein Vergleichswert ist kein Auswahlwert von „{$source}“."; + + continue; + } + + if ($position[$sourceKey] >= $position[$target]) { + $errors[] = "Regel $number: Die Bedingung „{$source}“ muss in der Vorlage vor ihrem Ziel stehen, sonst kann sie noch nicht ausgewertet werden."; + + continue; + } + + $conditions[] = ['source' => $source, 'op' => $op, 'values' => $values]; + } + + if ($conditions === [] || count($conditions) !== count((array) ($rule['conditions'] ?? []))) { + if ($conditions === []) { + $errors[] = "Regel $number hat keine gültige Bedingung."; + } + + continue; + } + + $normalized[] = [ + 'effect' => $effect, + 'target' => $target, + 'match' => $match, + 'conditions' => $conditions, + 'value' => $presetValue, + ]; + } + + // Widersprüche: gleiche Bedingung zeigt und blendet dasselbe Ziel aus. + $seen = []; + foreach ($normalized as $rule) { + if (! in_array($rule['effect'], ['show', 'hide'], true)) { + continue; + } + + $signature = json_encode([$rule['target'], $rule['match'], $rule['conditions']]); + $opposite = $rule['effect'] === 'show' ? 'hide' : 'show'; + + if (isset($seen[$opposite][$signature])) { + $errors[] = 'Widerspruch: Das Ziel „'.$rule['target'].'“ wird unter derselben Bedingung angezeigt und ausgeblendet.'; + } + + $seen[$rule['effect']][$signature] = true; + } + + return $normalized; + } + + private function text(mixed $value, int $max): ?string + { + if (! is_string($value) || trim($value) === '') { + return null; + } + + return mb_substr(trim($value), 0, $max); + } +} diff --git a/app/Jobs/SendInquiryNotification.php b/app/Jobs/SendInquiryNotification.php new file mode 100644 index 0000000..9ca927c --- /dev/null +++ b/app/Jobs/SendInquiryNotification.php @@ -0,0 +1,53 @@ +find($this->inquiryId); + + if ($inquiry === null) { + return; + } + + $recipients = CommunicationSettings::current()->recipientList(); + + if ($recipients === []) { + $inquiry->forceFill(['notification_error' => 'Es sind keine Empfänger für Benachrichtigungen hinterlegt (Kommunikation → Einstellungen).'])->save(); + + return; + } + + try { + Mail::to($recipients)->send(new InquiryReceived($inquiry)); + } catch (Throwable $e) { + report($e); + $inquiry->forceFill(['notification_error' => 'Der E-Mail-Versand ist fehlgeschlagen: '.Str::limit($e->getMessage(), 400)])->save(); + + return; + } + + $inquiry->forceFill(['notified_at' => now(), 'notification_error' => null])->save(); + } +} diff --git a/app/Mail/InquiryReceived.php b/app/Mail/InquiryReceived.php new file mode 100644 index 0000000..458eef0 --- /dev/null +++ b/app/Mail/InquiryReceived.php @@ -0,0 +1,35 @@ +inquiry->reference); + } + + public function content(): Content + { + return new Content( + text: 'mail.inquiry-received', + with: [ + 'reference' => $this->inquiry->reference, + 'issue' => $this->inquiry->issueTitle(), + 'received' => $this->inquiry->created_at?->timezone(config('app.timezone'))->format('d.m.Y H:i'), + 'url' => url('/verwaltung/anfragen/'.$this->inquiry->id), + ], + ); + } +} diff --git a/config/communication.php b/config/communication.php new file mode 100644 index 0000000..dddc45f --- /dev/null +++ b/config/communication.php @@ -0,0 +1,21 @@ + 24, + + /* Kürzeste Zeit zwischen Auslieferung und Absenden; schneller sendende Programme gelten als Automaten. */ + 'min_fill_seconds' => (int) env('INQUIRY_MIN_FILL_SECONDS', 3), + + /* Absendungen je Minute und Adresse beziehungsweise Auswertungen je Minute. */ + 'submit_per_minute' => 5, + 'submit_per_hour' => 20, + 'state_per_minute' => 120, + + /* Größte Menge an Eingaben (Zeichen), die ein Besucher senden darf. */ + 'max_payload_chars' => 40000, + +]; diff --git a/database/migrations/2026_12_03_100000_create_communication_tables.php b/database/migrations/2026_12_03_100000_create_communication_tables.php new file mode 100644 index 0000000..81cf4bb --- /dev/null +++ b/database/migrations/2026_12_03_100000_create_communication_tables.php @@ -0,0 +1,141 @@ +id(); + $table->foreignId('parent_id')->nullable()->constrained('inquiry_issues')->restrictOnDelete(); + $table->string('key', 60)->unique(); + $table->string('label', 120); + $table->text('description')->nullable(); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_fields', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->string('label', 200); + $table->text('help')->nullable(); + $table->string('type', 20); + $table->json('options')->nullable(); + $table->json('settings')->nullable(); + $table->string('purpose', 20)->nullable(); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_field_groups', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->string('label', 200)->nullable(); + $table->text('description')->nullable(); + $table->json('items'); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('active')->default(true); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_templates', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->text('description')->nullable(); + $table->json('draft'); + $table->unsignedBigInteger('published_version_id')->nullable()->index(); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiry_template_versions', function (Blueprint $table): void { + $table->id(); + $table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete(); + $table->unsignedInteger('version'); + $table->json('definition'); + $table->json('source'); + $table->string('note', 300)->nullable(); + $table->foreignId('published_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamp('published_at'); + $table->unique(['template_id', 'version']); + }); + + Schema::create('inquiry_entries', function (Blueprint $table): void { + $table->id(); + $table->string('key', 60)->unique(); + $table->string('name', 120); + $table->foreignId('template_id')->constrained('inquiry_templates')->restrictOnDelete(); + $table->json('config'); + $table->json('published_config')->nullable(); + $table->timestamp('published_at')->nullable(); + $table->timestamp('archived_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('inquiries', function (Blueprint $table): void { + $table->id(); + $table->string('reference', 20)->unique(); + $table->foreignId('entry_id')->nullable()->constrained('inquiry_entries')->restrictOnDelete(); + $table->foreignId('template_version_id')->constrained('inquiry_template_versions')->restrictOnDelete(); + $table->string('submission_token', 64)->unique(); + $table->string('issue_key', 60)->nullable(); + $table->string('issue_label', 120)->nullable(); + $table->string('subissue_key', 60)->nullable(); + $table->string('subissue_label', 120)->nullable(); + $table->string('contact_name', 200)->nullable(); + $table->string('contact_email', 200)->nullable(); + $table->string('contact_phone', 60)->nullable(); + $table->string('organisation', 200)->nullable(); + $table->text('message')->nullable(); + $table->json('answers'); + $table->string('source_path', 300)->nullable(); + $table->string('status', 20)->default('neu')->index(); + $table->timestamp('notified_at')->nullable(); + $table->text('notification_error')->nullable(); + $table->timestamps(); + $table->index('created_at'); + }); + + Schema::create('inquiry_notes', function (Blueprint $table): void { + $table->id(); + $table->foreignId('inquiry_id')->constrained('inquiries')->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->text('body'); + $table->timestamps(); + }); + + Schema::create('communication_settings', function (Blueprint $table): void { + $table->id(); + $table->json('recipients'); + $table->unsignedSmallInteger('retention_months')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('communication_settings'); + Schema::dropIfExists('inquiry_notes'); + Schema::dropIfExists('inquiries'); + Schema::dropIfExists('inquiry_entries'); + Schema::dropIfExists('inquiry_template_versions'); + Schema::dropIfExists('inquiry_templates'); + Schema::dropIfExists('inquiry_field_groups'); + Schema::dropIfExists('inquiry_fields'); + Schema::dropIfExists('inquiry_issues'); + } +}; diff --git a/resources/views/mail/inquiry-received.blade.php b/resources/views/mail/inquiry-received.blade.php new file mode 100644 index 0000000..1cf2fc5 --- /dev/null +++ b/resources/views/mail/inquiry-received.blade.php @@ -0,0 +1,11 @@ +Neue Anfrage {{ $reference }} + +Eingegangen: {{ $received }} +@if ($issue !== '') +Anliegen: {{ $issue }} +@endif + +Die Angaben stehen in der Verwaltung (Anmeldung erforderlich): +{{ $url }} + +Diese Nachricht enthält absichtlich keine Kontaktdaten und keine Antworten. diff --git a/tests/Feature/CommunicationInquiryTest.php b/tests/Feature/CommunicationInquiryTest.php new file mode 100644 index 0000000..734f0b2 --- /dev/null +++ b/tests/Feature/CommunicationInquiryTest.php @@ -0,0 +1,438 @@ + 0]); + app(ExampleConfiguration::class)->install(); + } + + private function entry(string $key): InquiryEntry + { + return InquiryEntry::query()->where('key', $key)->firstOrFail(); + } + + /** + * @param array $values + * @return array{reference: string, created: bool} + */ + private function send(InquiryEntry $entry, array $values, array $extra = []): array + { + $version = $entry->template->publishedVersion; + + return app(InquiryService::class)->submit($entry, array_merge([ + 'token' => FormToken::issue($entry->id, $version->id), + 'values' => $values, + ], $extra)); + } + + /** @return array */ + private function infoRequest(): array + { + return [ + 'anliegen' => 'kurse', + 'unteranliegen' => 'kursinfo', + 'kursformat' => 'schul_ag', + 'region' => 'Hannover', + 'vorname' => 'Mira', + 'nachname' => 'Beispiel', + 'email' => 'mira@example.org', + 'nachricht' => 'Wir möchten gern mehr erfahren.', + ]; + } + + public function test_the_example_configuration_is_published_and_only_installs_into_an_empty_area(): void + { + $this->assertSame(5, InquiryEntry::query()->live()->count()); + $this->assertSame(4, InquiryTemplate::query()->whereNotNull('published_version_id')->count()); + + $this->expectException(\RuntimeException::class); + app(ExampleConfiguration::class)->install(); + } + + public function test_an_information_request_asks_only_for_few_details_and_stores_readable_answers(): void + { + $result = $this->send($this->entry('kurse_workshops'), $this->infoRequest()); + + $this->assertTrue($result['created']); + + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertSame($result['reference'], $inquiry->reference); + $this->assertSame('Kurse & Workshops › Allgemeine Kursinformation', $inquiry->issueTitle()); + $this->assertSame('Mira Beispiel', $inquiry->contact_name); + $this->assertSame('mira@example.org', $inquiry->contact_email); + $this->assertSame('Wir möchten gern mehr erfahren.', $inquiry->message); + $this->assertSame(InquiryStatus::Neu, $inquiry->status); + + $answers = collect($inquiry->answers)->keyBy('key'); + $this->assertSame('Schul-AG', $answers['kursformat']['display']); + $this->assertSame('Welches Format interessiert Sie?', $answers['kursformat']['label']); + $this->assertSame('Ihre Kontaktdaten', $answers['email']['group']); + $this->assertArrayNotHasKey('einrichtung_name', $answers->all()); + } + + public function test_values_of_fields_that_are_not_relevant_are_never_stored(): void + { + // Besucher hat erst „konkretes Vorhaben“ ausgefüllt, dann auf „Information“ gewechselt: Schritt 2 entfällt. + $values = $this->infoRequest() + [ + 'einrichtung_name' => 'Altschule', + 'einrichtungstyp' => 'grundschule', + 'anzahl_kinder' => '24', + ]; + + $this->send($this->entry('kurse_workshops'), $values); + + $keys = collect(Inquiry::query()->firstOrFail()->answers)->pluck('key')->all(); + $this->assertNotContains('einrichtung_name', $keys); + $this->assertNotContains('anzahl_kinder', $keys); + $this->assertContains('region', $keys); + } + + public function test_a_concrete_course_request_needs_the_additional_planning_details_and_shows_follow_up_fields(): void + { + $values = [ + 'anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag', + 'einrichtung_name' => 'Grundschule Süd', 'einrichtungstyp' => 'grundschule', + 'einrichtung_strasse' => 'Schulweg 1', 'einrichtung_plz' => '30159', 'einrichtung_ort' => 'Hannover', + 'traeger_abweichend' => 'nein', 'ort_abweichend' => 'nein', + 'alter' => '8 bis 10 Jahre', 'anzahl_kinder' => '20', + 'vorname' => 'Mira', 'nachname' => 'Beispiel', 'email' => 'mira@example.org', + ]; + + $entry = $this->entry('schul_ag'); + + // Fehlt etwas Bedingtes, wird es angemahnt: Schulart bei Grundschule, Laufzeit und Häufigkeit bei Schul-AG. + try { + $this->send($entry, $values); + $this->fail('Erwartet: Zurückweisung wegen bedingter Pflichtfelder.'); + } catch (SubmissionException $e) { + $this->assertEqualsCanonicalizing(['schulart', 'laufzeit', 'haeufigkeit'], array_keys($e->fields)); + } + + $this->assertSame(0, Inquiry::query()->count()); + + $values += ['schulart' => 'gs', 'laufzeit' => 'halbjahr', 'haeufigkeit' => 'woechentlich']; + $this->send($entry, $values); + + $answers = collect(Inquiry::query()->firstOrFail()->answers)->keyBy('key'); + $this->assertSame('Ein Schulhalbjahr', $answers['laufzeit']['display']); + $this->assertArrayNotHasKey('traeger_name', $answers->all()); + $this->assertSame('Ihr Vorhaben', $answers['alter']['step']); + } + + public function test_a_deviating_provider_and_venue_make_their_fields_required(): void + { + $values = [ + 'anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'kompakt', + 'einrichtung_name' => 'Verein X', 'einrichtungstyp' => 'verein', + 'einrichtung_strasse' => 'Weg 2', 'einrichtung_plz' => '30159', 'einrichtung_ort' => 'Hannover', + 'traeger_abweichend' => 'ja', 'ort_abweichend' => 'ja', + 'alter' => '9', 'anzahl_kinder' => '12', + 'vorname' => 'A', 'nachname' => 'B', 'email' => 'a@example.org', + ]; + + try { + $this->send($this->entry('kurse_workshops'), $values); + $this->fail('Erwartet: Zurückweisung.'); + } catch (SubmissionException $e) { + $this->assertEqualsCanonicalizing(['traeger_name', 'ort_strasse', 'ort_plz', 'ort_ort'], array_keys($e->fields)); + } + } + + public function test_manipulated_issues_options_and_unknown_fields_are_rejected(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $good = ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']; + + foreach ([ + ['anliegen' => 'kurse'] + $good, // Anliegen außerhalb des Einstiegs (nur „allgemein“ zugelassen) + $good + ['unbekannt' => 'x'], // Feld, das es nicht gibt + ['email' => 'kein-mail'] + $good, // ungültiger Wert + ] as $values) { + try { + $this->send($entry, $values); + $this->fail('Erwartet: Zurückweisung für '.json_encode($values)); + } catch (SubmissionException $e) { + $this->assertSame(422, $e->getCode()); + } + } + + $course = $this->entry('kurse_workshops'); + try { + $this->send($course, ['kursformat' => 'gibt_es_nicht'] + $this->infoRequest()); + $this->fail('Erwartet: Zurückweisung eines nicht angebotenen Auswahlwerts.'); + } catch (SubmissionException $e) { + $this->assertArrayHasKey('kursformat', $e->fields); + } + + $this->assertSame(0, Inquiry::query()->count()); + } + + public function test_a_single_allowed_issue_is_not_asked_but_still_recorded(): void + { + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertSame('allgemein', $inquiry->issue_key); + $this->assertNull($inquiry->subissue_key); + } + + public function test_a_second_submission_with_the_same_token_creates_no_second_inquiry(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $token = FormToken::issue($entry->id, $entry->template->published_version_id); + $payload = ['token' => $token, 'values' => ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']]; + + $first = app(InquiryService::class)->submit($entry, $payload); + $second = app(InquiryService::class)->submit($entry, $payload); + + $this->assertTrue($first['created']); + $this->assertFalse($second['created']); + $this->assertSame($first['reference'], $second['reference']); + $this->assertSame(1, Inquiry::query()->count()); + } + + public function test_bots_are_caught_by_the_decoy_field_and_by_a_too_fast_submission(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $values = ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']; + + $result = $this->send($entry, $values, ['website' => 'http://spam.example']); + $this->assertFalse($result['created']); + $this->assertSame(0, Inquiry::query()->count()); + + config(['communication.min_fill_seconds' => 3]); + + try { + $this->send($entry, $values); + $this->fail('Erwartet: zu schnelle Absendung.'); + } catch (SubmissionException $e) { + $this->assertSame(429, $e->getCode()); + } + + $this->travel(5)->seconds(); + $token = FormToken::issue($entry->id, $entry->template->published_version_id); + $this->travel(5)->seconds(); + $this->assertTrue(app(InquiryService::class)->submit($entry, ['token' => $token, 'values' => $values])['created']); + } + + public function test_a_forged_or_foreign_token_is_refused(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $other = $this->entry('kooperation'); + + foreach (['x', '', FormToken::issue($other->id, $other->template->published_version_id)] as $token) { + try { + app(InquiryService::class)->submit($entry, ['token' => $token, 'values' => ['name' => 'a', 'email' => 'a@example.org', 'nachricht' => 'b']]); + $this->fail('Erwartet: Token abgelehnt.'); + } catch (SubmissionException $e) { + $this->assertSame(419, $e->getCode()); + } + } + } + + public function test_the_internal_notification_is_sent_to_the_recipients_without_personal_data(): void + { + Mail::fake(); + CommunicationSettings::current()->update(['recipients' => ['team@example.org']]); + + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira Geheim', 'email' => 'mira@example.org', 'nachricht' => 'Vertraulich']); + + Mail::assertSent(InquiryReceived::class, function (InquiryReceived $mail): bool { + $text = $mail->render(); + + return $mail->hasTo('team@example.org') + && ! str_contains($text, 'Mira Geheim') + && ! str_contains($text, 'mira@example.org') + && ! str_contains($text, 'Vertraulich') + && str_contains($text, $mail->inquiry->reference); + }); + + $this->assertNotNull(Inquiry::query()->firstOrFail()->notified_at); + } + + public function test_a_failing_mail_server_does_not_lose_the_inquiry(): void + { + CommunicationSettings::current()->update(['recipients' => ['team@example.org']]); + Mail::shouldReceive('to')->andThrow(new \RuntimeException('smtp down')); + + $result = $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $this->assertTrue($result['created']); + $inquiry = Inquiry::query()->firstOrFail(); + $this->assertNull($inquiry->notified_at); + $this->assertStringContainsString('smtp down', (string) $inquiry->notification_error); + } + + public function test_missing_recipients_are_recorded_instead_of_silently_dropped(): void + { + $this->send($this->entry('allgemeiner_kontakt'), ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + $this->assertStringContainsString('keine Empfänger', (string) Inquiry::query()->firstOrFail()->notification_error); + } + + public function test_changing_the_catalog_or_republishing_never_reinterprets_an_old_inquiry(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $this->send($entry, ['name' => 'Mira', 'email' => 'mira@example.org', 'nachricht' => 'Hallo']); + + InquiryField::query()->where('key', 'nachricht')->update(['label' => 'Etwas ganz anderes']); + $template = $entry->template; + app(Publisher::class)->publishTemplate($template, null, 'Neue Bezeichnung'); + + $inquiry = Inquiry::query()->firstOrFail(); + $label = collect($inquiry->answers)->firstWhere('key', 'nachricht')['label']; + $this->assertSame('Ihre Nachricht', $label); + $this->assertSame(1, $inquiry->templateVersion->version); + $this->assertSame(2, $template->fresh()->publishedVersion->version); + } + + public function test_a_draft_stays_invisible_until_the_template_is_deliberately_published(): void + { + $entry = $this->entry('allgemeiner_kontakt'); + $template = $entry->template; + $version = $template->publishedVersion; + + $draft = $template->draft; + $draft['texts']['heading'] = 'Ganz neue Überschrift'; + $template->update(['draft' => $draft]); + + $this->assertTrue($template->fresh()->hasUnpublishedChanges()); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Schreiben Sie uns', $delivered['form']['texts']['heading']); + + app(Publisher::class)->publishTemplate($template); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Ganz neue Überschrift', $delivered['form']['texts']['heading']); + + // Rückkehr zur früheren Fassung. + app(Publisher::class)->restoreVersion($template->fresh(), $version); + $delivered = app(InquiryService::class)->deliver($entry->fresh()); + $this->assertSame('Schreiben Sie uns', $delivered['form']['texts']['heading']); + } + + public function test_published_versions_are_immutable(): void + { + $version = $this->entry('allgemeiner_kontakt')->template->publishedVersion; + + $version->definition = ['v' => 1]; + $this->assertFalse($version->save()); + $this->assertFalse($version->delete()); + } + + public function test_an_entry_can_only_be_published_against_a_published_template_and_a_fitting_configuration(): void + { + $template = InquiryTemplate::query()->create(['key' => 'neu', 'name' => 'Neu', 'draft' => InquiryTemplate::emptyDraft()]); + $entry = InquiryEntry::query()->create(['key' => 'x', 'name' => 'X', 'template_id' => $template->id, 'config' => InquiryEntry::emptyConfig()]); + + try { + app(Publisher::class)->publishEntry($entry); + $this->fail('Erwartet: Vorlage nicht veröffentlicht.'); + } catch (ValidationException $e) { + $this->assertStringContainsString('noch nicht veröffentlicht', $e->errors()['config'][0]); + } + + $good = $this->entry('kurse_workshops'); + $good->config = array_merge((array) $good->config, ['defaults' => ['kursformat' => 'gibt_es_nicht']]); + $this->expectException(ValidationException::class); + app(Publisher::class)->publishEntry($good); + } + + public function test_publishing_a_template_is_blocked_when_the_draft_is_invalid_and_names_the_problems(): void + { + $template = $this->entry('kurse_workshops')->template; + $draft = $template->draft; + // Bedingung verweist auf ein Feld, das erst nach dem Ziel steht. + $draft['rules'][] = ['effect' => 'show', 'target' => 'field:kursformat', 'match' => 'all', 'conditions' => [['source' => 'einrichtungstyp', 'op' => 'eq', 'values' => ['verein']]], 'value' => null]; + $template->update(['draft' => $draft]); + + try { + app(Publisher::class)->publishTemplate($template); + $this->fail('Erwartet: Zurückweisung.'); + } catch (ValidationException $e) { + $this->assertStringContainsString('vor ihrem Ziel stehen', implode(' ', $e->errors()['draft'])); + } + + $this->assertSame(1, InquiryTemplateVersion::query()->where('template_id', $template->id)->count()); + } + + public function test_the_evaluator_shows_groups_and_skips_steps_from_the_choice(): void + { + $entry = $this->entry('kurse_workshops'); + $delivered = app(InquiryService::class)->deliver($entry); + $form = $delivered['form']; + $evaluator = app(FormEvaluator::class); + + $info = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursinfo']); + $this->assertFalse($info['steps']['skurs2']); + $this->assertFalse($info['fields']['einrichtung_name']); + $this->assertTrue($info['fields']['region']); + + $plan = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag', 'ort_abweichend' => 'ja']); + $this->assertTrue($plan['steps']['skurs2']); + $this->assertTrue($plan['groups']['schul_ag']); + $this->assertTrue($plan['groups']['ort_angaben']); + $this->assertFalse($plan['groups']['traeger_angaben']); + $this->assertFalse($plan['fields']['region']); + + // Wechsel des Formats blendet die Zusatzfragen wieder aus. + $other = $evaluator->evaluate($form, ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'kompakt']); + $this->assertFalse($other['groups']['schul_ag']); + } + + public function test_an_entry_can_limit_the_offered_issues_and_preselect_values(): void + { + $factory = app(FormFactory::class); + $definition = $this->entry('kurse_workshops')->template->publishedVersion->definition; + + $form = $factory->effective($definition, ['allowed_subissues' => ['kursvorhaben'], 'defaults' => ['kursformat' => 'schul_ag', 'anliegen' => 'kurse', 'nonsens' => 'x']]); + + $this->assertSame(['kursvorhaben'], array_column($form['issues'][0]['children'], 'key')); + $this->assertEquals(['kursformat' => 'schul_ag', 'anliegen' => 'kurse'], $form['defaults']); + $this->assertContains('unteranliegen', $form['controls']); + } + + public function test_the_example_schul_ag_entry_preselects_the_format(): void + { + $delivered = app(InquiryService::class)->deliver($this->entry('schul_ag')); + + $this->assertSame('schul_ag', $delivered['form']['defaults']['kursformat']); + $this->assertSame('wizard', $delivered['form']['mode']); + $this->assertSame('Schul-AG anfragen', $delivered['form']['texts']['heading']); + } + + public function test_a_withdrawn_or_archived_entry_is_not_delivered(): void + { + $entry = $this->entry('kooperation'); + app(Publisher::class)->withdrawEntry($entry); + + $this->assertNull(app(InquiryService::class)->deliver($entry->fresh())); + } +}