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:
LarsandClaude Sonnet 5.5 committed 2026-11-27 17:26:42 +01:00
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);
}
}
}
+56
View File
@@ -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;
}
}
+62
View File
@@ -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;
}
}
+286
View File
@@ -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'), ',');
}
}
+210
View File
@@ -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,
};
}
}
+179
View File
@@ -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;
}
}
+34
View File
@@ -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;
}
}
+85
View File
@@ -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;
}
}
+50
View File
@@ -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']];
}
}
+51
View File
@@ -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');
}
}
+64
View File
@@ -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' => [],
];
}
}
+75
View File
@@ -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;
}
}
+69
View File
@@ -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;
}
}
+22
View File
@@ -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');
}
}
+292
View File
@@ -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);
}
}
+48
View File
@@ -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;
}
}
+144
View File
@@ -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);
}
}
+53
View File
@@ -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();
}
}
+35
View File
@@ -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),
],
);
}
}