Lege das Datenmodell und den Anfrageservice der Kommunikationsverwaltung an
Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen mit unveränderlichen Fassungen, Anfrage-Einstiege und eingegangene Anfragen. Eine gemeinsame Regelauswertung bedient Besucher, Vorschau und Anfrageservice; Werte nicht mehr relevanter Felder werden verworfen, Anliegen und Auswahlwerte serverseitig geprüft, doppeltes Absenden bleibt eine Anfrage. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e2d64a4a9
commit
2ee1fc9866
30 files changed
+3380
No files matched your search
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Allgemeine Kommunikationsvorgaben (eine Zeile): Empfänger der internen Benachrichtigung und Aufbewahrungsdauer.
|
||||
* Empfänger werden nur hier gepflegt; Besucher und das CMS können keine Empfänger angeben.
|
||||
*/
|
||||
class CommunicationSettings extends Model
|
||||
{
|
||||
protected $fillable = ['recipients', 'retention_months'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['recipients' => 'array', 'retention_months' => 'integer'];
|
||||
}
|
||||
|
||||
public static function current(): self
|
||||
{
|
||||
return self::query()->first() ?? self::query()->create(['recipients' => []]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
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,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Beispielkonfiguration für die Kommunikationsverwaltung: Anliegen, Felder, Feldgruppen, drei Anfragevorlagen und
|
||||
* fünf Anfrage-Einstiege. Sie entsteht nur auf ausdrücklichen Wunsch („Beispielkonfiguration anlegen“) und nur in einer
|
||||
* noch leeren Verwaltung. Alles daraus lässt sich in der Verwaltung ändern; die Vorlagen sind gewöhnliche Entwürfe,
|
||||
* keine Sonderfälle im Code.
|
||||
*/
|
||||
final class ExampleConfiguration
|
||||
{
|
||||
public function __construct(private readonly Publisher $publisher) {}
|
||||
|
||||
public static function isEmpty(): bool
|
||||
{
|
||||
return ! InquiryIssue::query()->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<string, InquiryTemplate>
|
||||
*/
|
||||
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<string, InquiryTemplate> $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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Fachliche Verwendung eines Feldes in der Anfrageübersicht. Ohne Verwendung erscheint die Antwort nur in der Liste
|
||||
* der Antworten.
|
||||
*/
|
||||
enum FieldPurpose: string
|
||||
{
|
||||
case FirstName = 'vorname';
|
||||
case LastName = 'nachname';
|
||||
case FullName = 'name';
|
||||
case Email = 'email';
|
||||
case Phone = 'telefon';
|
||||
case Organisation = 'organisation';
|
||||
case Message = 'nachricht';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::FirstName => '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<FieldType> */
|
||||
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<string, string>
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (self::cases() as $case) {
|
||||
$options[$case->value] = $case->label();
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Unterstützte Feldtypen des Feldkatalogs (ADR-60). Ein neuer technischer Typ ist eine kontrollierte
|
||||
* Softwareerweiterung: hier ergänzen, in {@see FieldValue} prüfen und in resources/js/inquiry-form.js darstellen.
|
||||
*/
|
||||
enum FieldType: string
|
||||
{
|
||||
case Text = 'text';
|
||||
case Textarea = 'textarea';
|
||||
case Email = 'email';
|
||||
case Phone = 'phone';
|
||||
case Number = 'number';
|
||||
case Select = 'select';
|
||||
case Multiselect = 'multiselect';
|
||||
case Boolean = 'boolean';
|
||||
case Date = 'date';
|
||||
case Period = 'period';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Text => '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<string, string>
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (self::cases() as $case) {
|
||||
$options[$case->value] = $case->label();
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Prüft und bereinigt einen einzelnen Antwortwert nach dem Feldtyp. Die einzige Stelle, an der Werte eines Besuchers
|
||||
* in gespeicherte Werte übergehen. Eingabe ist die Feldbeschreibung aus der Fassung (siehe InquiryField::snapshot()).
|
||||
*/
|
||||
final class FieldValue
|
||||
{
|
||||
public const TEXT_MAX = 200;
|
||||
|
||||
public const TEXTAREA_MAX = 4000;
|
||||
|
||||
/**
|
||||
* Rohwert für Bedingungen: ungültige oder fehlende Werte zählen als nicht gesetzt (null).
|
||||
*
|
||||
* @param array<string, mixed> $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<string, mixed> $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<string, mixed> $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<string, mixed> $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<string, mixed> $field
|
||||
* @return list<string>
|
||||
*/
|
||||
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<string, mixed> $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'), ',');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Die einzige Auswertung der Bedingungen (ADR-60). Browser, Vorschau und Anfrageservice fragen dieselbe Funktion; der
|
||||
* Browser entscheidet nichts allein.
|
||||
*
|
||||
* Die Auswertung läuft einmal in Dokumentreihenfolge. Eine Bedingung sieht nur Werte von Feldern, die vor ihr stehen und
|
||||
* selbst sichtbar sind; Werte ausgeblendeter Felder zählen als nicht vorhanden. Daraus folgt: keine Zyklen, und
|
||||
* nicht mehr relevante Werte erreichen nie die Speicherung.
|
||||
*/
|
||||
final class FormEvaluator
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $form wirksames Formular (FormFactory::effective)
|
||||
* @param array<string, mixed> $values Eingaben des Besuchers, nach Feldkennung
|
||||
* @return array{steps: array<string, bool>, groups: array<string, bool>, fields: array<string, bool>, required: array<string, bool>, presets: array<string, string>, 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<string, mixed> $form
|
||||
* @param array<string, mixed> $values
|
||||
* @param array<string, mixed> $state
|
||||
* @param array<string, string|array<int, string>|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<array<string, mixed>> $rules
|
||||
* @param array<string, mixed> $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<array<string, mixed>> $rules
|
||||
* @param array<string, mixed> $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<string, mixed> $rule
|
||||
* @param array<string, mixed> $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<string, mixed> $condition
|
||||
* @param array<string, mixed> $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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Baut aus einer veröffentlichten Fassung und der Konfiguration eines Anfrage-Einstiegs das wirksame Formular:
|
||||
* zugelassene Anliegen, Texte, Darstellung und Vorbelegung. Dieselbe Funktion bedient Besucher, Vorschau und
|
||||
* Anfrageservice, damit nirgends eine zweite Auslegung entsteht.
|
||||
*/
|
||||
final class FormFactory
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $definition aufgelöste Fassung (TemplateCompiler)
|
||||
* @param array<string, mixed> $config Konfiguration des Einstiegs (veröffentlichter Stand oder Entwurf)
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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<string, mixed> $form
|
||||
* @param array<string, mixed> $wanted
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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<string, mixed> $form
|
||||
* @return list<string>
|
||||
*/
|
||||
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<string, mixed> $definition
|
||||
* @param array<string, mixed> $config
|
||||
* @return list<string>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Vergleichbare Form für gespeicherte Konfigurationen: Schlüssel sortiert, Listen unverändert, Skalare als Text.
|
||||
*/
|
||||
final class FormJson
|
||||
{
|
||||
/**
|
||||
* @param array<mixed> $value
|
||||
* @return array<mixed>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Die Texte eines Anfrageformulars. Die Vorlage legt sie fest, ein Anfrage-Einstieg darf sie überschreiben.
|
||||
* Alle Texte werden ausschließlich in der Kommunikationsverwaltung gepflegt (ADR-60).
|
||||
*/
|
||||
final class FormTexts
|
||||
{
|
||||
/** Schlüssel => [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<string, string>
|
||||
*/
|
||||
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<string, mixed> ...$layers von der schwächsten zur stärksten Schicht
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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<string, mixed> $texts
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Verschlüsseltes Formular-Token, das mit dem Formular ausgeliefert wird. Es trägt Einstieg, Fassung, Zeitpunkt und
|
||||
* eine einmalige Kennung. Daraus folgen:
|
||||
* - die Anfrage bezieht sich auf die Fassung, die der Besucher tatsächlich sah,
|
||||
* - eine zu schnelle Absendung und ein abgelaufenes Formular lassen sich erkennen,
|
||||
* - doppeltes Absenden ergibt dieselbe Anfrage (Einmalkennung).
|
||||
* Nichts davon steht in der gespeicherten Seite; die Seite enthält nur die Kennung des Einstiegs.
|
||||
*/
|
||||
final class FormToken
|
||||
{
|
||||
public static function issue(int $entryId, int $versionId): string
|
||||
{
|
||||
return Crypt::encryptString(json_encode([
|
||||
'e' => $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']];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Eine eingegangene Anfrage. answers hält Bezeichnungen und Werte, wie sie der Besucher sah; sie bleiben auch nach
|
||||
* einer Änderung der zentralen Konfiguration lesbar.
|
||||
*/
|
||||
class Inquiry extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'reference', 'entry_id', 'template_version_id', 'submission_token', 'issue_key', 'issue_label', 'subissue_key',
|
||||
'subissue_label', 'contact_name', 'contact_email', 'contact_phone', 'organisation', 'message', 'answers',
|
||||
'source_path', 'status', 'notified_at', 'notification_error',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['answers' => '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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anfrage-Einstieg: die veröffentlichbare Nutzungsvariante einer Anfragevorlage. config ist der Entwurf,
|
||||
* published_config der wirksame Stand.
|
||||
*/
|
||||
class InquiryEntry extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'template_id', 'config', 'published_config', 'published_at', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['config' => '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<string, mixed>
|
||||
*/
|
||||
public static function emptyConfig(): array
|
||||
{
|
||||
return [
|
||||
'mode' => 'compact',
|
||||
'open' => 'inline',
|
||||
'allowed_issues' => [],
|
||||
'allowed_subissues' => [],
|
||||
'defaults' => [],
|
||||
'texts' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Eingabefeld des Feldkatalogs. Wiederverwendbar in beliebig vielen Feldgruppen und Vorlagen.
|
||||
*/
|
||||
class InquiryField extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'label', 'help', 'type', 'options', 'settings', 'purpose', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'type' => 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<array{key: string, label: string}>
|
||||
*/
|
||||
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<string, mixed>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Fachliche Zusammenstellung von Feldern. items: geordnete Liste [{field: Kennung, required: bool}].
|
||||
*/
|
||||
class InquiryFieldGroup extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'label', 'description', 'items', 'sort_order', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['items' => '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<array{field: string, required: bool}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anliegen (oberste Ebene) oder Unteranliegen. Wird nie gelöscht, nur deaktiviert oder archiviert.
|
||||
*/
|
||||
class InquiryIssue extends Model
|
||||
{
|
||||
protected $fillable = ['parent_id', 'key', 'label', 'description', 'sort_order', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['active' => '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<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class InquiryNote extends Model
|
||||
{
|
||||
protected $fillable = ['inquiry_id', 'user_id', 'body'];
|
||||
|
||||
public function inquiry(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inquiry::class);
|
||||
}
|
||||
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Jobs\SendInquiryNotification;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Zentraler Anfrageservice (ADR-60): jeder öffentliche Anfrage-Einstieg sendet hierher, unabhängig von der Seite.
|
||||
*
|
||||
* 1. gültige veröffentlichte Konfiguration ermitteln, 2. Token prüfen, 3. Bedingungen auswerten, 4. serverseitig
|
||||
* validieren, 5. speichern, 6. erst danach benachrichtigen, 7. Ergebnis melden.
|
||||
* Der Browser entscheidet nichts: Werte ausgeblendeter Felder werden verworfen, unbekannte Schlüssel und Auswahlwerte
|
||||
* zurückgewiesen.
|
||||
*/
|
||||
final class InquiryService
|
||||
{
|
||||
public function __construct(private readonly FormFactory $factory, private readonly FormEvaluator $evaluator) {}
|
||||
|
||||
/**
|
||||
* Die Fassung und das wirksame Formular für einen Besucher. Null, wenn der Einstieg nicht ausgeliefert wird.
|
||||
*
|
||||
* @return array{form: array<string, mixed>, 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<string, mixed> $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<string, mixed> $form
|
||||
* @param array<string, mixed> $values
|
||||
* @return array{answers: list<array<string, mixed>>, contact: array<string, string>, issue: ?array<string, string>, subissue: ?array<string, string>}
|
||||
*
|
||||
* @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<string, mixed> $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<string, mixed> $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
enum InquiryStatus: string
|
||||
{
|
||||
case Neu = 'neu';
|
||||
case InBearbeitung = 'in_bearbeitung';
|
||||
case RueckfrageOffen = 'rueckfrage_offen';
|
||||
case Erledigt = 'erledigt';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Neu => '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<string, string>
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (self::cases() as $case) {
|
||||
$options[$case->value] = $case->label();
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anfragevorlage: bearbeitbarer Entwurf (draft) und unveränderliche, veröffentlichte Fassungen.
|
||||
*/
|
||||
class InquiryTemplate extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'description', 'draft', 'published_version_id', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['draft' => '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<string, mixed>
|
||||
*/
|
||||
public static function emptyDraft(): array
|
||||
{
|
||||
return [
|
||||
'texts' => [],
|
||||
'issues' => [],
|
||||
'steps' => [],
|
||||
'rules' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Unveränderliche Fassung einer Anfragevorlage. definition ist vollständig aufgelöst (Bezeichnungen, Auswahlwerte,
|
||||
* Regeln); source ist der bearbeitbare Entwurf, aus dem sie entstand. Eine Fassung wird nie geändert.
|
||||
*/
|
||||
class InquiryTemplateVersion extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = ['template_id', 'version', 'definition', 'source', 'note', 'published_by', 'published_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['definition' => '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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Stabile technische Kennungen für Anliegen, Felder, Gruppen und Auswahlwerte. Eine Kennung entsteht einmal aus der
|
||||
* Bezeichnung und ändert sich nie; die öffentliche Bezeichnung darf sich ändern (ADR-60).
|
||||
*/
|
||||
final class Keys
|
||||
{
|
||||
public const PATTERN = '/^[a-z][a-z0-9_]{1,59}$/';
|
||||
|
||||
/** Kennungen der eingebauten Anliegen-Felder; Felder des Katalogs dürfen sie nicht belegen. */
|
||||
public const RESERVED = ['anliegen', 'unteranliegen'];
|
||||
|
||||
public static function valid(mixed $key): bool
|
||||
{
|
||||
return is_string($key) && preg_match(self::PATTERN, $key) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt aus einer Bezeichnung eine freie Kennung. $taken enthält bereits vergebene Kennungen.
|
||||
*
|
||||
* @param list<string> $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Veröffentlichung von Anfragevorlagen und Anfrage-Einstiegen (ADR-60).
|
||||
*
|
||||
* Eine Vorlage wird als neue, unveränderliche Fassung veröffentlicht; bis dahin gilt die bisherige Fassung. Ein Einstieg
|
||||
* veröffentlicht seine Konfiguration gegen die aktuell gültige Fassung seiner Vorlage. Wirksam ist immer nur ein
|
||||
* bewusst veröffentlichter Stand, nie ein Entwurf.
|
||||
*/
|
||||
final class Publisher
|
||||
{
|
||||
public function __construct(private readonly TemplateCompiler $compiler, private readonly FormFactory $factory) {}
|
||||
|
||||
/**
|
||||
* Einstiege, die von einer neuen Fassung betroffen sind, samt Befund gegen die neue Fassung.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
* @return list<array{entry: InquiryEntry, problems: list<string>}>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Eine Einsendung wurde zurückgewiesen. fields: Feldkennung => Meldung. Der Code entspricht dem HTTP-Status.
|
||||
*/
|
||||
final class SubmissionException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
public function __construct(string $message, public readonly array $fields = [], int $code = 422)
|
||||
{
|
||||
parent::__construct($message, $code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Übersetzt den bearbeitbaren Entwurf einer Anfragevorlage in eine vollständig aufgelöste Definition (Fassung) und prüft
|
||||
* dabei die Konfiguration: Verweise, doppelte Verwendung, Regeln und deren Reihenfolge. Kein Skript, keine freien
|
||||
* Ausdrücke: Regeln sind Daten aus einer festen Menge von Operatoren und Wirkungen (ADR-60).
|
||||
*
|
||||
* Entwurf: {texts, issues[Kennungen oberster Anliegen], steps[{key,title,intro,items[{kind,...}]}], rules[...]}
|
||||
* Reihenfolge ist Dokumentreihenfolge: Schritte, darin Bausteine, darin Felder. Eine Bedingung darf nur auf Felder
|
||||
* verweisen, die vor ihrem Ziel stehen; damit sind Zyklen ausgeschlossen.
|
||||
*/
|
||||
final class TemplateCompiler
|
||||
{
|
||||
public const EFFECTS = [
|
||||
'show' => '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<string, mixed> $draft
|
||||
* @return array{definition: ?array<string, mixed>, errors: list<string>}
|
||||
*/
|
||||
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<string, mixed> $draft
|
||||
* @return array{definition: ?array<string, mixed>, errors: list<string>}
|
||||
*/
|
||||
public function preview(array $draft): array
|
||||
{
|
||||
return $this->compile($draft);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $only
|
||||
* @return list<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
|
||||
*/
|
||||
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<int|string, mixed> $rules
|
||||
* @param array<string, array<string, mixed>> $fields
|
||||
* @param list<array<string, mixed>> $tree
|
||||
* @param array<string, int> $position
|
||||
* @param list<string> $stepKeys
|
||||
* @param array<string, true> $usedGroups
|
||||
* @param list<string> $errors
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Domain\Communication\CommunicationSettings;
|
||||
use App\Domain\Communication\Inquiry;
|
||||
use App\Mail\InquiryReceived;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Interne Benachrichtigung über eine neue Anfrage. Die Anfrage ist zu diesem Zeitpunkt bereits gespeichert; ein Fehler
|
||||
* hier wird an der Anfrage vermerkt (notification_error), geht nie verloren und lässt sich in der Verwaltung wiederholen.
|
||||
*/
|
||||
class SendInquiryNotification implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public int $tries = 1;
|
||||
|
||||
public function __construct(public int $inquiryId) {}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$inquiry = Inquiry::query()->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Domain\Communication\Inquiry;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
|
||||
/**
|
||||
* Interne Benachrichtigung. Sie nennt nur Kennzeichen, Anliegen und den Weg zur Anfrage; Kontaktdaten und Antworten
|
||||
* stehen ausschließlich in der Verwaltung (Datensparsamkeit).
|
||||
*/
|
||||
class InquiryReceived extends Mailable
|
||||
{
|
||||
public function __construct(public Inquiry $inquiry) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(subject: 'Neue Anfrage '.$this->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),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
| Anfrageformulare (ADR-60). Das Formular-Token bindet eine Einsendung an das ausgelieferte Formular.
|
||||
*/
|
||||
'token_ttl_hours' => 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,
|
||||
|
||||
];
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Zentrale Kommunikationsverwaltung (ADR-60): nur neue Tabellen, nichts Bestehendes wird verändert.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('inquiry_issues', function (Blueprint $table): void {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -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.
|
||||
@@ -0,0 +1,438 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Domain\Communication\CommunicationSettings;
|
||||
use App\Domain\Communication\ExampleConfiguration;
|
||||
use App\Domain\Communication\FormEvaluator;
|
||||
use App\Domain\Communication\FormFactory;
|
||||
use App\Domain\Communication\FormToken;
|
||||
use App\Domain\Communication\Inquiry;
|
||||
use App\Domain\Communication\InquiryEntry;
|
||||
use App\Domain\Communication\InquiryField;
|
||||
use App\Domain\Communication\InquiryService;
|
||||
use App\Domain\Communication\InquiryStatus;
|
||||
use App\Domain\Communication\InquiryTemplate;
|
||||
use App\Domain\Communication\InquiryTemplateVersion;
|
||||
use App\Domain\Communication\Publisher;
|
||||
use App\Domain\Communication\SubmissionException;
|
||||
use App\Mail\InquiryReceived;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CommunicationInquiryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config(['communication.min_fill_seconds' => 0]);
|
||||
app(ExampleConfiguration::class)->install();
|
||||
}
|
||||
|
||||
private function entry(string $key): InquiryEntry
|
||||
{
|
||||
return InquiryEntry::query()->where('key', $key)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $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<string, mixed> */
|
||||
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()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user