CI Feature / test (push) Successful in 4m18s
Der Aufbau eines Formulars zeigt Bereiche als Karten, Teilbereiche als eingerahmte Einheit darin und Felder als Zeilen (Frage, Art der Antwort, Pflicht). Hilfetext, Auswahlwerte, Bedingung und weitere Einstellungen öffnen als Pop-up. Bereiche, Teilbereiche und Felder lassen sich ziehen (SortableJS aus Filament) oder per Pfeiltasten und über "Verschieben nach" ordnen; Rückgängig nimmt Änderungen bis zum Speichern zurück. Der Browser führt den Baum und übergibt ihn beim Speichern als Text; FormEditor prüft ihn (validateTree) und überführt ihn über fromTree in dieselbe flache Ansicht wie bisher. Entwurf, Katalog und Engine bleiben unverändert, keine Migration. Tests: Die Livewire-Tests des Editors setzen jetzt den Baumtext (editor_json) statt der Builder-Blöcke; neu sind Baumumwandlung ohne Verlust, Teilbereich mit Feldern, Prüfung und Konfiguration. Das ist bewusst: Der Builder entfällt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
742 lines
31 KiB
PHP
742 lines
31 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Communication;
|
|
|
|
use Illuminate\Support\Arr;
|
|
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),
|
|
];
|
|
});
|
|
}
|
|
|
|
/** Beschriftungen der Wirkungen am Element, je Art des Ziels. */
|
|
public 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 …'],
|
|
];
|
|
|
|
/**
|
|
* Baumansicht für die Formularoberfläche (ADR-62): Ein Teilbereich trägt seine Felder selbst (items), die
|
|
* Ende-Markierung der flachen Ansicht entfällt. Die Umwandlung ist verlustfrei: fromTree(toTree(x)) liefert dieselbe
|
|
* Struktur, die persist() in denselben Entwurf überführt.
|
|
*
|
|
* @param array<string, mixed> $view Ergebnis von expand()
|
|
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
|
|
*/
|
|
public static function toTree(array $view): array
|
|
{
|
|
$areas = [];
|
|
|
|
foreach (array_values((array) ($view['areas'] ?? [])) as $area) {
|
|
$area = is_array($area) ? $area : [];
|
|
$items = [];
|
|
$section = 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':
|
|
$section = null;
|
|
$items[] = ['kind' => 'issue', 'issues' => array_values(array_filter((array) ($data['issues'] ?? []), 'is_string'))];
|
|
|
|
break;
|
|
|
|
case 'end':
|
|
$section = null;
|
|
|
|
break;
|
|
|
|
case 'section':
|
|
$items[] = ['kind' => 'section', ...$data, 'items' => []];
|
|
$section = array_key_last($items);
|
|
|
|
break;
|
|
|
|
case 'field':
|
|
if ($section !== null) {
|
|
$items[$section]['items'][] = ['kind' => 'field', ...$data];
|
|
} else {
|
|
$items[] = ['kind' => 'field', ...$data];
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
$areas[] = [...Arr::except($area, ['items']), 'items' => $items];
|
|
}
|
|
|
|
return ['areas' => $areas, 'rules' => array_values((array) ($view['rules'] ?? []))];
|
|
}
|
|
|
|
/**
|
|
* Umkehrung von toTree(): die flache Ansicht, die persist() erwartet. Nach jedem Teilbereich steht eine
|
|
* Ende-Markierung, damit folgende Einzelfelder nicht in ihn fallen.
|
|
*
|
|
* @param array<string, mixed> $tree
|
|
* @return array{areas: list<array<string, mixed>>, rules: list<array<string, mixed>>}
|
|
*/
|
|
public static function fromTree(array $tree): array
|
|
{
|
|
$areas = [];
|
|
$field = fn (array $item): array => ['type' => 'field', 'data' => Arr::except($item, ['kind', '_id'])];
|
|
|
|
foreach (array_values((array) ($tree['areas'] ?? [])) as $area) {
|
|
$area = is_array($area) ? $area : [];
|
|
$blocks = [];
|
|
|
|
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
|
|
$item = is_array($item) ? $item : [];
|
|
|
|
switch ((string) ($item['kind'] ?? '')) {
|
|
case 'issue':
|
|
$blocks[] = ['type' => 'issue', 'data' => ['issues' => array_values(array_filter((array) ($item['issues'] ?? []), 'is_string'))]];
|
|
|
|
break;
|
|
|
|
case 'section':
|
|
$blocks[] = ['type' => 'section', 'data' => Arr::except($item, ['kind', '_id', 'items'])];
|
|
|
|
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
|
|
$blocks[] = $field(is_array($inner) ? $inner : []);
|
|
}
|
|
|
|
$blocks[] = ['type' => 'end', 'data' => []];
|
|
|
|
break;
|
|
|
|
case 'field':
|
|
$blocks[] = $field($item);
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
$areas[] = [...Arr::except($area, ['items', '_id']), 'items' => $blocks];
|
|
}
|
|
|
|
return ['areas' => $areas, 'rules' => array_values((array) ($tree['rules'] ?? []))];
|
|
}
|
|
|
|
/**
|
|
* Prüft die Baumansicht vor dem Speichern. Was nur gekürzt oder ignoriert würde, wird hier benannt, damit die
|
|
* Verwaltung nichts stillschweigend verliert.
|
|
*
|
|
* @param array<string, mixed> $tree
|
|
* @return list<string>
|
|
*/
|
|
public function validateTree(array $tree): array
|
|
{
|
|
$errors = [];
|
|
$seen = [];
|
|
$issueQuestions = 0;
|
|
$limit = function (string $where, string $what, mixed $value, int $max) use (&$errors): void {
|
|
if (mb_strlen(trim((string) $value)) > $max) {
|
|
$errors[] = "$where: $what darf höchstens $max Zeichen lang sein.";
|
|
}
|
|
};
|
|
|
|
foreach (array_values((array) ($tree['areas'] ?? [])) as $index => $area) {
|
|
$area = is_array($area) ? $area : [];
|
|
$title = trim((string) ($area['title'] ?? ''));
|
|
$where = 'Bereich '.($index + 1).($title !== '' ? ' „'.$title.'“' : '');
|
|
|
|
if ($title === '') {
|
|
$errors[] = "$where: Der Titel fehlt.";
|
|
}
|
|
|
|
$limit($where, 'Der Titel', $title, 120);
|
|
$limit($where, 'Die Einleitung', $area['intro'] ?? '', 600);
|
|
|
|
$checkField = function (array $field) use (&$errors, &$seen, $where, $limit): void {
|
|
$label = trim((string) ($field['label'] ?? ''));
|
|
$name = $label !== '' ? '„'.$label.'“' : 'Ein Feld';
|
|
|
|
if ($label === '') {
|
|
$errors[] = "$where: Ein Feld hat keine Frage oder Beschriftung.";
|
|
}
|
|
|
|
$limit($where, "Die Frage $name", $label, 200);
|
|
$limit($where, "Der Hilfetext von $name", $field['help'] ?? '', 600);
|
|
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
|
|
|
|
if ($type === null) {
|
|
$errors[] = "$where: Bei $name fehlt die Art der Antwort.";
|
|
} elseif ($type->hasOptions()) {
|
|
$options = array_filter((array) ($field['options'] ?? []), fn (mixed $option): bool => is_array($option) && trim((string) ($option['label'] ?? '')) !== '');
|
|
|
|
if ($options === []) {
|
|
$errors[] = "$where: Bei $name fehlen die Auswahlwerte.";
|
|
}
|
|
|
|
foreach ($options as $option) {
|
|
$limit($where, "Ein Auswahlwert von $name", $option['label'], 120);
|
|
}
|
|
}
|
|
|
|
$key = (string) ($field['key'] ?? '');
|
|
|
|
if ($key !== '' && ! str_starts_with($key, 'tmp_')) {
|
|
if (isset($seen[$key])) {
|
|
$errors[] = "$where: $name steht mehrfach im Formular.";
|
|
}
|
|
|
|
$seen[$key] = true;
|
|
}
|
|
};
|
|
|
|
foreach (array_values((array) ($area['items'] ?? [])) as $item) {
|
|
$item = is_array($item) ? $item : [];
|
|
|
|
if (($item['kind'] ?? null) === 'issue') {
|
|
$issueQuestions++;
|
|
} elseif (($item['kind'] ?? null) === 'section') {
|
|
$label = trim((string) ($item['label'] ?? ''));
|
|
|
|
if ($label === '') {
|
|
$errors[] = "$where: Ein Teilbereich hat keine Überschrift.";
|
|
}
|
|
|
|
$limit($where, 'Die Überschrift eines Teilbereichs', $label, 200);
|
|
$limit($where, 'Die Erläuterung eines Teilbereichs', $item['description'] ?? '', 600);
|
|
|
|
foreach (array_values((array) ($item['items'] ?? [])) as $inner) {
|
|
$checkField(is_array($inner) ? $inner : []);
|
|
}
|
|
} elseif (($item['kind'] ?? null) === 'field') {
|
|
$checkField($item);
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($issueQuestions > 1) {
|
|
$errors[] = 'Die Frage nach dem Anliegen darf nur einmal im Formular vorkommen.';
|
|
}
|
|
|
|
return array_values(array_unique($errors));
|
|
}
|
|
|
|
/**
|
|
* Auswahllisten für die Formularoberfläche: Feldarten, Verwendungen, Wirkungen, Vergleiche, Anliegen und die Felder
|
|
* des Katalogs mit Verwendung in anderen Formularen.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function clientConfig(?int $exceptTemplate = null): array
|
|
{
|
|
$usage = $this->usage($exceptTemplate);
|
|
|
|
return [
|
|
'types' => array_map(fn (FieldType $type): array => ['value' => $type->value, 'label' => $type->label(), 'options' => $type->hasOptions(), 'control' => $type->canControl()], FieldType::cases()),
|
|
'purposes' => array_map(fn (FieldPurpose $purpose): array => ['value' => $purpose->value, 'label' => $purpose->label(), 'types' => array_map(fn (FieldType $type): string => $type->value, $purpose->types())], FieldPurpose::cases()),
|
|
'effects' => self::EFFECT_LABELS,
|
|
'operators' => TemplateCompiler::OPERATORS,
|
|
'issues' => InquiryIssue::tree(),
|
|
'catalog' => InquiryField::query()->offered()->orderBy('name')->get()->map(fn (InquiryField $field): array => [
|
|
'key' => $field->key,
|
|
'name' => $field->name,
|
|
'label' => $field->label,
|
|
'help' => $field->help,
|
|
'type' => $field->type->value,
|
|
'options' => $field->optionList(),
|
|
'purpose' => $field->purpose?->value,
|
|
'used_in' => implode(', ', $usage['fields'][$field->key] ?? []),
|
|
])->values()->all(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
}
|