Files
laraundfelix/app/Filament/Resources/Communication/Templates/Pages/EditInquiryTemplate.php
T
LarsandClaude Sonnet 5.5 380a3013c7
CI Feature / test (push) Successful in 4m18s
Ersetze die Builder-Liste des Formular-Editors durch eine Formularansicht mit Ziehen und Ablegen
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>
2026-11-28 08:08:39 +01:00

205 lines
8.8 KiB
PHP

<?php
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;
use App\Domain\Communication\TemplateDraft;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Schemas\Components\Text;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Validation\ValidationException;
class EditInquiryTemplate extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryTemplateResource::class;
protected Width|string|null $maxContentWidth = Width::Full;
protected ?bool $hasUnsavedDataChangesAlert = true;
public function getSubheading(): string|Htmlable|null
{
/** @var InquiryTemplate $template */
$template = $this->getRecord();
if ($template->archived_at !== null) {
return 'Archiviert.';
}
if (! $template->isPublished()) {
return 'Noch nicht veröffentlicht. Besucher sehen dieses Formular erst nach „Veröffentlichen“.';
}
$version = $template->publishedVersion;
return 'Gültig ist Fassung '.$version->version.' (veröffentlicht am '.$version->published_at->format('d.m.Y').').'
.($template->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : ' Der Entwurf entspricht der gültigen Fassung.');
}
protected function getHeaderActions(): array
{
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->tooltip('Zeigt den zuletzt gespeicherten Entwurf als Besucher mit allen Bedingungen. Es wird nichts gesendet.')
->url(fn (): string => route('communication.preview.template', $this->getRecord()))
->openUrlInNewTab(),
Action::make('check')
->label('Konfiguration prüfen')
->color('gray')
->action(function (): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
$result = app(TemplateCompiler::class)->compile(TemplateDraft::clean((array) $this->getRecord()->draft));
if ($result['errors'] === []) {
Notification::make()->title('Die Konfiguration ist in Ordnung.')->body('Der Entwurf wurde gespeichert und lässt sich veröffentlichen.')->success()->send();
return;
}
Notification::make()->title('Die Konfiguration hat Probleme')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $result['errors'])))->danger()->persistent()->send();
}),
Action::make('publish')
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->modalHeading('Formular veröffentlichen')
->modalSubmitActionLabel('Jetzt veröffentlichen')
->modalWidth('2xl')
->schema(fn (): array => [
Text::make($this->affectedText()),
Textarea::make('note')->label('Bemerkung zur Fassung (optional)')->rows(2)->maxLength(300),
])
->action(function (array $data): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
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('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;
}
Notification::make()->title('Fassung '.$version->version.' ist veröffentlicht.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
...$this->archiveActions(),
];
}
/** Einstiege, die diese Vorlage verwenden und von einer neuen Fassung betroffen sind. */
private function affectedText(): string
{
$rows = app(Publisher::class)->affected($this->getRecord());
if ($rows === []) {
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. 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 '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
{
return ['archived_at' => now()];
}
protected function indexUrl(): string
{
return InquiryTemplateResource::getUrl('index');
}
protected function archiveBlocked(): ?string
{
$live = $this->getRecord()->entries()->live()->count();
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
{
$tree = FormEditor::toTree(app(FormEditor::class)->expand((array) ($data['draft'] ?? []), $this->getRecord()->getKey()));
// Die Formularansicht führt den Baum im Browser und übergibt ihn als Text; die weiteren Regeln bleiben eine Liste.
$data['editor'] = ['rules' => $tree['rules']];
$data['editor_json'] = json_encode(['areas' => $tree['areas']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$editor = app(FormEditor::class);
$tree = json_decode((string) ($data['editor_json'] ?? ''), true);
if (! is_array($tree)) {
$this->failEditor(['Der Aufbau konnte nicht gelesen werden. Bitte lade die Seite neu und versuche es noch einmal.']);
}
$errors = $editor->validateTree($tree);
if ($errors !== []) {
$this->failEditor($errors);
}
// Der Editor schreibt neue und geänderte Felder und Teilbereiche in den Katalog und liefert den Entwurf.
$view = FormEditor::fromTree($tree);
$view['rules'] = (array) ($data['editor']['rules'] ?? []);
$saved = $editor->persist($view);
unset($data['editor'], $data['editor_json']);
$data['draft'] = TemplateDraft::clean([
'texts' => (array) ($data['draft']['texts'] ?? []),
'issues' => $saved['issues'],
'steps' => $saved['steps'],
'rules' => $saved['rules'],
]);
return $data;
}
/**
* @param list<string> $messages
* @return never
*/
private function failEditor(array $messages): void
{
Notification::make()->title('Das Formular ist noch nicht vollständig')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, $messages)))->danger()->persistent()->send();
throw ValidationException::withMessages(['data.editor_json' => $messages]);
}
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;
}
}