Files
laraundfelix/app/Filament/Support/TemplateEditor.php
T
2026-11-27 18:03:45 +01:00

324 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Support;
use App\Domain\Communication\FieldType;
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\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get;
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.
*/
final class TemplateEditor
{
/**
* @return list<Component>
*/
public static function schema(): array
{
return [
TextInput::make('name')->label('Bezeichnung der Vorlage')->required()->maxLength(120),
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()),
]),
];
}
/**
* @return list<Component>
*/
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.')
->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),
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'),
])
->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',
}),
])
->reorderableWithButtons()
->collapsible()
->addActionLabel('Schritt hinzufügen')
->live()
->itemLabel(fn (array $state): string => $state['title'] ?? 'Neuer Schritt'),
];
}
/**
* @return list<Component>
*/
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.')
->schema([
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'))),
Select::make('value')->label('Vorbelegen mit')->live()
->options(fn ($livewire, Get $get): array => self::targetValues((array) ($livewire->data['draft'] ?? []), (string) $get('target')))
->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'] ?? []))),
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'))),
])
->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'] ?? [])) : '')),
]),
];
}
/**
* @return list<Component>
*/
private static function texts(): array
{
$fields = [];
foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) {
$field = $multiline
? Textarea::make("draft.texts.$key")->rows(2)->maxLength(1500)
: TextInput::make("draft.texts.$key")->maxLength(200);
$fields[] = $field->label($label)->placeholder($default !== '' ? $default : 'Kein Text')->helperText($help);
}
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.')
->schema($fields),
];
}
/**
* Felder des Entwurfs in Reihenfolge: [Schlüssel => Name], dazu die Bausteine, aus denen sie stammen.
*
* @param array<string, mixed> $draft
* @return array{steps: array<string, string>, groups: array<string, string>, fields: array<string, string>, hasIssue: bool}
*/
private static function inventory(array $draft): array
{
$steps = [];
$groups = [];
$fields = [];
$hasIssue = false;
$names = InquiryField::query()->pluck('name', 'key')->all();
$groupNames = InquiryFieldGroup::query()->get()->keyBy('key');
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
$key = (string) ($step['key'] ?? '');
if ($key !== '') {
$steps[$key] = (string) (($step['title'] ?? '') ?: 'Schritt');
}
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
$kind = $item['kind'] ?? null;
if ($kind === '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']);
}
}
}
return ['steps' => $steps, 'groups' => $groups, 'fields' => $fields, 'hasIssue' => $hasIssue];
}
/**
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
private static function targets(array $draft, string $effect): array
{
$inventory = self::inventory($draft);
$steps = [];
foreach ($inventory['steps'] as $key => $title) {
$steps["step:$key"] = 'Schritt: '.$title;
}
$groups = [];
foreach ($inventory['groups'] as $key => $name) {
$groups["group:$key"] = 'Feldgruppe: '.$name;
}
$fields = [];
foreach ($inventory['fields'] as $key => $name) {
$fields["field:$key"] = 'Feld: '.$name;
}
return match ($effect) {
'skip' => $steps,
'require', 'preset' => $fields,
'show', 'hide' => ['Feldgruppen' => $groups, 'Felder' => $fields],
default => ['Schritte' => $steps, 'Feldgruppen' => $groups, 'Felder' => $fields],
};
}
/**
* @param array<string, mixed> $draft
*/
private static function targetName(string $target, array $draft = []): string
{
[$kind, $key] = array_pad(explode(':', $target, 2), 2, '');
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),
default => $key,
};
}
/**
* Felder, auf deren Wert sich eine Bedingung stützen darf.
*
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function sources(array $draft): array
{
$inventory = self::inventory($draft);
$sources = [];
if ($inventory['hasIssue']) {
$sources['anliegen'] = 'Anliegen';
$sources['unteranliegen'] = 'Unteranliegen';
}
$catalog = InquiryField::query()->whereIn('key', array_keys($inventory['fields']))->get()->keyBy('key');
foreach ($inventory['fields'] as $key => $name) {
if (isset($catalog[$key]) && $catalog[$key]->type->canControl()) {
$sources[$key] = $name;
}
}
return $sources;
}
/**
* @param array<string, mixed> $draft
* @return array<string, string>
*/
private static function sourceValues(array $draft, string $source): array
{
if ($source === 'anliegen' || $source === 'unteranliegen') {
$only = array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string'));
$options = [];
foreach (InquiryIssue::tree() as $issue) {
if ($only !== [] && ! in_array($issue['key'], $only, true)) {
continue;
}
if ($source === 'anliegen') {
$options[$issue['key']] = $issue['label'];
continue;
}
foreach ($issue['children'] as $child) {
$options[$child['key']] = $issue['label'].' › '.$child['label'];
}
}
return $options;
}
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>
*/
private static function fieldValues(string $key): array
{
$field = InquiryField::query()->where('key', $key)->first();
if ($field === null || ! in_array($field->type, [FieldType::Select, FieldType::Multiselect, FieldType::Boolean], true)) {
return [];
}
return collect($field->optionList())->pluck('label', 'key')->all();
}
}