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>
502 lines
21 KiB
PHP
502 lines
21 KiB
PHP
<?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;
|
|
}
|
|
}
|