Bearbeite ein Formular vollständig in einem Editor und reduziere die Navigation der Kommunikation
CI Feature / test (push) Successful in 4m17s

Der Editor zeigt Bereiche mit Feldern und Teilbereichen; Felder werden direkt im Bereich angelegt oder aus dem Katalog
übernommen und landen im selben Katalog wie bisher. Bedingungen stehen am Feld, Teilbereich oder Bereich und werden zu
denselben Regeln wie die Regelliste; alles andere bleibt unter „Weitere Regeln“. Navigation: Anfragen, Formulare &
Befragungen, Einstellungen. Anliegen, Feldkatalog, Feldgruppen und Einstiege bleiben erreichbar (Einstellungen).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-27 22:37:32 +01:00
1 parent fb479c1b01
commit 7302ac78e9
11 files changed
+1121 -130

No files matched your search

+501
View File
@@ -0,0 +1,501 @@
<?php
namespace App\Domain\Communication;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Übersetzung zwischen dem Entwurf einer Vorlage (Schritte mit Feldgruppen und Einzelfeldern, Regeln; ADR-60) und der
* flachen Bearbeitungsansicht des Formular-Editors (ADR-61): Bereiche mit Feldern und Teilbereichen, Bedingungen direkt am
* Element. Die Engine bleibt unverändert; der Editor schreibt Felder und Teilbereiche in denselben Katalog, aus dem die
* Vorlage sie liest, und erzeugt aus den Bedingungen am Element dieselben Regeln wie die Regelliste.
*
* Ansicht (Builder-Format der Verwaltung):
* areas[] {key, title, intro, cond, items[]}
* items[] {type: field|section|end|issue, data: {...}} (end: Ende eines Teilbereichs; danach folgen Einzelfelder)
* cond {effect, match, conditions[{source, op, values[]}], pos} (leer: keine Bedingung)
* rules[] Regeln, die sich nicht an ein Element heften lassen (zusätzliche Regeln desselben Ziels, Vorbelegungen)
*
* Ein Teilbereich ist eine Überschrift im Fluss: Die Felder bis zum nächsten Teilbereich gehören zu ihm (Feldgruppe).
* Neue Elemente tragen eine vorläufige Kennung (tmp_…), die beim Speichern durch eine feste ersetzt wird.
*/
final class FormEditor
{
/** Wirkungen, die ein Element selbst trägt, je Art des Ziels. */
public const EFFECTS = [
'step' => ['show', 'hide', 'skip'],
'group' => ['show', 'hide'],
'field' => ['show', 'hide', 'require'],
];
/**
* @param array<string, mixed> $draft
* @param ?int $exceptTemplate die bearbeitete Vorlage: Sie zählt nicht als „auch verwendet in“
* @return array{issues: list<string>, areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function expand(array $draft, ?int $exceptTemplate = null): array
{
$fields = InquiryField::query()->get()->keyBy('key');
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = $this->usage($exceptTemplate);
$byTarget = [];
$rules = array_values(array_filter((array) ($draft['rules'] ?? []), 'is_array'));
foreach ($rules as $index => $rule) {
$byTarget[(string) ($rule['target'] ?? '')][] = $index;
}
$consumed = [];
$take = function (string $target, string $kind) use (&$byTarget, &$consumed, $rules): array {
foreach ($byTarget[$target] ?? [] as $index) {
if (isset($consumed[$index]) || ! in_array($rules[$index]['effect'] ?? null, self::EFFECTS[$kind], true)) {
continue;
}
$consumed[$index] = true;
return $this->cond($rules[$index], $index);
}
return [];
};
$areas = [];
$issueDone = false;
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$step = is_array($step) ? $step : [];
$key = (string) ($step['key'] ?? '');
$items = [];
$list = array_values((array) ($step['items'] ?? []));
foreach ($list as $position => $item) {
$item = is_array($item) ? $item : [];
$kind = (string) ($item['kind'] ?? '');
if ($kind === 'issue') {
$items[] = ['type' => 'issue', 'data' => ['issues' => $issueDone ? [] : array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'))]];
$issueDone = true;
} elseif ($kind === 'group') {
$groupKey = (string) ($item['group'] ?? '');
$group = $groups[$groupKey] ?? null;
$items[] = ['type' => 'section', 'data' => [
'key' => $groupKey,
'label' => $group === null ? 'Nicht mehr verfügbare Feldgruppe' : ($group->label ?: $group->name),
'description' => $group?->description,
'missing' => $group === null,
'used_in' => implode(', ', $usage['groups'][$groupKey] ?? []),
'cond' => $take('group:'.$groupKey, 'group'),
]];
foreach ($group?->itemList() ?? [] as $row) {
$field = $fields[$row['field']] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, $row['required'], $usage, $take)];
}
}
// Ein Einzelfeld direkt nach einer Feldgruppe gehört nicht zu ihr: Das Ende des Teilbereichs ist ausdrücklich.
if (($list[$position + 1]['kind'] ?? null) === 'field') {
$items[] = ['type' => 'end', 'data' => []];
}
} elseif ($kind === 'field') {
$field = $fields[(string) ($item['field'] ?? '')] ?? null;
if ($field !== null) {
$items[] = ['type' => 'field', 'data' => $this->fieldData($field, (bool) ($item['required'] ?? false), $usage, $take)];
}
}
}
$areas[] = [
'key' => $key,
'title' => (string) ($step['title'] ?? ''),
'intro' => $step['intro'] ?? null,
'cond' => $take('step:'.$key, 'step'),
'items' => $items,
];
}
$rest = [];
foreach ($rules as $index => $rule) {
if (! isset($consumed[$index])) {
$rest[] = $this->cond($rule, $index) + ['target' => (string) ($rule['target'] ?? ''), 'value' => $rule['value'] ?? null];
}
}
return [
'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')),
'areas' => $areas,
'rules' => $rest,
];
}
/**
* Speichert die Ansicht: legt neue Felder und Teilbereiche im Katalog an, aktualisiert bearbeitete und liefert den
* Entwurf (ohne Texte, die der Editor getrennt führt).
*
* @param array<string, mixed> $editor
* @return array{issues: list<string>, steps: list<array<string, mixed>>, rules: list<array<string, mixed>>}
*/
public function persist(array $editor): array
{
return DB::transaction(function () use ($editor): array {
$takenFields = InquiryField::query()->pluck('key')->all();
$takenGroups = InquiryFieldGroup::query()->pluck('key')->all();
$existingFields = InquiryField::query()->get()->keyBy('key');
$existingGroups = InquiryFieldGroup::query()->get()->keyBy('key');
$map = [];
$issues = [];
$steps = [];
$rules = [];
$order = 0;
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$area = is_array($area) ? $area : [];
$stepKey = Keys::valid($area['key'] ?? null) || preg_match('/^s[a-z0-9]{3,12}$/', (string) ($area['key'] ?? '')) === 1 ? (string) $area['key'] : 's'.Str::lower(Str::random(6));
$items = [];
$group = null;
$flush = function () use (&$group, &$items): void {
if ($group !== null) {
$items[] = $group;
$group = null;
}
};
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$block = is_array($block) ? $block : [];
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
switch ((string) ($block['type'] ?? '')) {
case 'issue':
$flush();
$items[] = ['kind' => 'issue'];
if ($issues === []) {
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
}
break;
case 'end':
$flush();
break;
case 'section':
$flush();
$original = (string) ($data['key'] ?? '');
$isMissing = (bool) ($data['missing'] ?? false);
$current = isset($existingGroups[$original]) ? $existingGroups[$original] : null;
$key = $current?->key ?? Keys::from((string) ($data['label'] ?? ''), $takenGroups);
$takenGroups[] = $key;
$map[$original] = $key;
$group = ['kind' => 'group', 'group' => $key, '_label' => trim((string) ($data['label'] ?? '')), '_description' => $data['description'] ?? null, '_rows' => [], '_current' => $current, '_missing' => $isMissing, '_new' => $current === null];
$this->rule($rules, 'group:'.$key, (array) ($data['cond'] ?? []), 'group', $order);
break;
case 'field':
$field = $this->saveField($data, $existingFields, $takenFields);
$original = (string) ($data['key'] ?? '');
$map[$original] = $field->key;
$required = (bool) ($data['required'] ?? false);
if ($group !== null) {
$group['_rows'][] = ['field' => $field->key, 'required' => $required];
} else {
$items[] = ['kind' => 'field', 'field' => $field->key, 'required' => $required];
}
$this->rule($rules, 'field:'.$field->key, (array) ($data['cond'] ?? []), 'field', $order);
break;
}
}
$flush();
$this->rule($rules, 'step:'.$stepKey, (array) ($area['cond'] ?? []), 'step', $order);
foreach ($items as $index => $item) {
if (($item['kind'] ?? null) !== 'group') {
continue;
}
$items[$index] = $this->saveGroup($item, $existingGroups, $takenGroups);
}
$steps[] = [
'key' => $stepKey,
'title' => mb_substr(trim((string) ($area['title'] ?? '')), 0, 120),
'intro' => filled($area['intro'] ?? null) ? mb_substr(trim((string) $area['intro']), 0, 600) : null,
'items' => $items,
];
}
foreach (array_values((array) ($editor['rules'] ?? [])) as $rule) {
$rule = is_array($rule) ? $rule : [];
$target = (string) ($rule['target'] ?? '');
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$rules[] = [
'effect' => (string) ($rule['effect'] ?? ''),
'target' => $kind === '' ? $target : $kind.':'.($map[$key] ?? $key),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $this->conditions((array) ($rule['conditions'] ?? []), $map),
'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null,
'_pos' => is_numeric($rule['pos'] ?? null) ? (int) $rule['pos'] : 1000 + $order++,
];
}
foreach ($rules as $index => $rule) {
$rules[$index]['conditions'] = $this->conditions((array) $rule['conditions'], $map);
}
usort($rules, fn (array $a, array $b): int => $a['_pos'] <=> $b['_pos']);
return [
'issues' => $issues,
'steps' => $steps,
'rules' => array_map(function (array $rule): array {
unset($rule['_pos']);
return $rule;
}, $rules),
];
});
}
/**
* Eine neue Zeile in der Karteikarte der Bedingungen (leer: Standardwerte).
*
* @return array<string, mixed>
*/
public static function newCondition(): array
{
return ['source' => null, 'op' => 'eq', 'values' => []];
}
/** Vorläufige Kennung eines neuen Feldes oder Teilbereichs. */
public static function temporaryKey(): string
{
return 'tmp_'.Str::lower(Str::random(8));
}
/**
* Verwendung von Feldern und Feldgruppen in Vorlagen: [Art => [Kennung => [Vorlagennamen]]]. Zeigt im Editor, wo
* eine Änderung noch wirkt (bei der nächsten Veröffentlichung dieser Vorlagen).
*
* @return array{fields: array<string, list<string>>, groups: array<string, list<string>>}
*/
public function usage(?int $exceptTemplate = null): array
{
$groups = InquiryFieldGroup::query()->get()->keyBy('key');
$usage = ['fields' => [], 'groups' => []];
foreach (InquiryTemplate::query()->whereNull('archived_at')->when($exceptTemplate !== null, fn ($query) => $query->whereKeyNot($exceptTemplate))->get() as $template) {
foreach ((array) ($template->draft['steps'] ?? []) as $step) {
foreach ((array) ($step['items'] ?? []) as $item) {
if (($item['kind'] ?? null) === 'field') {
$usage['fields'][(string) ($item['field'] ?? '')][$template->id] = $template->name;
} elseif (($item['kind'] ?? null) === 'group') {
$key = (string) ($item['group'] ?? '');
$usage['groups'][$key][$template->id] = $template->name;
foreach ($groups[$key]?->itemList() ?? [] as $row) {
$usage['fields'][$row['field']][$template->id] = $template->name;
}
}
}
}
}
return $usage;
}
/**
* @param array<string, mixed> $rule
* @return array<string, mixed>
*/
private function cond(array $rule, int $pos): array
{
return [
'effect' => (string) ($rule['effect'] ?? ''),
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => array_values(array_map(fn (mixed $condition): array => [
'source' => (string) ($condition['source'] ?? ''),
'op' => (string) ($condition['op'] ?? 'eq'),
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
], array_filter((array) ($rule['conditions'] ?? []), 'is_array'))),
'pos' => $pos,
];
}
/**
* @param array{fields: array<string, list<string>>, groups: array<string, list<string>>} $usage
* @return array<string, mixed>
*/
private function fieldData(InquiryField $field, bool $required, array $usage, callable $take): array
{
return [
'key' => $field->key,
'label' => $field->label,
'name' => $field->name,
'help' => $field->help,
'type' => $field->type->value,
'options' => $field->optionList(),
'required' => $required,
'purpose' => $field->purpose?->value,
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
'cond' => $take('field:'.$field->key, 'field'),
];
}
/**
* @param list<array<string, mixed>> $rules
* @param array<string, mixed> $cond
*/
private function rule(array &$rules, string $target, array $cond, string $kind, int &$order): void
{
$effect = (string) ($cond['effect'] ?? '');
$conditions = array_values(array_filter((array) ($cond['conditions'] ?? []), fn (mixed $c): bool => is_array($c) && filled($c['source'] ?? null)));
if ($effect === '' || ! in_array($effect, self::EFFECTS[$kind], true) || $conditions === []) {
return;
}
$rules[] = [
'effect' => $effect,
'target' => $target,
'match' => ($cond['match'] ?? 'all') === 'any' ? 'any' : 'all',
'conditions' => $conditions,
'value' => null,
'_pos' => is_numeric($cond['pos'] ?? null) ? (int) $cond['pos'] : 1000 + $order++,
];
}
/**
* @param array<int|string, mixed> $conditions
* @param array<string, string> $map
* @return list<array{source: string, op: string, values: list<string>}>
*/
private function conditions(array $conditions, array $map): array
{
$result = [];
foreach (array_values($conditions) as $condition) {
$condition = is_array($condition) ? $condition : [];
$source = (string) ($condition['source'] ?? '');
if ($source === '') {
continue;
}
$result[] = [
'source' => $map[$source] ?? $source,
'op' => in_array($condition['op'] ?? 'eq', array_keys(TemplateCompiler::OPERATORS), true) ? (string) ($condition['op'] ?? 'eq') : 'eq',
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
];
}
return $result;
}
/**
* @param array<string, mixed> $data
* @param Collection<string, InquiryField> $existing
* @param list<string> $taken
*/
private function saveField(array $data, $existing, array &$taken): InquiryField
{
$key = (string) ($data['key'] ?? '');
$label = mb_substr(trim((string) ($data['label'] ?? '')), 0, 200);
$help = filled($data['help'] ?? null) ? mb_substr(trim((string) $data['help']), 0, 600) : null;
$type = FieldType::tryFrom((string) ($data['type'] ?? '')) ?? FieldType::Text;
$purpose = FieldPurpose::tryFrom((string) ($data['purpose'] ?? ''));
$field = $existing[$key] ?? null;
if ($field !== null) {
$type = $field->type;
}
if ($purpose !== null && ! in_array($type, $purpose->types(), true)) {
$purpose = null;
}
$options = $type->hasOptions() ? Keys::withKeys(array_values((array) ($data['options'] ?? []))) : null;
if ($field === null) {
$final = Keys::from($label, $taken);
$taken[] = $final;
return InquiryField::query()->create([
'key' => $final,
'name' => mb_substr($label, 0, 120),
'label' => $label,
'help' => $help,
'type' => $type->value,
'options' => $options,
'settings' => null,
'purpose' => $purpose?->value,
'active' => true,
]);
}
$field->fill(['label' => $label, 'help' => $help, 'options' => $options ?? $field->options, 'purpose' => $purpose?->value]);
if ($field->isDirty()) {
$field->save();
}
return $field;
}
/**
* @param array<string, mixed> $group Teilbereich mit gesammelten Feldern (_rows)
* @param Collection<string, InquiryFieldGroup> $existing
* @param list<string> $taken
* @return array{kind: string, group: string}
*/
private function saveGroup(array $group, $existing, array &$taken): array
{
$item = ['kind' => 'group', 'group' => $group['group']];
if ($group['_missing']) {
return $item;
}
$label = mb_substr($group['_label'], 0, 200);
$description = filled($group['_description']) ? mb_substr(trim((string) $group['_description']), 0, 600) : null;
$current = $group['_current'];
if ($current === null) {
InquiryFieldGroup::query()->create([
'key' => $group['group'],
'name' => mb_substr($label, 0, 120),
'label' => $label,
'description' => $description,
'items' => $group['_rows'],
'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10,
'active' => true,
]);
return $item;
}
// Die Bezeichnung bleibt, wenn der Teilbereich vorher keine eigene öffentliche Überschrift hatte und unverändert ist.
$keepLabel = blank($current->label) && $label === $current->name;
$current->fill(['label' => $keepLabel ? null : $label, 'description' => $description, 'items' => $group['_rows']]);
if ($current->isDirty()) {
$current->save();
}
return $item;
}
}
@@ -5,6 +5,10 @@
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\CommunicationSettings;
use App\Domain\Communication\ExampleConfiguration;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use App\Mail\CommunicationTestMail;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
@@ -31,7 +35,7 @@ class KommunikationEinstellungen extends Page
protected static ?string $navigationLabel = 'Einstellungen';
protected static ?int $navigationSort = 7;
protected static ?int $navigationSort = 3;
protected static ?string $slug = 'kommunikation/einstellungen';
@@ -84,6 +88,17 @@ public function form(Schema $schema): Schema
}
}),
]),
Section::make('Weitere Bausteine')->description('Anliegen und der gemeinsame Feldkatalog gehören zu den Formularen. Im Formular-Editor müssen sie nicht geöffnet werden; hier lassen sie sich einsehen und ordnen.')
->visible(fn (): bool => CommunicationAccess::configure())
->collapsed()
->schema([
Actions::make([
Action::make('issues')->label('Anliegen')->url(InquiryIssueResource::getUrl('index'))->color('gray'),
Action::make('fields')->label('Feldkatalog')->url(InquiryFieldResource::getUrl('index'))->color('gray'),
Action::make('groups')->label('Feldgruppen')->url(InquiryFieldGroupResource::getUrl('index'))->color('gray'),
Action::make('entries')->label('Anfrage-Einstiege (ältere Seiten)')->url(InquiryEntryResource::getUrl('index'))->color('gray'),
]),
]),
Section::make('Aufbewahrung')->schema([
TextInput::make('retention_months')->label('Anfragen löschen nach … Monaten')->numeric()->minValue(1)->maxValue(120)
->helperText('Leer: Anfragen werden nicht automatisch gelöscht. Der Befehl „php artisan communication:purge“ löscht Anfragen, die älter sind. Einzelne Anfragen lassen sich jederzeit im Posteingang löschen. Die Dauer ist mit dem Datenschutzkonzept abzustimmen.'),
@@ -43,6 +43,12 @@ class InquiryEntryResource extends CommunicationResource
protected static ?int $navigationSort = 6;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -43,6 +43,12 @@ class InquiryFieldResource extends CommunicationResource
protected static ?int $navigationSort = 3;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
/**
* @return list<Component>
*/
@@ -36,6 +36,12 @@ class InquiryFieldGroupResource extends CommunicationResource
protected static ?int $navigationSort = 4;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -34,6 +34,12 @@ class InquiryIssueResource extends CommunicationResource
protected static ?int $navigationSort = 2;
/** Technischer Baustein des Formular-Editors: erreichbar über „Einstellungen“, nicht in der Hauptnavigation (ADR-61). */
public static function shouldRegisterNavigation(): bool
{
return false;
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -13,24 +13,24 @@
use Filament\Tables\Table;
/**
* Anfragevorlagen: ein vollständiger fachlicher Anfrageprozess. Der Entwurf ist frei bearbeitbar; wirksam wird nur eine
* Formulare & Befragungen (Anfragevorlagen): ein vollständiger fachlicher Anfrageprozess, bearbeitet im Formular-Editor (ADR-61). Der Entwurf ist frei bearbeitbar; wirksam wird nur eine
* bewusst veröffentlichte, unveränderliche Fassung.
*/
class InquiryTemplateResource extends CommunicationResource
{
protected static ?string $model = InquiryTemplate::class;
protected static ?string $navigationLabel = 'Anfragevorlagen';
protected static ?string $navigationLabel = 'Formulare & Befragungen';
protected static ?string $modelLabel = 'Anfragevorlage';
protected static ?string $modelLabel = 'Formular';
protected static ?string $pluralModelLabel = 'Anfragevorlagen';
protected static ?string $pluralModelLabel = 'Formulare & Befragungen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/vorlagen';
protected static ?int $navigationSort = 5;
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
@@ -2,6 +2,7 @@
namespace App\Filament\Resources\Communication\Templates\Pages;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use App\Domain\Communication\TemplateCompiler;
@@ -38,7 +39,7 @@ public function getSubheading(): string|Htmlable|null
}
if (! $template->isPublished()) {
return 'Noch nicht veröffentlicht. Besucher sehen diese Vorlage erst nach „Veröffentlichen“.';
return 'Noch nicht veröffentlicht. Besucher sehen dieses Formular erst nach „Veröffentlichen“.';
}
$version = $template->publishedVersion;
@@ -76,7 +77,7 @@ protected function getHeaderActions(): array
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->modalHeading('Neue Fassung veröffentlichen')
->modalHeading('Formular veröffentlichen')
->modalSubmitActionLabel('Jetzt veröffentlichen')
->modalWidth('2xl')
->schema(fn (): array => [
@@ -89,7 +90,7 @@ protected function getHeaderActions(): array
try {
$version = app(Publisher::class)->publishTemplate($this->getRecord(), auth('staff')->user() instanceof User ? auth('staff')->user() : null, $data['note'] ?? null);
} catch (ValidationException $e) {
Notification::make()->title('Die Vorlage lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send();
Notification::make()->title('Das Formular lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['draft'] ?? []))))->danger()->persistent()->send();
return;
}
@@ -107,17 +108,17 @@ private function affectedText(): string
$rows = app(Publisher::class)->affected($this->getRecord());
if ($rows === []) {
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Noch kein Anfrage-Einstieg verwendet diese Vorlage.';
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
$names = array_map(fn (array $row): string => $row['entry']->name.($row['entry']->published_config !== null ? ' (veröffentlicht)' : ' (Entwurf)'), $rows);
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sofort betroffen sind diese Anfrage-Einstiege und damit alle Seiten, die sie einbinden: '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
return 'Speichert den Entwurf und veröffentlicht ihn als neue Fassung. Sie gilt sofort überall, wo das Formular im Widget „Anfrage“ eingebunden ist, und für diese Anfrage-Einstiege (ältere Seiten): '.implode(', ', $names).'. Die bisherige Fassung bleibt als Verlauf erhalten und lässt sich wieder in Kraft setzen.';
}
protected function archiveNote(): string
{
return 'Die Vorlage wird archiviert. Anfrage-Einstiege, die sie verwenden, liefern dann kein Formular mehr aus. Eingegangene Anfragen bleiben unverändert.';
return 'Das Formular wird archiviert. Seiten, die es einbinden, bieten es dann nicht mehr an (auch Anfrage-Einstiege liefern nichts mehr aus). Eingegangene Anfragen bleiben unverändert.';
}
protected function archiveAttributes(): array
@@ -134,16 +135,38 @@ protected function archiveBlocked(): ?string
{
$live = $this->getRecord()->entries()->live()->count();
return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit dieser Vorlage. Bitte zuerst zurückziehen oder auf eine andere Vorlage umstellen." : null;
return $live > 0 ? "Es gibt noch $live veröffentlichte Anfrage-Einstiege mit diesem Formular. Bitte zuerst zurückziehen oder auf ein anderes Formular umstellen." : null;
}
protected function mutateFormDataBeforeFill(array $data): array
{
$data['editor'] = app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey());
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$data['draft'] = TemplateDraft::clean((array) ($data['draft'] ?? []));
// Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf.
$saved = app(FormEditor::class)->persist((array) ($data['editor'] ?? []));
unset($data['editor']);
$data['draft'] = TemplateDraft::clean([
'texts' => (array) ($data['draft']['texts'] ?? []),
'issues' => $saved['issues'],
'steps' => $saved['steps'],
'rules' => $saved['rules'],
]);
return $data;
}
protected function afterSave(): void
{
// Neue Felder und Teilbereiche tragen jetzt ihre festen Kennungen. Ohne neues Laden würde ein zweites Speichern sie doppelt anlegen.
$this->fillForm();
}
protected function getRedirectUrl(): ?string
{
return null;
@@ -22,19 +22,19 @@ class ListInquiryTemplates extends ListRecords
public function getSubheading(): string|Htmlable|null
{
return 'Eine Anfragevorlage beschreibt einen vollständigen Anfrageprozess: Schritte, Feldgruppen, Bedingungen und Texte. Änderungen entstehen zunächst als Entwurf und gelten erst nach „Veröffentlichen“. Die Anfrage-Einstiege, die eine Vorlage verwenden, übernehmen jede neu veröffentlichte Fassung.';
return 'Hier entstehen Formulare und Befragungen: Bereiche mit Feldern, Bedingungen und Texte, alles in einem Editor. Änderungen sind zunächst ein Entwurf und gelten erst nach „Veröffentlichen“. Im Widget „Anfrage“ einer Seite wählst du, welches Formular zu welchem Anfragegrund gehört.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Vorlage anlegen')
->modalHeading('Neue Anfragevorlage')
->modalDescription('Der Aufbau entsteht danach auf der Seite der Vorlage.')
->modalSubmitActionLabel('Vorlage anlegen')
->label('Formular anlegen')
->modalHeading('Neues Formular')
->modalDescription('Der Aufbau entsteht danach im Editor des Formulars.')
->modalSubmitActionLabel('Formular anlegen')
->schema([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120),
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400),
])
->action(function (array $data): void {
@@ -48,7 +48,7 @@ protected function getHeaderActions(): array
'draft' => $draft,
]);
Notification::make()->title('Die Vorlage ist angelegt.')->success()->send();
Notification::make()->title('Das Formular ist angelegt.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template]));
}),
];
@@ -68,7 +68,7 @@ protected function catalogRows(): array
$rows[] = [
'schluessel' => 't'.$template->id,
'titel' => $template->name,
'meta' => 'Anfragevorlage · '.$steps.' '.($steps === 1 ? 'Schritt' : 'Schritte').' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege'),
'meta' => 'Formular · '.$steps.' '.($steps === 1 ? 'Bereich' : 'Bereiche').($template->entries_count > 0 ? ' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege').' (ältere Seiten)' : ''),
'text' => (string) ($template->description ?? ''),
'symbol' => 'modul',
'url' => $url,
@@ -104,11 +104,11 @@ protected function suchPlatzhalter(): string
protected function einheit(): array
{
return ['Anfragevorlage', 'Anfragevorlagen'];
return ['Formular', 'Formulare'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfragevorlagen', 'text' => 'Mit „Vorlage anlegen“ oben entsteht die erste Vorlage. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
return ['titel' => 'Noch keine Formulare', 'text' => 'Mit „Formular anlegen“ oben entsteht das erste Formular. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
+262 -106
View File
@@ -2,12 +2,15 @@
namespace App\Filament\Support;
use App\Domain\Communication\FieldPurpose;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\TemplateCompiler;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
@@ -18,28 +21,38 @@
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\Str;
/**
* Formular der Anfragevorlage: Aufbau (Schritte, Feldgruppen, Einzelfelder), Regeln und Texte. Alles sind Auswahlfelder
* und Listen; es gibt keine freie Eingabe von Ausdrücken oder JSON. Die Auswahllisten der Regeln (Ziele, Quellen, Werte)
* leiten sich aus dem gerade bearbeiteten Aufbau ab.
* Formular-Editor (ADR-61): ein Formular wird an einer Stelle bearbeitet. Es besteht aus Bereichen (im mehrstufigen Dialog
* je ein Schritt), darin Felder und Teilbereiche, Bedingungen direkt am Element. Felder werden hier angelegt und
* geändert; sie landen im selben Katalog wie bisher (FormEditor). Die Regelliste bleibt für alles, was sich nicht an ein
* Element heften lässt. Alles sind Auswahlfelder und Listen; es gibt keine freie Eingabe von Ausdrücken oder JSON.
*/
final class TemplateEditor
{
private const EFFECT_LABELS = [
'step' => ['show' => 'Bereich nur anzeigen, wenn …', 'hide' => 'Bereich ausblenden, wenn …', 'skip' => 'Bereich überspringen, wenn …'],
'group' => ['show' => 'Teilbereich nur anzeigen, wenn …', 'hide' => 'Teilbereich ausblenden, wenn …'],
'field' => ['show' => 'Feld nur anzeigen, wenn …', 'hide' => 'Feld ausblenden, wenn …', 'require' => 'Pflichtfeld, wenn …'],
];
/**
* @return list<Component>
*/
public static function schema(): array
{
return [
TextInput::make('name')->label('Bezeichnung der Vorlage')->required()->maxLength(120),
TextInput::make('name')->label('Name des Formulars')->required()->maxLength(120)
->helperText('So heißt das Formular in der Verwaltung und in der Auswahl des Widgets „Anfrage“.'),
Textarea::make('description')->label('Beschreibung (nur Verwaltung)')->rows(2)->maxLength(400),
Tabs::make('vorlage')->persistTabInQueryString('bereich')->tabs([
Tab::make('Aufbau')->icon('heroicon-o-queue-list')->schema(self::structure()),
Tab::make('Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
Tab::make('Texte')->icon('heroicon-o-chat-bubble-bottom-center-text')->schema(self::texts()),
Tab::make('Weitere Regeln')->icon('heroicon-o-adjustments-horizontal')->schema(self::rules()),
]),
];
}
@@ -50,50 +63,171 @@ public static function schema(): array
private static function structure(): array
{
return [
Select::make('draft.issues')->label('Unterstützte Anliegen')->multiple()->live()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Welche Anliegen diese Vorlage kennt. Leer: alle angebotenen. Ein Anfrage-Einstieg kann daraus weiter auswählen.'),
Repeater::make('draft.steps')
->label('Schritte')
->helperText('Jeder Schritt ist im mehrstufigen Dialog eine Seite. Im Kompaktformular stehen alle Schritte untereinander. Die Reihenfolge von oben nach unten ist die Reihenfolge der Fragen und zugleich die Reihenfolge, in der Bedingungen ausgewertet werden.')
Text::make('Ein Formular besteht aus Bereichen. Im mehrstufigen Dialog ist jeder Bereich ein Schritt, im langen Formular stehen alle Bereiche untereinander. In einem Bereich legst du Felder an; ein Teilbereich fasst Felder unter einer Überschrift zusammen. Bedingungen stehen direkt am Feld oder Bereich. Neue Felder und Auswahlwerte stehen in Bedingungen zur Verfügung, sobald das Formular einmal gespeichert ist.'),
Repeater::make('editor.areas')
->label('Bereiche')
->schema([
Hidden::make('key')->default(fn (): string => 's'.Str::lower(Str::random(6))),
TextInput::make('title')->label('Titel des Schritts')->required()->maxLength(120)->live(onBlur: true),
TextInput::make('title')->label('Titel des Bereichs')->required()->maxLength(120)->live(onBlur: true)
->helperText('Im mehrstufigen Dialog die Überschrift des Schritts.'),
Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(600),
Repeater::make('items')
->label('Inhalt des Schritts')
->schema([
Select::make('kind')->label('Art')->required()->live()->options([
'issue' => 'Auswahl des Anliegens',
'group' => 'Feldgruppe',
'field' => 'Einzelnes Feld',
]),
Select::make('group')->label('Feldgruppe')->searchable()->live()
->options(fn (): array => InquiryFieldGroup::query()->offered()->orderBy('sort_order')->pluck('name', 'key')->all())
->visible(fn (Get $get): bool => $get('kind') === 'group')->required(fn (Get $get): bool => $get('kind') === 'group'),
Select::make('field')->label('Feld')->searchable()->live()
->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->pluck('name', 'key')->all())
->visible(fn (Get $get): bool => $get('kind') === 'field')->required(fn (Get $get): bool => $get('kind') === 'field'),
Toggle::make('required')->label('Pflichtfeld')
->visible(fn (Get $get): bool => $get('kind') === 'field'),
])
self::condition('step'),
Builder::make('items')
->label('Inhalt des Bereichs')
->blocks(self::blocks())
->addActionLabel('Feld oder Teilbereich hinzufügen')
->blockPickerColumns(2)
->blockNumbers(false)
->reorderableWithButtons()
->addActionLabel('Baustein hinzufügen')
->itemLabel(fn (array $state): string => match ($state['kind'] ?? null) {
'issue' => 'Auswahl des Anliegens',
'group' => 'Feldgruppe: '.(InquiryFieldGroup::query()->where('key', $state['group'] ?? '')->value('name') ?? '…'),
'field' => 'Feld: '.(InquiryField::query()->where('key', $state['field'] ?? '')->value('name') ?? '…'),
default => 'Neuer Baustein',
}),
->collapsible()
->collapsed()
->live(),
])
->reorderableWithButtons()
->collapsible()
->addActionLabel('Schritt hinzufügen')
->addActionLabel('Bereich hinzufügen')
->live()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Neuer Schritt'),
->itemLabel(fn (array $state): string => (($state['title'] ?? '') ?: 'Neuer Bereich').(filled($state['cond']['effect'] ?? null) ? ' · mit Bedingung' : '')),
];
}
/**
* @return list<Block>
*/
private static function blocks(): array
{
return [
Block::make('field')
->label(fn (?array $state): string => 'Feld: '.(($state['label'] ?? '') ?: 'neu').self::fieldBadges($state))
->icon('heroicon-o-pencil-square')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('name'),
Hidden::make('used_in'),
Select::make('pick')->label('Vorhandenes Feld verwenden (optional)')->searchable()->live()->dehydrated(false)
->options(fn ($livewire): array => self::catalogFields((array) ($livewire->data['editor'] ?? [])))
->placeholder('Neues Feld anlegen')
->visible(fn (Get $get): bool => str_starts_with((string) $get('key'), 'tmp_'))
->afterStateUpdated(function ($state, Set $set): void {
$field = filled($state) ? InquiryField::query()->where('key', $state)->first() : null;
if ($field === null) {
return;
}
$set('key', $field->key);
$set('name', $field->name);
$set('label', $field->label);
$set('help', $field->help);
$set('type', $field->type->value);
$set('options', $field->optionList());
$set('purpose', $field->purpose?->value);
$set('pick', null);
})
->helperText('Felder wie „E-Mail-Adresse“ lassen sich in mehreren Formularen verwenden.'),
TextInput::make('label')->label('Frage oder Beschriftung im Formular')->required()->maxLength(200)->live(onBlur: true),
Select::make('type')->label('Art der Antwort')->required()->live()->dehydrated()
->options(FieldType::options())
->disabled(fn (Get $get): bool => ! str_starts_with((string) $get('key'), 'tmp_'))
->helperText('Nach dem Speichern nicht mehr änderbar, weil Bedingungen und bisherige Anfragen darauf aufbauen. Soll sich die Art ändern, lege ein neues Feld an.'),
Repeater::make('options')->label('Auswahlwerte')
->schema([Hidden::make('key'), TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120)])
->reorderableWithButtons()
->addActionLabel('Auswahlwert hinzufügen')
->minItems(1)
->itemLabel(fn (array $state): ?string => $state['label'] ?? null)
->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false)
->helperText('Jeder Wert behält seine feste interne Kennung; eine Umbenennung beschädigt keine Anfragen.'),
Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600)->helperText('Steht unter der Frage.'),
Toggle::make('required')->label('Pflichtfeld'),
Section::make('Weitere Einstellungen')->compact()->collapsed()->schema([
Select::make('purpose')->label('Verwendung in der Anfrageübersicht')->options(FieldPurpose::options())->placeholder('Keine besondere Verwendung')
->helperText('Welche Angabe der Posteingang als Name, E-Mail-Adresse oder Nachricht zeigt. Jedes Formular braucht ein Feld „E-Mail-Adresse für Rückfragen“.'),
]),
Text::make(fn (Get $get): string => 'Dieses Feld wird auch in diesen Formularen verwendet: '.$get('used_in').'. Eine Änderung gilt dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('field'),
]),
Block::make('section')
->label(fn (?array $state): string => 'Teilbereich: '.(($state['label'] ?? '') ?: 'neu').(filled($state['cond']['effect'] ?? null) ? ' (Bedingung)' : ''))
->icon('heroicon-o-rectangle-group')
->schema([
Hidden::make('key')->default(fn (): string => FormEditor::temporaryKey()),
Hidden::make('missing')->default(false),
Hidden::make('used_in'),
TextInput::make('label')->label('Überschrift des Teilbereichs')->required()->maxLength(200)->live(onBlur: true)
->helperText('Die Felder darunter stehen im Formular unter dieser Überschrift, bis ein weiterer Teilbereich oder „Ende des Teilbereichs“ folgt.'),
Textarea::make('description')->label('Erläuterung (optional)')->rows(2)->maxLength(600),
Text::make(fn (Get $get): string => 'Dieser Teilbereich wird auch in diesen Formularen verwendet: '.$get('used_in').'. Änderungen an seinen Feldern gelten dort mit der nächsten Veröffentlichung.')
->visible(fn (Get $get): bool => filled($get('used_in'))),
self::condition('group'),
]),
Block::make('end')
->label('Ende des Teilbereichs')
->icon('heroicon-o-arrow-uturn-down')
->schema([Text::make('Die folgenden Felder stehen wieder ohne Teilbereich.')]),
Block::make('issue')
->label('Frage nach dem Anliegen')
->icon('heroicon-o-chat-bubble-left-right')
->maxItems(1)
->schema([
Select::make('issues')->label('Angebotene Anliegen')->multiple()->live()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Welche Anliegen dieses Formular kennt. Leer: alle angebotenen. Ein Anfragegrund im Widget kann daraus eines vorwählen; die Frage entfällt dann. Anliegen und Unteranliegen pflegst du unter „Einstellungen → Anliegen“.'),
]),
];
}
/**
* Bedingung am Element: Wirkung, Verknüpfung und eine Liste von Vergleichen. Ohne Wirkung gibt es keine Bedingung.
*/
private static function condition(string $kind): Section
{
return Section::make('Bedingung (optional)')->statePath('cond')->compact()->collapsed()->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->options(self::EFFECT_LABELS[$kind])->placeholder('Keine Bedingung')->live()
->helperText($kind === 'step' ? 'Zum Beispiel: Bereich „Angaben zur Schule“ nur anzeigen, wenn das Anliegen „Kursanfrage“ ist.' : null),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')
->visible(fn (Get $get): bool => filled($get('effect'))),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn (Select $component, $livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), $component->getStatePath())),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn (Get $get, $livewire): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (string) $get('source'))),
])
->addActionLabel('Bedingung hinzufügen')
->visible(fn (Get $get): bool => filled($get('effect')))
->helperText('Zur Auswahl stehen Felder, die im Formular weiter oben stehen.'),
]);
}
/**
* @param array<string, mixed>|null $state
*/
private static function fieldBadges(?array $state): string
{
$parts = [];
if (filled($state['type'] ?? null)) {
$parts[] = FieldType::tryFrom((string) $state['type'])?->label();
}
if ($state['required'] ?? false) {
$parts[] = 'Pflicht';
}
if (filled($state['cond']['effect'] ?? null)) {
$parts[] = 'Bedingung';
}
$parts = array_filter($parts);
return $parts === [] ? '' : ' ('.implode(', ', $parts).')';
}
/**
* @return list<Component>
*/
@@ -101,32 +235,33 @@ private static function rules(): array
{
return [
Section::make()->schema([
Repeater::make('draft.rules')
->label('Regeln')
->helperText('Eine Regel verändert ein Feld, eine Feldgruppe oder einen Schritt abhängig von Auswahlen davor. Bedingungen können nur auf Felder verweisen, die im Aufbau vor dem Ziel stehen; so entstehen keine Zirkelbezüge.')
Text::make('Hier stehen Regeln, die sich nicht an ein einzelnes Feld oder einen Bereich heften lassen: weitere Regeln für dasselbe Ziel und Vorbelegungen. Bedingungen für ein Feld oder einen Bereich legst du direkt am Element an. Eine Bedingung darf nur auf Felder verweisen, die im Formular weiter oben stehen.'),
Repeater::make('editor.rules')
->label('Weitere Regeln')
->schema([
Hidden::make('pos'),
Select::make('effect')->label('Wirkung')->required()->live()->options(TemplateCompiler::EFFECTS),
Select::make('target')->label('Ziel')->required()->live()->searchable()
->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['draft'] ?? []), (string) $get('effect'))),
->options(fn ($livewire, Get $get): array => self::targets((array) ($livewire->data['editor'] ?? []), (string) $get('effect'))),
Select::make('value')->label('Vorbelegen mit')->live()
->options(fn ($livewire, Get $get): array => self::targetValues((array) ($livewire->data['draft'] ?? []), (string) $get('target')))
->options(fn (Get $get): array => str_starts_with((string) $get('target'), 'field:') ? self::fieldValues(substr((string) $get('target'), 6)) : [])
->visible(fn (Get $get): bool => $get('effect') === 'preset')->required(fn (Get $get): bool => $get('effect') === 'preset'),
Select::make('match')->label('Es müssen zutreffen')->options(['all' => 'alle Bedingungen', 'any' => 'mindestens eine Bedingung'])->default('all')->required(),
Repeater::make('conditions')
->label('Bedingungen')
->schema([
Select::make('source')->label('Wenn …')->required()->live()->searchable()
->options(fn ($livewire): array => self::sources((array) ($livewire->data['draft'] ?? []))),
->options(fn ($livewire): array => self::sources((array) ($livewire->data['editor'] ?? []), null)),
Select::make('op')->label('Vergleich')->required()->options(TemplateCompiler::OPERATORS)->default('eq')->live(),
Select::make('values')->label('Wert')->required()->multiple()
->options(fn ($livewire, Get $get): array => self::sourceValues((array) ($livewire->data['draft'] ?? []), (string) $get('source'))),
->options(fn ($livewire, Get $get): array => self::sourceValues((array) ($livewire->data['editor'] ?? []), (string) $get('source'))),
])
->minItems(1)
->addActionLabel('Bedingung hinzufügen'),
])
->collapsible()
->addActionLabel('Regel hinzufügen')
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], (array) ($livewire->data['draft'] ?? [])) : '')),
->itemLabel(fn (array $state, $livewire): string => (TemplateCompiler::EFFECTS[$state['effect'] ?? ''] ?? 'Neue Regel').(($state['target'] ?? null) ? ' → '.self::targetName((string) $state['target'], (array) ($livewire->data['editor'] ?? [])) : '')),
]),
];
}
@@ -148,68 +283,77 @@ private static function texts(): array
return [
Section::make('Texte des Formulars')
->description('Alle Texte des Formulars werden hier und in den Anfrage-Einstiegen gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext. Ein Anfrage-Einstieg kann einzelne Texte überschreiben.')
->description('Alle Texte des Formulars werden hier gepflegt, nie im CMS. Leer lassen: es gilt der grau angezeigte Standardtext.')
->schema($fields),
];
}
/**
* Felder des Entwurfs in Reihenfolge: [Schlüssel => Name], dazu die Bausteine, aus denen sie stammen.
* Felder des Katalogs, die im Formular noch nicht vorkommen.
*
* @param array<string, mixed> $draft
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool}
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function inventory(array $draft): array
private static function catalogFields(array $editor): array
{
$used = array_keys(self::inventory($editor)['fields']);
return InquiryField::query()->offered()->whereNotIn('key', $used)->orderBy('name')->pluck('name', 'key')->all();
}
/**
* Inhalt des Formulars in Reihenfolge: Bereiche, Teilbereiche, Felder, und ob die Frage nach dem Anliegen vorkommt.
*
* @param array<string, mixed> $editor
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool, issues: list<string>}
*/
private static function inventory(array $editor): array
{
$steps = [];
$groups = [];
$fields = [];
$hasIssue = false;
$names = InquiryField::query()->pluck('name', 'key')->all();
$groupNames = InquiryFieldGroup::query()->get()->keyBy('key');
$issues = [];
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$key = (string) ($step['key'] ?? '');
foreach (array_values((array) ($editor['areas'] ?? [])) as $area) {
$key = (string) ($area['key'] ?? '');
if ($key !== '') {
$steps[$key] = (string) (($step['title'] ?? '') ?: 'Schritt');
$steps[$key] = (string) (($area['title'] ?? '') ?: 'Bereich');
}
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$kind = $item['kind'] ?? null;
foreach (array_values((array) ($area['items'] ?? [])) as $block) {
$data = (array) ($block['data'] ?? []);
$type = $block['type'] ?? null;
if ($kind === 'issue') {
if ($type === 'issue') {
$hasIssue = true;
} elseif ($kind === 'group' && isset($groupNames[$item['group'] ?? ''])) {
$group = $groupNames[$item['group']];
$groups[$group->key] = $group->name;
foreach ($group->itemList() as $row) {
$fields[$row['field']] = (string) ($names[$row['field']] ?? $row['field']);
}
} elseif ($kind === 'field' && filled($item['field'] ?? null)) {
$fields[$item['field']] = (string) ($names[$item['field']] ?? $item['field']);
$issues = array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'));
} elseif ($type === 'section' && filled($data['key'] ?? null)) {
$groups[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Teilbereich');
} elseif ($type === 'field' && filled($data['key'] ?? null)) {
$fields[(string) $data['key']] = (string) (($data['label'] ?? '') ?: 'Feld');
}
}
}
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue];
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue, 'issues' => $issues];
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, mixed>
*/
private static function targets(array $draft, string $effect): array
private static function targets(array $editor, string $effect): array
{
$inventory = self::inventory($draft);
$inventory = self::inventory($editor);
$steps = [];
foreach ($inventory['steps'] as $key => $title) {
$steps["step:$key"] = 'Schritt: '.$title;
$steps["step:$key"] = 'Bereich: '.$title;
}
$groups = [];
foreach ($inventory['groups'] as $key => $name) {
$groups["group:$key"] = 'Feldgruppe: '.$name;
$groups["group:$key"] = 'Teilbereich: '.$name;
}
$fields = [];
foreach ($inventory['fields'] as $key => $name) {
@@ -219,47 +363,68 @@ private static function targets(array $draft, string $effect): array
return match ($effect) {
'skip' => $steps,
'require', 'preset' => $fields,
'show', 'hide' => ['Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Schritte' => $steps, 'Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Bereiche' => $steps, 'Teilbereiche' => $groups, 'Felder' => $fields],
};
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
*/
private static function targetName(string $target, array $draft = []): string
private static function targetName(string $target, array $editor = []): string
{
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
$inventory = self::inventory($editor);
return match ($kind) {
'step' => (string) (self::inventory($draft)['steps'][$key] ?? $key),
'field' => (string) (InquiryField::query()->where('key', $key)->value('name') ?? $key),
'group' => (string) (InquiryFieldGroup::query()->where('key', $key)->value('name') ?? $key),
'step' => (string) ($inventory['steps'][$key] ?? $key),
'field' => (string) ($inventory['fields'][$key] ?? InquiryField::query()->where('key', $key)->value('name') ?? $key),
'group' => (string) ($inventory['groups'][$key] ?? $key),
default => $key,
};
}
/**
* Felder, auf deren Wert sich eine Bedingung stützen darf.
* Felder, auf deren Wert sich eine Bedingung stützen darf: gespeicherte Auswahlfelder und Ja/Nein-Felder. Mit
* Zustandspfad der Bedingung nur Felder, die im Formular davor stehen (sonst lehnt die Prüfung die Regel ab).
*
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sources(array $draft): array
private static function sources(array $editor, ?string $path): array
{
$inventory = self::inventory($draft);
$sources = [];
$areaId = null;
$blockId = null;
if ($inventory['hasIssue']) {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
if ($path !== null) {
$segments = explode('.', $path);
$areaAt = array_search('areas', $segments, true);
$itemAt = array_search('items', $segments, true);
$areaId = $areaAt === false ? null : ($segments[$areaAt + 1] ?? null);
$blockId = $itemAt === false ? null : ($segments[$itemAt + 1] ?? null);
}
$catalog = InquiryField::query()->whereIn('key', array_keys($inventory['fields']))->get()->keyBy('key');
$catalog = InquiryField::query()->get()->keyBy('key');
$sources = [];
foreach ($inventory['fields'] as $key => $name) {
if (isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = $name;
foreach ((array) ($editor['areas'] ?? []) as $currentArea => $area) {
if ($areaId !== null && (string) $currentArea === $areaId && $blockId === null) {
break;
}
foreach ((array) ($area['items'] ?? []) as $currentBlock => $block) {
if ($areaId !== null && (string) $currentArea === $areaId && (string) $currentBlock === $blockId) {
break 2;
}
$data = (array) ($block['data'] ?? []);
$key = (string) ($data['key'] ?? '');
if (($block['type'] ?? null) === 'issue') {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
} elseif (($block['type'] ?? null) === 'field' && isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = (string) (($data['label'] ?? '') ?: $catalog[$key]->label);
}
}
}
@@ -267,13 +432,13 @@ private static function sources(array $draft): array
}
/**
* @param array<string, mixed> $draft
* @param array<string, mixed> $editor
* @return array<string, string>
*/
private static function sourceValues(array $draft, string $source): array
private static function sourceValues(array $editor, string $source): array
{
if ($source === 'anliegen' || $source === 'unteranliegen') {
$only = array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'));
$only = self::inventory($editor)['issues'];
$options = [];
foreach (InquiryIssue::tree() as $issue) {
@@ -298,15 +463,6 @@ private static function sourceValues(array $draft, string $source): array
return self::fieldValues($source);
}
/**
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function targetValues(array $draft, string $target): array
{
return str_starts_with($target, 'field:') ? self::fieldValues(substr($target, 6)) : [];
}
/**
* @return array<string, string>
*/
+272
View File
@@ -0,0 +1,272 @@
<?php
namespace Tests\Feature;
use App\Domain\Communication\ExampleConfiguration;
use App\Domain\Communication\FormEditor;
use App\Domain\Communication\FormJson;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Publisher;
use App\Domain\Communication\TemplateCompiler;
use App\Filament\Resources\Communication\Templates\Pages\EditInquiryTemplate;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;
/**
* Formular-Editor (ADR-61): Übersetzung zwischen Entwurf und Bearbeitungsansicht, Anlegen von Feldern im Katalog.
*/
class CommunicationEditorTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
app(ExampleConfiguration::class)->install();
}
/**
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
private function structure(array $draft): array
{
return FormJson::normalize(['issues' => $draft['issues'], 'steps' => $draft['steps'], 'rules' => $draft['rules']]);
}
public function test_every_example_form_opens_and_saves_unchanged_in_the_editor(): void
{
$editor = app(FormEditor::class);
foreach (InquiryTemplate::query()->get() as $template) {
$draft = (array) $template->draft;
$fieldsBefore = InquiryField::query()->get()->map->getAttributes()->all();
$groupsBefore = InquiryFieldGroup::query()->get()->map->getAttributes()->all();
$saved = $editor->persist($editor->expand($draft));
$this->assertSame($this->structure($draft), $this->structure($saved), 'Entwurf unverändert: '.$template->name);
$this->assertSame($fieldsBefore, InquiryField::query()->get()->map->getAttributes()->all(), 'Feldkatalog unverändert: '.$template->name);
$this->assertSame($groupsBefore, InquiryFieldGroup::query()->get()->map->getAttributes()->all(), 'Feldgruppen unverändert: '.$template->name);
}
}
public function test_the_example_courses_form_shows_its_conditions_at_the_elements_and_keeps_the_rest_as_rules(): void
{
$view = app(FormEditor::class)->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft);
$second = $view['areas'][1];
$this->assertSame('skip', $second['cond']['effect']);
$this->assertSame('unteranliegen', $second['cond']['conditions'][0]['source']);
$sections = collect($second['items'])->where('type', 'section')->keyBy('data.key');
$this->assertSame('show', $sections['traeger_angaben']['data']['cond']['effect']);
$this->assertSame('ja', $sections['traeger_angaben']['data']['cond']['conditions'][0]['values'][0]);
$fields = collect($view['areas'])->flatMap(fn (array $area) => $area['items'])->where('type', 'field')->keyBy('data.key');
$this->assertSame('show', $fields['schulart']['data']['cond']['effect'], 'Die erste Regel am Ziel erscheint am Feld.');
// Die zweite Regel desselben Ziels (Pflichtfeld, wenn …) bleibt als weitere Regel erhalten.
$this->assertCount(1, $view['rules']);
$this->assertSame('require', $view['rules'][0]['effect']);
$this->assertSame('field:schulart', $view['rules'][0]['target']);
}
public function test_new_fields_and_sections_are_created_in_the_catalog_and_the_form_publishes(): void
{
$editor = app(FormEditor::class);
$view = [
'issues' => [],
'rules' => [],
'areas' => [[
'key' => 'sabc123', 'title' => 'Ihre Angaben', 'intro' => null, 'cond' => [],
'items' => [
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Wie heißen Sie?', 'help' => 'Vor- und Nachname', 'type' => 'text', 'required' => true, 'purpose' => 'name', 'options' => [], 'cond' => []]],
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'E-Mail für Rückfragen', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
['type' => 'section', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Angaben zur Schule', 'description' => 'Nur für Schulen', 'cond' => []]],
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Welche Schulart?', 'type' => 'select', 'required' => false, 'purpose' => null, 'options' => [['key' => '', 'label' => 'Grundschule'], ['key' => '', 'label' => 'Gymnasium']], 'cond' => []]],
],
]],
];
$draft = $editor->persist($view);
$name = InquiryField::query()->where('label', 'Wie heißen Sie?')->firstOrFail();
$this->assertSame('wie_heissen_sie', $name->key);
$this->assertSame('name', $name->purpose->value);
$schule = InquiryField::query()->where('label', 'Welche Schulart?')->firstOrFail();
$this->assertSame(['grundschule', 'gymnasium'], array_column($schule->optionList(), 'key'));
$group = InquiryFieldGroup::query()->where('label', 'Angaben zur Schule')->firstOrFail();
$this->assertSame([['field' => $schule->key, 'required' => false]], $group->itemList());
$this->assertSame([
['kind' => 'field', 'field' => 'wie_heissen_sie', 'required' => true],
['kind' => 'field', 'field' => (string) InquiryField::query()->where('label', 'E-Mail für Rückfragen')->value('key'), 'required' => true],
['kind' => 'group', 'group' => $group->key],
], $draft['steps'][0]['items']);
$template = InquiryTemplate::query()->create(['key' => 'neu', 'name' => 'Neu', 'draft' => [...InquiryTemplate::emptyDraft(), ...$draft]]);
$result = app(TemplateCompiler::class)->compile((array) $template->draft);
$this->assertSame([], $result['errors']);
app(Publisher::class)->publishTemplate($template, null, null);
$this->assertTrue($template->fresh()->isPublished());
}
public function test_conditions_at_elements_become_engine_rules_in_document_order_with_keys_resolved(): void
{
$editor = app(FormEditor::class);
$ja = [['source' => 'traeger_abweichend', 'op' => 'eq', 'values' => ['ja']]];
$view = [
'issues' => [], 'rules' => [],
'areas' => [
['key' => 'sa1', 'title' => 'Eins', 'intro' => null, 'cond' => [], 'items' => [
['type' => 'field', 'data' => ['key' => 'traeger_abweichend', 'label' => 'Abweichender Träger?', 'type' => 'boolean', 'required' => false, 'options' => [], 'cond' => []]],
['type' => 'field', 'data' => ['key' => 'email', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
]],
['key' => 'sa2', 'title' => 'Zwei', 'intro' => null, 'cond' => ['effect' => 'show', 'match' => 'all', 'conditions' => $ja], 'items' => [
['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Name des Trägers', 'type' => 'text', 'required' => true, 'options' => [], 'cond' => ['effect' => 'require', 'match' => 'all', 'conditions' => $ja]]],
]],
],
];
$draft = $editor->persist($view);
$this->assertSame([
['effect' => 'require', 'target' => 'field:name_des_traegers', 'match' => 'all', 'conditions' => $ja, 'value' => null],
['effect' => 'show', 'target' => 'step:sa2', 'match' => 'all', 'conditions' => $ja, 'value' => null],
], $draft['rules']);
$template = InquiryTemplate::query()->create(['key' => 'bedingt', 'name' => 'Bedingt', 'draft' => [...InquiryTemplate::emptyDraft(), ...$draft]]);
$this->assertSame([], app(TemplateCompiler::class)->compile((array) $template->draft)['errors']);
}
public function test_an_existing_field_keeps_its_key_and_type_and_options_keep_their_keys_when_renamed(): void
{
$editor = app(FormEditor::class);
$view = $editor->expand((array) InquiryTemplate::query()->where('key', 'allgemein')->firstOrFail()->draft);
$found = false;
foreach ($view['areas'] as &$area) {
foreach ($area['items'] as &$block) {
if ($block['type'] === 'field' && $block['data']['key'] === 'nachricht') {
$block['data']['label'] = 'Was möchten Sie uns mitteilen?';
$block['data']['type'] = 'text';
$found = true;
}
}
}
unset($area, $block);
$this->assertTrue($found);
$editor->persist($view);
$field = InquiryField::query()->where('key', 'nachricht')->firstOrFail();
$this->assertSame('Was möchten Sie uns mitteilen?', $field->label);
$this->assertSame('textarea', $field->type->value, 'Der Feldtyp eines vorhandenen Feldes ändert sich nicht.');
$options = InquiryField::query()->where('key', 'kursformat')->firstOrFail()->optionList();
$view = $editor->expand((array) InquiryTemplate::query()->where('key', 'kursanfragen')->firstOrFail()->draft);
foreach ($view['areas'] as &$area) {
foreach ($area['items'] as &$block) {
if ($block['type'] === 'field' && $block['data']['key'] === 'kursformat') {
$block['data']['options'][0]['label'] = 'Umbenannt';
}
}
}
unset($area, $block);
$editor->persist($view);
$renamed = InquiryField::query()->where('key', 'kursformat')->firstOrFail()->optionList();
$this->assertSame($options[0]['key'], $renamed[0]['key']);
$this->assertSame('Umbenannt', $renamed[0]['label']);
}
private function staff(): User
{
$user = User::factory()->redakteur()->create();
$user->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $user;
}
private function emptyForm(string $key): InquiryTemplate
{
return InquiryTemplate::query()->create(['key' => $key, 'name' => ucfirst($key), 'draft' => [...InquiryTemplate::emptyDraft(), 'steps' => [['key' => 'sstart1', 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]]]]);
}
public function test_a_form_is_built_in_the_editor_saved_twice_without_duplicates_and_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('frisch');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areas = $component->get('data.editor.areas');
$this->assertCount(1, $areas);
$areaId = array_key_first($areas);
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Rufname', 'type' => 'text', 'required' => true, 'purpose' => 'name', 'options' => [], 'cond' => []]],
'b' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihre Mailadresse zur Antwort', 'type' => 'email', 'required' => true, 'purpose' => 'email', 'options' => [], 'cond' => []]],
])->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$draft = $template->fresh()->draft;
$this->assertSame(['ihr_rufname', 'ihre_mailadresse_zur_antwort'], array_column($draft['steps'][0]['items'], 'field'));
// Ein zweites Speichern legt nichts doppelt an, weil die Ansicht nach dem Speichern die festen Kennungen trägt.
$component->call('save')->assertHasNoFormErrors();
$this->assertSame(1, InquiryField::query()->where('label', 'Ihr Rufname')->count());
$this->assertSame($draft, $template->fresh()->draft);
$component->callAction('check')->assertNotified('Die Konfiguration ist in Ordnung.');
$component->callAction('publish', ['note' => 'Erste Fassung'])->assertHasNoActionErrors();
$this->assertTrue($template->fresh()->isPublished());
}
public function test_an_invalid_form_is_not_published(): void
{
$editor = $this->staff();
$template = $this->emptyForm('ohnemail');
$component = Livewire::actingAs($editor, 'staff')->test(EditInquiryTemplate::class, ['record' => $template->id]);
$areaId = array_key_first($component->get('data.editor.areas'));
$component->set('data.editor.areas.'.$areaId.'.items', [
'a' => ['type' => 'field', 'data' => ['key' => FormEditor::temporaryKey(), 'label' => 'Ihr Name', 'type' => 'text', 'required' => true, 'options' => [], 'cond' => []]],
])->call('save');
$component->callAction('publish', ['note' => null]);
$this->assertFalse($template->fresh()->isPublished());
}
public function test_the_navigation_offers_forms_for_editors_and_the_technical_blocks_stay_reachable(): void
{
$this->actingAs($this->staff(), 'staff');
$html = $this->get('/verwaltung')->assertOk()->getContent();
$this->assertStringContainsString('Formulare &amp; Befragungen', $html);
$this->assertStringNotContainsString('Feldkatalog', $html);
$this->assertStringNotContainsString('Anfrage-Einstiege', $html);
$this->assertStringNotContainsString('Feldgruppen', $html);
$this->get('/verwaltung/kommunikation/felder')->assertOk();
$this->get('/verwaltung/kommunikation/anliegen')->assertOk();
}
public function test_the_usage_in_other_forms_is_reported(): void
{
$usage = app(FormEditor::class)->usage();
$this->assertContains('Allgemeine Kontaktaufnahme', $usage['fields']['email']);
$this->assertGreaterThan(1, count($usage['fields']['email']));
}
}