Baue die Verwaltung Kommunikation, die öffentliche Anfrageschnittstelle und das CMS-Widget Anfrage

Anliegen, Feldkatalog, Feldgruppen, Anfragevorlagen mit Fassungen, Anfrage-Einstiege, Posteingang mit
Status und Notizen, Einstellungen mit Empfängern. Das Widget speichert nur die Kennung eines veröffentlichten
Einstiegs; Formular, Bedingungen und Annahme kommen zur Laufzeit vom Server (Kompaktformular und
mehrstufiger Dialog aus derselben Beschreibung).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-27 17:41:55 +01:00
1 parent 2ee1fc9866
commit c6a8167601
45 files changed
+5415

No files matched your search

@@ -0,0 +1,46 @@
<?php
namespace App\Filament\Resources\Communication;
use App\Domain\Communication\CommunicationAccess;
use Filament\Resources\Resource;
use Illuminate\Database\Eloquent\Model;
/**
* Gemeinsame Grundlage der Konfigurationsbereiche der Kommunikationsverwaltung: Gruppe „Kommunikation“, Rechte,
* kein Löschen (Einträge werden archiviert, weil Anfragen und Fassungen auf sie verweisen).
*/
abstract class CommunicationResource extends Resource
{
protected static string|\UnitEnum|null $navigationGroup = 'Kommunikation';
public static function canViewAny(): bool
{
return CommunicationAccess::configure();
}
public static function canCreate(): bool
{
return CommunicationAccess::configure();
}
public static function canEdit(Model $record): bool
{
return CommunicationAccess::configure();
}
public static function canView(Model $record): bool
{
return CommunicationAccess::configure();
}
public static function canDelete(Model $record): bool
{
return false;
}
public static function canDeleteAny(): bool
{
return false;
}
}
@@ -0,0 +1,143 @@
<?php
namespace App\Filament\Resources\Communication\Entries;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\InquiryTemplate;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Entries\Pages\EditInquiryEntry;
use App\Filament\Resources\Communication\Entries\Pages\ListInquiryEntries;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Anfrage-Einstiege: die veröffentlichbare Nutzungsvariante einer Anfragevorlage. Sie legen fest, welche Anliegen
* angeboten werden, was vorausgewählt ist, welche Texte erscheinen und ob ein Kompaktformular oder ein mehrstufiger
* Dialog gezeigt wird. Das CMS wählt nur einen veröffentlichten Einstieg aus.
*/
class InquiryEntryResource extends CommunicationResource
{
protected static ?string $model = InquiryEntry::class;
protected static ?string $navigationLabel = 'Anfrage-Einstiege';
protected static ?string $modelLabel = 'Anfrage-Einstieg';
protected static ?string $pluralModelLabel = 'Anfrage-Einstiege';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/einstiege';
protected static ?int $navigationSort = 6;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120)
->helperText('So heißt der Einstieg in der Auswahl im CMS, zum Beispiel „Kurse & Workshops“.'),
Select::make('template_id')->label('Anfragevorlage')->required()->live()
->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all())
->helperText('Die Formularstruktur kommt aus der veröffentlichten Fassung dieser Vorlage und folgt jeder neu veröffentlichten Fassung.'),
Section::make('Angebotene Anliegen')->description('Der Rahmen, in dem Besucher wählen. Ist nur ein Anliegen zugelassen, müssen sie es nicht bestätigen.')->schema([
Select::make('config.allowed_issues')->label('Zugelassene Anliegen')->multiple()
->options(fn (): array => InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all())
->helperText('Leer: alle Anliegen der Vorlage.'),
Select::make('config.allowed_subissues')->label('Zugelassene Unteranliegen')->multiple()
->options(function (): array {
$options = [];
foreach (InquiryIssue::tree() as $issue) {
foreach ($issue['children'] as $child) {
$options[$child['key']] = $issue['label'].' › '.$child['label'];
}
}
return $options;
})
->helperText('Leer: alle Unteranliegen der zugelassenen Anliegen.'),
Repeater::make('config.preselect')
->label('Vorauswahl')
->helperText('Zum Beispiel das Kursformat „Schul-AG“. Besucher können die Auswahl ändern.')
->schema([
Select::make('field')->label('Angabe')->required()->live()->searchable()->distinct()
->options(fn (): array => ['anliegen' => 'Anliegen', 'unteranliegen' => 'Unteranliegen'] + InquiryField::query()->offered()->whereIn('type', ['select', 'boolean'])->orderBy('name')->pluck('name', 'key')->all()),
Select::make('value')->label('Wert')->required()
->options(function (Get $get): array {
$field = (string) $get('field');
if ($field === 'anliegen') {
return InquiryIssue::query()->offered()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all();
}
if ($field === 'unteranliegen') {
return InquiryIssue::query()->offered()->whereNotNull('parent_id')->orderBy('sort_order')->pluck('label', 'key')->all();
}
$model = InquiryField::query()->where('key', $field)->first();
return $model === null ? [] : collect($model->optionList())->pluck('label', 'key')->all();
}),
])
->addActionLabel('Vorauswahl hinzufügen')
->itemLabel(fn (array $state): ?string => ($state['field'] ?? null) ? ($state['field'] === 'anliegen' ? 'Anliegen' : ($state['field'] === 'unteranliegen' ? 'Unteranliegen' : InquiryField::query()->where('key', $state['field'])->value('name'))) : null),
]),
Section::make('Darstellung')->schema([
Select::make('config.mode')->label('Formularart')->required()->default('compact')
->options(['compact' => 'Kompaktformular: alle Fragen auf einer Seite', 'wizard' => 'Mehrstufiger Dialog: Schritt für Schritt mit Zusammenfassung'])
->helperText('Beides verwendet dieselbe Vorlage, dieselben Bedingungen und dieselbe Prüfung.'),
Select::make('config.open')->label('Beim Aufruf der Seite')->required()->default('inline')
->options(['inline' => 'Formular direkt anzeigen', 'button' => 'Zunächst nur eine Schaltfläche zeigen, die das Formular öffnet']),
]),
Section::make('Texte dieses Einstiegs')
->description('Überschreibt einzelne Texte der Vorlage. Leer lassen: es gilt der Text der Vorlage. Die Texte werden ausschließlich hier und in der Vorlage gepflegt, nie im CMS.')
->collapsed()
->schema(self::textFields()),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryEntry $record): string => (string) $record?->key)
->visible(fn (?InquiryEntry $record): bool => $record !== null),
]);
}
/**
* @return list<Component>
*/
private static function textFields(): array
{
$fields = [];
foreach (FormTexts::FIELDS as $key => [$label, $default, $help, $multiline]) {
$field = $multiline
? Textarea::make("config.texts.$key")->rows(2)->maxLength(1500)
: TextInput::make("config.texts.$key")->maxLength(200);
$fields[] = $field->label($label)->placeholder('Text der Vorlage'.($default !== '' ? ': '.$default : ''))->helperText($help);
}
return $fields;
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryEntries::route('/'),
'edit' => EditInquiryEntry::route('/{record}'),
];
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Filament\Resources\Communication\Entries\Pages;
use App\Domain\Communication\FormTexts;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\Publisher;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Validation\ValidationException;
class EditInquiryEntry extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryEntryResource::class;
protected ?bool $hasUnsavedDataChangesAlert = true;
public function getSubheading(): string|Htmlable|null
{
/** @var InquiryEntry $entry */
$entry = $this->getRecord();
if ($entry->archived_at !== null) {
return 'Archiviert.';
}
if ($entry->published_at === null) {
return 'Entwurf. Im CMS lässt sich dieser Einstieg erst nach „Veröffentlichen“ auswählen.';
}
if (! $entry->isLive()) {
return 'Veröffentlicht, wird aber nicht ausgeliefert: Die Anfragevorlage hat keine gültige Fassung.';
}
return 'Veröffentlicht seit '.$entry->published_at->format('d.m.Y').'.'.($entry->hasUnpublishedChanges() ? ' Der Entwurf enthält Änderungen, die noch nicht veröffentlicht sind.' : '');
}
protected function getHeaderActions(): array
{
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->tooltip('Zeigt den zuletzt gespeicherten Entwurf des Einstiegs mit der gültigen Fassung der Vorlage. Es wird nichts gesendet.')
->url(fn (): string => route('communication.preview.entry', $this->getRecord()))
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->color('primary')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->requiresConfirmation()
->modalHeading('Anfrage-Einstieg veröffentlichen')
->modalDescription('Speichert den Entwurf und macht ihn wirksam. Alle Seiten, die diesen Einstieg einbinden, zeigen danach den neuen Stand.')
->action(function (): void {
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
try {
app(Publisher::class)->publishEntry($this->getRecord());
} catch (ValidationException $e) {
Notification::make()->title('Der Einstieg lässt sich nicht veröffentlichen')->body(implode("\n", array_map(fn (string $line): string => '• '.$line, (array) ($e->errors()['config'] ?? []))))->danger()->persistent()->send();
return;
}
Notification::make()->title('Der Einstieg ist veröffentlicht.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
Action::make('withdraw')
->label('Zurückziehen')
->color('gray')
->visible(fn (): bool => $this->getRecord()->published_at !== null)
->requiresConfirmation()
->modalDescription('Der Einstieg wird nicht mehr ausgeliefert; Seiten, die ihn einbinden, zeigen kein Formular. Die Konfiguration bleibt als Entwurf erhalten.')
->action(function (): void {
app(Publisher::class)->withdrawEntry($this->getRecord());
Notification::make()->title('Der Einstieg ist zurückgezogen.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
...$this->archiveActions(),
];
}
protected function archiveNote(): string
{
return 'Der Einstieg wird archiviert und nicht mehr ausgeliefert. Eingegangene Anfragen bleiben unverändert.';
}
protected function archiveAttributes(): array
{
return ['archived_at' => now(), 'published_config' => null, 'published_at' => null];
}
protected function indexUrl(): string
{
return InquiryEntryResource::getUrl('index');
}
protected function mutateFormDataBeforeFill(array $data): array
{
$config = array_merge(InquiryEntry::emptyConfig(), (array) ($data['config'] ?? []));
$preselect = [];
foreach ((array) ($config['defaults'] ?? []) as $field => $value) {
$preselect[] = ['field' => $field, 'value' => $value];
}
$config['preselect'] = $preselect;
$data['config'] = $config;
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$config = (array) ($data['config'] ?? []);
$defaults = [];
foreach (array_values((array) ($config['preselect'] ?? [])) as $row) {
if (is_array($row) && filled($row['field'] ?? null) && filled($row['value'] ?? null)) {
$defaults[(string) $row['field']] = (string) $row['value'];
}
}
$data['config'] = [
'mode' => ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact',
'open' => ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline',
'allowed_issues' => array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string')),
'allowed_subissues' => array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string')),
'defaults' => $defaults,
'texts' => FormTexts::clean((array) ($config['texts'] ?? [])),
];
return $data;
}
protected function getRedirectUrl(): ?string
{
return null;
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Filament\Resources\Communication\Entries\Pages;
use App\Domain\Communication\InquiryEntry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Entries\InquiryEntryResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryEntries extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryEntryResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Ein Anfrage-Einstieg ist die Nutzungsvariante einer Anfragevorlage: zugelassene Anliegen, Vorauswahl, Texte und Darstellung. Nur veröffentlichte Einstiege lassen sich im CMS mit dem Widget „Anfrage“ auf einer Seite einbinden. Mehrere Seiten können denselben Einstieg verwenden.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Einstieg anlegen')
->modalHeading('Neuer Anfrage-Einstieg')
->modalDescription('Zugelassene Anliegen, Vorauswahl und Texte legst du danach fest.')
->modalSubmitActionLabel('Einstieg anlegen')
->schema([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120),
Select::make('template_id')->label('Anfragevorlage')->required()
->options(fn (): array => InquiryTemplate::query()->whereNull('archived_at')->orderBy('name')->pluck('name', 'id')->all()),
])
->action(function (array $data): void {
$entry = InquiryEntry::query()->create([
'key' => Keys::from($data['name'], InquiryEntry::query()->pluck('key')->all()),
'name' => $data['name'],
'template_id' => $data['template_id'],
'config' => InquiryEntry::emptyConfig(),
]);
Notification::make()->title('Der Einstieg ist angelegt.')->success()->send();
$this->redirect(InquiryEntryResource::getUrl('edit', ['record' => $entry]));
}),
];
}
protected function catalogRows(): array
{
$rows = [];
foreach (InquiryEntry::query()->with('template.publishedVersion')->orderBy('name')->get() as $entry) {
$url = InquiryEntryResource::getUrl('edit', ['record' => $entry]);
$archived = $entry->archived_at !== null;
$live = $entry->isLive();
$config = (array) ($entry->published_config ?? $entry->config);
$mode = ($config['mode'] ?? 'compact') === 'wizard' ? 'Mehrstufiger Dialog' : 'Kompaktformular';
$rows[] = [
'schluessel' => 'e'.$entry->id,
'titel' => $entry->name,
'meta' => 'Anfrage-Einstieg · '.$mode.' · Vorlage „'.$entry->template->name.'“',
'text' => '',
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
$archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($live
? ['label' => 'Veröffentlicht', 'ton' => 'gut']
: ($entry->published_at !== null ? ['label' => 'Veröffentlicht, aber Vorlage nicht gültig', 'ton' => 'achtung'] : ['label' => 'Entwurf', 'ton' => 'offen'])),
$entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null,
])),
'zustand' => [$archived ? 'archiviert' : ($live ? 'veroeffentlicht' : 'entwurf'), ...($entry->published_at !== null && $entry->hasUnpublishedChanges() ? ['aenderungen'] : [])],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Zustand',
'veroeffentlicht' => 'Veröffentlicht',
'entwurf' => 'Entwurf',
'aenderungen' => 'Mit unveröffentlichten Änderungen',
'archiviert' => 'Archiviert',
];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung';
}
protected function einheit(): array
{
return ['Anfrage-Einstieg', 'Anfrage-Einstiege'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfrage-Einstiege', 'text' => 'Mit „Einstieg anlegen“ oben entsteht der erste Einstieg. Dazu braucht es eine veröffentlichte Anfragevorlage.'];
}
}
@@ -0,0 +1,120 @@
<?php
namespace App\Filament\Resources\Communication\Fields;
use App\Domain\Communication\FieldPurpose;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Fields\Pages\EditInquiryField;
use App\Filament\Resources\Communication\Fields\Pages\ListInquiryFields;
use Closure;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Placeholder;
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\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Feldkatalog: wiederverwendbare Eingabefelder. Ein Feld wird einmal definiert und in beliebig vielen Feldgruppen und
* Anfragevorlagen verwendet.
*/
class InquiryFieldResource extends CommunicationResource
{
protected static ?string $model = InquiryField::class;
protected static ?string $navigationLabel = 'Feldkatalog';
protected static ?string $modelLabel = 'Feld';
protected static ?string $pluralModelLabel = 'Felder';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/felder';
protected static ?int $navigationSort = 3;
/**
* @return list<Component>
*/
public static function optionsFields(): array
{
return [
Repeater::make('options')
->label('Auswahlwerte')
->schema([
Hidden::make('key'),
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(120),
])
->minItems(1)
->reorderableWithButtons()
->addActionLabel('Auswahlwert hinzufügen')
->itemLabel(fn (array $state): ?string => $state['label'] ?? null)
->helperText('Reihenfolge wie hier. Jeder Wert erhält eine feste interne Kennung; eine Umbenennung ändert sie nicht und beschädigt keine Anfragen.')
->visible(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false)
->required(fn (Get $get): bool => FieldType::tryFrom((string) $get('type'))?->hasOptions() ?? false),
];
}
public static function form(Schema $schema): Schema
{
return $schema->components([
Section::make('Feld')->schema([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)
->helperText('Nur für die Verwaltung, zum Beispiel „Postleitzahl (Einrichtung)“.'),
TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200)
->helperText('So heißt das Feld im Formular.'),
Textarea::make('help')->label('Hilfetext (optional)')->rows(2)->maxLength(600)
->helperText('Steht unter der Beschriftung.'),
Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live()
->disabled(fn (?InquiryField $record): bool => $record !== null)
->dehydrated(fn (?InquiryField $record): bool => $record === null)
->helperText('Nach dem Anlegen nicht mehr änderbar, weil Bedingungen und Gruppen darauf aufbauen.'),
...self::optionsFields(),
TextInput::make('settings.max_length')->label('Höchste Textlänge')->numeric()->minValue(1)->maxValue(8000)
->visible(fn (Get $get): bool => in_array($get('type'), ['text', 'textarea'], true))
->helperText('Leer: Vorgabe (200 Zeichen einzeilig, 4000 mehrzeilig).'),
TextInput::make('settings.min')->label('Kleinster Wert')->numeric()
->visible(fn (Get $get): bool => $get('type') === 'number'),
TextInput::make('settings.max')->label('Größter Wert')->numeric()
->visible(fn (Get $get): bool => $get('type') === 'number'),
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 der Anfrage zeigt. Jede Vorlage braucht ein Feld „E-Mail-Adresse für Rückfragen“.')
->rule(fn (Get $get): Closure => function (string $attribute, mixed $value, Closure $fail) use ($get): void {
$type = FieldType::tryFrom((string) $get('type'));
if ($value !== null && $type !== null && ! in_array($type, FieldPurpose::from($value)->types(), true)) {
$fail('Diese Verwendung passt nicht zum Feldtyp „'.$type->label().'“.');
}
}),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryField $record): string => (string) $record?->key)
->visible(fn (?InquiryField $record): bool => $record !== null)
->helperText('Ändert sich nie.'),
Toggle::make('active')->label('Zur Verwendung anbieten')
->helperText('Ausgeschaltet kann das Feld in keiner neuen Fassung einer Vorlage verwendet werden; bestehende Fassungen und Anfragen bleiben unverändert.'),
]),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryFields::route('/'),
'edit' => EditInquiryField::route('/{record}'),
];
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Filament\Resources\Communication\Fields\Pages;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Resources\Pages\EditRecord;
class EditInquiryField extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryFieldResource::class;
protected function getHeaderActions(): array
{
return $this->archiveActions();
}
protected function archiveNote(): string
{
return 'Das Feld kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.';
}
protected function indexUrl(): string
{
return InquiryFieldResource::getUrl('index');
}
protected function mutateFormDataBeforeSave(array $data): array
{
/** @var InquiryField $record */
$record = $this->getRecord();
$type = $record->type;
$data['options'] = $type->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null;
$settings = array_filter((array) ($data['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== '');
$data['settings'] = match ($type) {
FieldType::Text, FieldType::Textarea => array_intersect_key($settings, ['max_length' => true]),
FieldType::Number => array_intersect_key($settings, ['min' => true, 'max' => true]),
default => [],
};
return $data;
}
protected function getRedirectUrl(): ?string
{
return InquiryFieldResource::getUrl('index');
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Filament\Resources\Communication\Fields\Pages;
use App\Domain\Communication\FieldType;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Fields\InquiryFieldResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryFields extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryFieldResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Der Feldkatalog enthält alle Eingabefelder, die Anfragevorlagen verwenden können. Ein Feld wie „Postleitzahl“ oder „Telefonnummer“ wird einmal angelegt und überall wiederverwendet. Felder werden nie gelöscht, nur deaktiviert oder archiviert.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Feld anlegen')
->modalHeading('Neues Feld')
->modalDescription('Weitere Angaben wie Hilfetext, Grenzen oder die Verwendung in der Anfrageübersicht legst du danach fest.')
->modalSubmitActionLabel('Feld anlegen')
->schema([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120),
TextInput::make('label')->label('Öffentliche Beschriftung')->required()->maxLength(200),
Select::make('type')->label('Feldtyp')->options(FieldType::options())->required()->live(),
...InquiryFieldResource::optionsFields(),
])
->action(function (array $data): void {
$field = InquiryField::query()->create([
'key' => Keys::from($data['name'], InquiryField::query()->pluck('key')->all()),
'name' => $data['name'],
'label' => $data['label'],
'type' => $data['type'],
'options' => FieldType::from($data['type'])->hasOptions() ? Keys::withKeys((array) ($data['options'] ?? [])) : null,
]);
Notification::make()->title('Das Feld ist angelegt.')->success()->send();
$this->redirect(InquiryFieldResource::getUrl('edit', ['record' => $field]));
}),
];
}
protected function catalogRows(): array
{
$usage = [];
foreach (InquiryFieldGroup::query()->get() as $group) {
foreach ($group->itemList() as $item) {
$usage[$item['field']] = ($usage[$item['field']] ?? 0) + 1;
}
}
$rows = [];
foreach (InquiryField::query()->orderBy('name')->get() as $field) {
$url = InquiryFieldResource::getUrl('edit', ['record' => $field]);
$state = $field->archived_at !== null ? 'archiviert' : ($field->active ? 'aktiv' : 'inaktiv');
$used = $usage[$field->key] ?? 0;
$rows[] = [
'schluessel' => 'f'.$field->id,
'titel' => $field->name,
'meta' => $field->type->label().' · '.$field->key,
'text' => $field->label,
'suchtext' => $field->key.' '.$field->label,
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
['label' => $used === 0 ? 'In keiner Feldgruppe' : ($used === 1 ? 'In 1 Feldgruppe' : "In $used Feldgruppen"), 'ton' => 'neutral'],
$field->purpose !== null ? ['label' => $field->purpose->label(), 'ton' => 'neutral'] : null,
])),
'zustand' => [$state, 'typ_'.$field->type->value],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung, Beschriftung oder Kennung';
}
protected function einheit(): array
{
return ['Feld', 'Felder'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Felder', 'text' => 'Mit „Feld anlegen“ oben entsteht das erste Feld, zum Beispiel „E-Mail-Adresse“.'];
}
}
@@ -0,0 +1,80 @@
<?php
namespace App\Filament\Resources\Communication\Groups;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Groups\Pages\EditInquiryFieldGroup;
use App\Filament\Resources\Communication\Groups\Pages\ListInquiryFieldGroups;
use Filament\Forms\Components\Placeholder;
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\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Feldgruppen: fachliche Zusammenstellung von Feldern in fester Reihenfolge, die mehrere Anfragevorlagen verwenden.
*/
class InquiryFieldGroupResource extends CommunicationResource
{
protected static ?string $model = InquiryFieldGroup::class;
protected static ?string $navigationLabel = 'Feldgruppen';
protected static ?string $modelLabel = 'Feldgruppe';
protected static ?string $pluralModelLabel = 'Feldgruppen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/feldgruppen';
protected static ?int $navigationSort = 4;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)
->helperText('Nur für die Verwaltung, zum Beispiel „Kindergruppe“.'),
TextInput::make('label')->label('Überschrift im Formular (optional)')->maxLength(200)
->helperText('Leer: die fachliche Bezeichnung.'),
Textarea::make('description')->label('Erläuterung im Formular (optional)')->rows(2)->maxLength(600),
Repeater::make('items')
->label('Felder der Gruppe')
->schema([
Select::make('field')->label('Feld')->required()->searchable()->distinct()
->options(fn (): array => InquiryField::query()->offered()->orderBy('name')->get()->mapWithKeys(
fn (InquiryField $field): array => [$field->key => $field->name.' ('.$field->type->label().')']
)->all()),
Toggle::make('required')->label('Pflichtfeld')->default(false)
->helperText('Eine Vorlage kann ein Feld zusätzlich unter einer Bedingung zur Pflicht machen.'),
])
->minItems(1)
->reorderableWithButtons()
->addActionLabel('Feld hinzufügen')
->itemLabel(fn (array $state): ?string => InquiryField::query()->where('key', $state['field'] ?? '')->value('name'))
->helperText('Die Reihenfolge hier ist die Reihenfolge im Formular.'),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryFieldGroup $record): string => (string) $record?->key)
->visible(fn (?InquiryFieldGroup $record): bool => $record !== null),
Toggle::make('active')->label('Zur Verwendung anbieten'),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryFieldGroups::route('/'),
'edit' => EditInquiryFieldGroup::route('/{record}'),
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Filament\Resources\Communication\Groups\Pages;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Support\ArchivesCommunicationRecords;
use Filament\Resources\Pages\EditRecord;
class EditInquiryFieldGroup extends EditRecord
{
use ArchivesCommunicationRecords;
protected static string $resource = InquiryFieldGroupResource::class;
protected function getHeaderActions(): array
{
return $this->archiveActions();
}
protected function archiveNote(): string
{
return 'Die Gruppe kann in keiner neuen Fassung einer Vorlage mehr verwendet werden. Veröffentlichte Fassungen und eingegangene Anfragen bleiben unverändert.';
}
protected function indexUrl(): string
{
return InquiryFieldGroupResource::getUrl('index');
}
protected function getRedirectUrl(): ?string
{
return InquiryFieldGroupResource::getUrl('index');
}
}
@@ -0,0 +1,139 @@
<?php
namespace App\Filament\Resources\Communication\Groups\Pages;
use App\Domain\Communication\InquiryField;
use App\Domain\Communication\InquiryFieldGroup;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Groups\InquiryFieldGroupResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryFieldGroups extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryFieldGroupResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Feldgruppen fassen Felder fachlich zusammen, zum Beispiel „Kontaktinformationen“ oder „Kindergruppe“. Eine Gruppe wird in beliebig vielen Anfragevorlagen verwendet; Reihenfolge und Pflichtangaben pflegst du hier einmal.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Feldgruppe anlegen')
->modalHeading('Neue Feldgruppe')
->modalDescription('Die Felder legst du danach auf der Seite der Gruppe fest.')
->modalSubmitActionLabel('Feldgruppe anlegen')
->schema([TextInput::make('name')->label('Fachliche Bezeichnung')->required()->maxLength(120)])
->action(function (array $data): void {
$group = InquiryFieldGroup::query()->create([
'key' => Keys::from($data['name'], InquiryFieldGroup::query()->pluck('key')->all()),
'name' => $data['name'],
'items' => [],
'sort_order' => ((int) InquiryFieldGroup::query()->max('sort_order')) + 10,
]);
Notification::make()->title('Die Feldgruppe ist angelegt.')->success()->send();
$this->redirect(InquiryFieldGroupResource::getUrl('edit', ['record' => $group]));
}),
];
}
public function moveGroup(int $id, string $direction): void
{
$group = InquiryFieldGroup::query()->findOrFail($id);
$all = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get()->values();
$index = $all->search(fn (InquiryFieldGroup $item): bool => $item->id === $group->id);
$target = $direction === 'up' ? $index - 1 : $index + 1;
if ($index === false || $target < 0 || $target >= $all->count()) {
return;
}
$order = $all->all();
[$order[$index], $order[$target]] = [$order[$target], $order[$index]];
foreach ($order as $position => $item) {
$item->forceFill(['sort_order' => ($position + 1) * 10])->save();
}
}
protected function catalogRows(): array
{
$templates = InquiryTemplate::query()->get(['id', 'draft']);
$names = InquiryField::query()->pluck('name', 'key');
$groups = InquiryFieldGroup::query()->orderBy('sort_order')->orderBy('id')->get();
$rows = [];
foreach ($groups as $i => $group) {
$url = InquiryFieldGroupResource::getUrl('edit', ['record' => $group]);
$state = $group->archived_at !== null ? 'archiviert' : ($group->active ? 'aktiv' : 'inaktiv');
$used = $templates->filter(function (InquiryTemplate $template) use ($group): bool {
foreach ((array) ($template->draft['steps'] ?? []) as $step) {
foreach ((array) ($step['items'] ?? []) as $item) {
if (($item['group'] ?? null) === $group->key) {
return true;
}
}
}
return false;
})->count();
$fieldNames = array_map(fn (array $item): string => (string) ($names[$item['field']] ?? $item['field']), $group->itemList());
$rows[] = [
'schluessel' => 'g'.$group->id,
'titel' => $group->name,
'meta' => 'Feldgruppe · '.count($fieldNames).' '.(count($fieldNames) === 1 ? 'Feld' : 'Felder'),
'text' => implode(', ', $fieldNames),
'symbol' => 'modul',
'url' => $url,
'chips' => [
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
['label' => $used === 0 ? 'In keiner Vorlage' : ($used === 1 ? 'In 1 Vorlage' : "In $used Vorlagen"), 'ton' => 'neutral'],
],
'zustand' => [$state],
'aktionen' => [
['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'],
...($i > 0 ? [['label' => 'Nach oben', 'wire' => "moveGroup({$group->id}, 'up')"]] : []),
...($i < $groups->count() - 1 ? [['label' => 'Nach unten', 'wire' => "moveGroup({$group->id}, 'down')"]] : []),
],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Feldname';
}
protected function einheit(): array
{
return ['Feldgruppe', 'Feldgruppen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Feldgruppen', 'text' => 'Mit „Feldgruppe anlegen“ oben entsteht die erste Gruppe, zum Beispiel „Kontaktinformationen“.'];
}
}
@@ -0,0 +1,144 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\Inquiry;
use App\Filament\Resources\Communication\Inquiries\Pages\ListInquiries;
use App\Filament\Resources\Communication\Inquiries\Pages\ViewInquiry;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Zentraler Posteingang aller Anfragen (ADR-60). Anfragen enthalten personenbezogene Daten: Zugriff nur für
* Kundenbetreuung und Systemverwaltung.
*/
class InquiryResource extends Resource
{
protected static ?string $model = Inquiry::class;
protected static string|\UnitEnum|null $navigationGroup = 'Kommunikation';
protected static ?string $navigationLabel = 'Anfragen';
protected static ?string $modelLabel = 'Anfrage';
protected static ?string $pluralModelLabel = 'Anfragen';
protected static ?string $recordTitleAttribute = 'reference';
protected static ?string $slug = 'anfragen';
protected static ?int $navigationSort = 1;
public static function canViewAny(): bool
{
return CommunicationAccess::inbox();
}
public static function canView(Model $record): bool
{
return CommunicationAccess::inbox();
}
public static function canCreate(): bool
{
return false;
}
public static function canEdit(Model $record): bool
{
return false;
}
public static function canDelete(Model $record): bool
{
return false;
}
public static function canDeleteAny(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
if (! CommunicationAccess::inbox()) {
return null;
}
$new = Inquiry::query()->where('status', 'neu')->count();
return $new > 0 ? (string) $new : null;
}
public static function getNavigationBadgeTooltip(): ?string
{
return 'Neue Anfragen';
}
public static function infolist(Schema $schema): Schema
{
return $schema->components([
Section::make('Ansprechpartner')->columns(2)->schema([
TextEntry::make('contact_name')->label('Name')->placeholder('Nicht angegeben'),
TextEntry::make('organisation')->label('Organisation')->placeholder('Nicht angegeben'),
TextEntry::make('contact_email')->label('E-Mail-Adresse')->placeholder('Nicht angegeben')->copyable(),
TextEntry::make('contact_phone')->label('Telefon')->placeholder('Nicht angegeben'),
]),
Section::make('Anliegen')->columns(2)->schema([
TextEntry::make('issue')->label('Anliegen')->state(fn (Inquiry $record): string => $record->issueTitle() ?: 'Nicht erfragt'),
TextEntry::make('status')->label('Bearbeitungsstatus')->badge()
->formatStateUsing(fn ($state): string => $state->label())
->color(fn ($state): string => $state->color()),
TextEntry::make('entry.name')->label('Anfrage-Einstieg')->placeholder('Gelöscht'),
TextEntry::make('source_path')->label('Quellseite')->placeholder('Unbekannt'),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i'),
TextEntry::make('reference')->label('Kennzeichen')->copyable(),
TextEntry::make('version')->label('Formularfassung')
->state(fn (Inquiry $record): string => 'Vorlage „'.($record->templateVersion->template->name ?? '').'“, Fassung '.($record->templateVersion->version ?? '')),
TextEntry::make('notification')->label('Benachrichtigung')
->state(fn (Inquiry $record): string => $record->notified_at !== null ? 'Gesendet am '.$record->notified_at->format('d.m.Y H:i') : ($record->notification_error ?: 'Noch nicht gesendet'))
->color(fn (Inquiry $record): ?string => $record->notified_at === null && $record->notification_error !== null ? 'danger' : null),
]),
Section::make('Antworten')->schema([
ViewEntry::make('answers')->hiddenLabel()->view('filament.communication.answers'),
]),
Section::make('Nachricht')->visible(fn (Inquiry $record): bool => filled($record->message))->schema([
TextEntry::make('message')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']),
]),
Section::make('Interne Notizen')->schema([
RepeatableEntry::make('notes')->hiddenLabel()->placeholder('Noch keine Notizen.')->schema([
TextEntry::make('body')->hiddenLabel()->extraAttributes(['style' => 'white-space: pre-line']),
TextEntry::make('meta')->hiddenLabel()->color('gray')
->state(fn ($record): string => ($record->author->name ?? 'Unbekannt').' · '.$record->created_at->format('d.m.Y H:i')),
]),
]),
]);
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('reference')->label('Kennzeichen')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiries::route('/'),
'view' => ViewInquiry::route('/{record}'),
];
}
}
@@ -0,0 +1,128 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries\Pages;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryStatus;
use App\Filament\Resources\Communication\Inquiries\InquiryResource;
use App\Filament\Support\Bestand;
use App\Filament\Support\ListsCatalog;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Str;
use Livewire\Attributes\Url;
class ListInquiries extends ListRecords
{
use ListsCatalog {
bestand as protected baseBestand;
}
protected static string $resource = InquiryResource::class;
#[Url(as: 'anliegen', except: 'alle')]
public string $anliegen = 'alle';
#[Url(as: 'sortierung', except: 'neu')]
public string $sortierung = 'neu';
public function getSubheading(): string|Htmlable|null
{
return 'Alle eingegangenen Anfragen aus allen Anfrage-Einstiegen. Der Status wird von Hand gesetzt; Notizen sind nur intern sichtbar.';
}
protected function bestandFilterEigenschaften(): array
{
return ['suche', 'zustand', 'anliegen', 'sortierung'];
}
public function resetFilters(): void
{
$this->suche = '';
$this->zustand = 'alle';
$this->anliegen = 'alle';
$this->sortierung = 'neu';
$this->bestandGrenze = Bestand::SCHRITT;
}
public function bestand(): array
{
$b = $this->baseBestand();
$issues = Inquiry::query()->whereNotNull('issue_key')->select('issue_key', 'issue_label')->distinct()->orderBy('issue_label')->pluck('issue_label', 'issue_key')->all();
$b['filter'][] = ['eigenschaft' => 'anliegen', 'label' => 'Anliegen', 'vorgabe' => 'alle', 'optionen' => ['alle' => 'Alle Anliegen'] + $issues];
$b['sortierung'] = ['eigenschaft' => 'sortierung', 'label' => 'Sortierung', 'optionen' => ['neu' => 'Neueste zuerst', 'alt' => 'Älteste zuerst', 'name' => 'Name', 'status' => 'Status']];
return $b;
}
protected function catalogRows(): array
{
$query = Inquiry::query()->with('entry');
if ($this->anliegen !== 'alle') {
$query->where('issue_key', $this->anliegen);
}
$inquiries = match ($this->sortierung) {
'alt' => $query->orderBy('created_at')->orderBy('id')->get(),
'name' => $query->get()->sortBy(fn (Inquiry $i): string => mb_strtolower($i->contactTitle()), SORT_NATURAL)->values(),
'status' => $query->get()->sortBy(fn (Inquiry $i): string => array_search($i->status, InquiryStatus::cases(), true).'-'.(PHP_INT_MAX - $i->created_at->getTimestamp()))->values(),
default => $query->orderByDesc('created_at')->orderByDesc('id')->get(),
};
$rows = [];
foreach ($inquiries as $inquiry) {
$url = InquiryResource::getUrl('view', ['record' => $inquiry]);
$failed = $inquiry->notified_at === null && $inquiry->notification_error !== null;
$rows[] = [
'schluessel' => 'q'.$inquiry->id,
'titel' => $inquiry->contactTitle().($inquiry->organisation ? ' · '.$inquiry->organisation : ''),
'meta' => $inquiry->created_at->format('d.m.Y H:i').' · '.($inquiry->issueTitle() ?: 'Ohne Anliegen').' · '.($inquiry->entry->name ?? 'Einstieg gelöscht'),
'text' => Str::limit((string) $inquiry->message, 180),
'suchtext' => implode(' ', array_filter([$inquiry->contact_email, $inquiry->reference, $inquiry->contact_phone])),
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
['label' => $inquiry->status->label(), 'ton' => match ($inquiry->status) {
InquiryStatus::Neu => 'offen',
InquiryStatus::RueckfrageOffen => 'achtung',
InquiryStatus::Erledigt => 'gut',
default => 'neutral',
}],
$failed ? ['label' => 'Benachrichtigung fehlgeschlagen', 'ton' => 'achtung'] : null,
])),
'zustand' => array_values(array_filter([$inquiry->status->value, $inquiry->status !== InquiryStatus::Erledigt ? 'offen' : null, $failed ? 'mailfehler' : null])),
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Status',
'offen' => 'Nicht erledigt',
...InquiryStatus::options(),
'mailfehler' => 'Benachrichtigung fehlgeschlagen',
];
}
protected function suchPlatzhalter(): string
{
return 'Name, E-Mail, Organisation, Nachricht oder Kennzeichen';
}
protected function einheit(): array
{
return ['Anfrage', 'Anfragen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anfragen', 'text' => 'Sobald jemand über einen Anfrage-Einstieg eine Anfrage sendet, erscheint sie hier.'];
}
}
@@ -0,0 +1,106 @@
<?php
namespace App\Filament\Resources\Communication\Inquiries\Pages;
use App\Domain\Communication\CommunicationAccess;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryNote;
use App\Domain\Communication\InquiryStatus;
use App\Filament\Resources\Communication\Inquiries\InquiryResource;
use App\Jobs\SendInquiryNotification;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Contracts\Support\Htmlable;
class ViewInquiry extends ViewRecord
{
protected static string $resource = InquiryResource::class;
public function getTitle(): string|Htmlable
{
/** @var Inquiry $inquiry */
$inquiry = $this->getRecord();
return $inquiry->contactTitle();
}
public function getSubheading(): string|Htmlable|null
{
/** @var Inquiry $inquiry */
$inquiry = $this->getRecord();
return 'Anfrage '.$inquiry->reference.' vom '.$inquiry->created_at->format('d.m.Y H:i');
}
protected function getHeaderActions(): array
{
return [
Action::make('status')
->label('Status ändern')
->icon('heroicon-o-arrow-path')
->modalHeading('Bearbeitungsstatus')
->modalSubmitActionLabel('Status speichern')
->fillForm(fn (): array => ['status' => $this->getRecord()->status->value])
->schema([Select::make('status')->label('Neuer Status')->options(InquiryStatus::options())->required()])
->action(function (array $data): void {
$this->getRecord()->forceFill(['status' => $data['status']])->save();
Notification::make()->title('Der Status ist geändert.')->success()->send();
$this->refreshFormData(['status']);
}),
Action::make('note')
->label('Notiz hinzufügen')
->icon('heroicon-o-pencil-square')
->color('gray')
->modalHeading('Interne Notiz')
->modalDescription('Nur für das Team sichtbar, nie für den Anfragenden.')
->modalSubmitActionLabel('Notiz speichern')
->schema([Textarea::make('body')->label('Notiz')->required()->rows(4)->maxLength(4000)])
->action(function (array $data): void {
InquiryNote::query()->create([
'inquiry_id' => $this->getRecord()->id,
'user_id' => CommunicationAccess::user()?->id,
'body' => $data['body'],
]);
$this->getRecord()->load('notes');
Notification::make()->title('Die Notiz ist gespeichert.')->success()->send();
$this->redirect(InquiryResource::getUrl('view', ['record' => $this->getRecord()]));
}),
Action::make('resend')
->label('Benachrichtigung erneut senden')
->icon('heroicon-o-envelope')
->color('gray')
->visible(fn (): bool => $this->getRecord()->notified_at === null)
->requiresConfirmation()
->modalDescription('Sendet die interne Benachrichtigung an die in den Einstellungen hinterlegten Empfänger noch einmal.')
->action(function (): void {
SendInquiryNotification::dispatchSync($this->getRecord()->id);
$inquiry = $this->getRecord()->fresh();
if ($inquiry->notified_at !== null) {
Notification::make()->title('Die Benachrichtigung ist gesendet.')->success()->send();
} else {
Notification::make()->title('Die Benachrichtigung ist weiterhin fehlgeschlagen.')->body((string) $inquiry->notification_error)->danger()->send();
}
$this->redirect(InquiryResource::getUrl('view', ['record' => $inquiry]));
}),
Action::make('erase')
->label('Anfrage löschen')
->icon('heroicon-o-trash')
->color('danger')
->visible(fn (): bool => CommunicationAccess::erase())
->requiresConfirmation()
->modalHeading('Anfrage endgültig löschen?')
->modalDescription('Die Anfrage mit allen Antworten und Notizen wird unwiderruflich gelöscht, zum Beispiel auf Wunsch der betroffenen Person. Das lässt sich nicht rückgängig machen.')
->action(function (): void {
$this->getRecord()->delete();
Notification::make()->title('Die Anfrage ist gelöscht.')->success()->send();
$this->redirect(InquiryResource::getUrl('index'));
}),
];
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Resources\Communication\Issues;
use App\Domain\Communication\InquiryIssue;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Issues\Pages\EditInquiryIssue;
use App\Filament\Resources\Communication\Issues\Pages\ListInquiryIssues;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Anliegen und Unteranliegen: warum ein Besucher Kontakt aufnimmt. Sie steuern die Besucherführung und die bedingte
* Anzeige von Feldern.
*/
class InquiryIssueResource extends CommunicationResource
{
protected static ?string $model = InquiryIssue::class;
protected static ?string $navigationLabel = 'Anliegen';
protected static ?string $modelLabel = 'Anliegen';
protected static ?string $pluralModelLabel = 'Anliegen';
protected static ?string $recordTitleAttribute = 'label';
protected static ?string $slug = 'kommunikation/anliegen';
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120)
->helperText('So sieht es der Besucher. Die Bezeichnung darf sich ändern; die fachliche Identität bleibt.'),
Textarea::make('description')->label('Beschreibung (optional)')->rows(3)->maxLength(300)
->helperText('Ein Satz unter der Bezeichnung in der Auswahl.'),
Placeholder::make('hierarchy')->label('Einordnung')->content(
fn (?InquiryIssue $record): string => $record?->parent !== null ? 'Unteranliegen von „'.$record->parent->label.'“' : 'Anliegen auf oberster Ebene'
),
Placeholder::make('key_info')->label('Interne Kennung')->content(fn (?InquiryIssue $record): string => (string) $record?->key)
->helperText('Wird beim Anlegen vergeben und ändert sich nie. Bereits eingegangene Anfragen und Bedingungen beziehen sich darauf.'),
Toggle::make('active')->label('Besuchern anbieten')
->helperText('Ausgeschaltet erscheint das Anliegen in keiner neuen Fassung einer Vorlage; bestehende Fassungen und Anfragen bleiben unverändert.'),
]);
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('label')->label('Bezeichnung')]);
}
public static function getPages(): array
{
return [
'index' => ListInquiryIssues::route('/'),
'edit' => EditInquiryIssue::route('/{record}'),
];
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Filament\Resources\Communication\Issues\Pages;
use App\Domain\Communication\InquiryIssue;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
class EditInquiryIssue extends EditRecord
{
protected static string $resource = InquiryIssueResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('archive')
->label('Archivieren')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at === null)
->requiresConfirmation()
->modalDescription('Das Anliegen wird in neuen Fassungen von Vorlagen nicht mehr angeboten. Bereits eingegangene Anfragen und veröffentlichte Fassungen bleiben unverändert.')
->action(function (): void {
/** @var InquiryIssue $issue */
$issue = $this->getRecord();
$issue->forceFill(['archived_at' => now(), 'active' => false])->save();
foreach ($issue->children as $child) {
$child->forceFill(['archived_at' => $child->archived_at ?? now(), 'active' => false])->save();
}
Notification::make()->title('Archiviert.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('index'));
}),
Action::make('restore')
->label('Wiederherstellen')
->color('gray')
->visible(fn (): bool => $this->getRecord()->archived_at !== null)
->action(function (): void {
$this->getRecord()->forceFill(['archived_at' => null])->save();
Notification::make()->title('Wiederhergestellt. Das Anliegen ist weiterhin deaktiviert, bis es eingeschaltet wird.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $this->getRecord()]));
}),
];
}
protected function getRedirectUrl(): ?string
{
return InquiryIssueResource::getUrl('index');
}
}
@@ -0,0 +1,143 @@
<?php
namespace App\Filament\Resources\Communication\Issues\Pages;
use App\Domain\Communication\InquiryIssue;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Issues\InquiryIssueResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListInquiryIssues extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryIssueResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Ein Anliegen beschreibt, weshalb Besucher Kontakt aufnehmen. Unteranliegen verfeinern es. Welche Anliegen ein Formular anbietet und welche Felder dazu erscheinen, legst du in den Anfragevorlagen und Anfrage-Einstiegen fest. Anliegen werden nie gelöscht, nur deaktiviert oder archiviert.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Anliegen anlegen')
->modalHeading('Neues Anliegen')
->modalDescription('Bezeichnung und Einordnung genügen. Die interne Kennung wird einmalig vergeben.')
->modalSubmitActionLabel('Anliegen anlegen')
->schema([
Select::make('parent_id')->label('Einordnung')
->options(fn (): array => InquiryIssue::query()->whereNull('parent_id')->orderBy('sort_order')->pluck('label', 'id')->all())
->placeholder('Anliegen auf oberster Ebene')
->helperText('Alternativ als Unteranliegen eines bestehenden Anliegens.'),
TextInput::make('label')->label('Öffentliche Bezeichnung')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (optional)')->rows(2)->maxLength(300),
])
->action(function (array $data): void {
$issue = InquiryIssue::query()->create([
'parent_id' => $data['parent_id'] ?? null,
'key' => Keys::from($data['label'], InquiryIssue::query()->pluck('key')->all()),
'label' => $data['label'],
'description' => $data['description'] ?? null,
'sort_order' => ((int) InquiryIssue::query()->where('parent_id', $data['parent_id'] ?? null)->max('sort_order')) + 10,
]);
Notification::make()->title('Das Anliegen ist angelegt.')->success()->send();
$this->redirect(InquiryIssueResource::getUrl('edit', ['record' => $issue]));
}),
];
}
/** Ein Anliegen vor oder hinter seinem Nachbarn derselben Ebene einordnen. */
public function moveIssue(int $id, string $direction): void
{
$issue = InquiryIssue::query()->findOrFail($id);
$siblings = InquiryIssue::query()->where('parent_id', $issue->parent_id)->orderBy('sort_order')->orderBy('id')->get()->values();
$index = $siblings->search(fn (InquiryIssue $item): bool => $item->id === $issue->id);
$target = $direction === 'up' ? $index - 1 : $index + 1;
if ($index === false || $target < 0 || $target >= $siblings->count()) {
return;
}
$order = $siblings->all();
[$order[$index], $order[$target]] = [$order[$target], $order[$index]];
foreach ($order as $position => $item) {
$item->forceFill(['sort_order' => ($position + 1) * 10])->save();
}
}
protected function catalogRows(): array
{
$all = InquiryIssue::query()->orderBy('sort_order')->orderBy('id')->get();
$children = $all->whereNotNull('parent_id')->groupBy('parent_id');
$rows = [];
$tops = $all->whereNull('parent_id')->values();
$row = function (InquiryIssue $issue, ?InquiryIssue $parent, int $position, int $count) use (&$rows): void {
$url = InquiryIssueResource::getUrl('edit', ['record' => $issue]);
$state = $issue->archived_at !== null ? 'archiviert' : ($issue->active ? 'aktiv' : 'inaktiv');
$rows[] = [
'schluessel' => 'i'.$issue->id,
'titel' => ($parent !== null ? '↳ ' : '').$issue->label,
'meta' => $parent !== null ? 'Unteranliegen von „'.$parent->label.'“' : 'Anliegen',
'text' => (string) ($issue->description ?? ''),
'symbol' => 'modul',
'url' => $url,
'chips' => [
match ($state) {
'aktiv' => ['label' => 'Wird angeboten', 'ton' => 'gut'],
'inaktiv' => ['label' => 'Deaktiviert', 'ton' => 'leise'],
default => ['label' => 'Archiviert', 'ton' => 'leise'],
},
],
'zustand' => [$state],
'aktionen' => [
['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift'],
...($position > 0 ? [['label' => 'Nach oben', 'wire' => "moveIssue({$issue->id}, 'up')"]] : []),
...($position < $count - 1 ? [['label' => 'Nach unten', 'wire' => "moveIssue({$issue->id}, 'down')"]] : []),
],
];
};
foreach ($tops as $i => $top) {
$row($top, null, $i, $tops->count());
$kids = ($children[$top->id] ?? collect())->values();
foreach ($kids as $j => $child) {
$row($child, $top, $j, $kids->count());
}
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Wird angeboten', 'inaktiv' => 'Deaktiviert', 'archiviert' => 'Archiviert'];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Beschreibung';
}
protected function einheit(): array
{
return ['Anliegen', 'Anliegen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Anliegen', 'text' => 'Mit „Anliegen anlegen“ oben entsteht das erste Anliegen, zum Beispiel „Kurse & Workshops“. Auf der Seite „Einstellungen“ lässt sich eine Beispielkonfiguration anlegen.'];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Communication\Templates;
use App\Domain\Communication\InquiryTemplate;
use App\Filament\Resources\Communication\CommunicationResource;
use App\Filament\Resources\Communication\Templates\Pages\EditInquiryTemplate;
use App\Filament\Resources\Communication\Templates\Pages\ListInquiryTemplates;
use App\Filament\Resources\Communication\Templates\RelationManagers\VersionsRelationManager;
use App\Filament\Support\TemplateEditor;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Anfragevorlagen: ein vollständiger fachlicher Anfrageprozess. 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 $modelLabel = 'Anfragevorlage';
protected static ?string $pluralModelLabel = 'Anfragevorlagen';
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'kommunikation/vorlagen';
protected static ?int $navigationSort = 5;
public static function form(Schema $schema): Schema
{
return $schema->components(TemplateEditor::schema());
}
public static function table(Table $table): Table
{
return $table->columns([TextColumn::make('name')->label('Bezeichnung')]);
}
public static function getRelations(): array
{
return [VersionsRelationManager::class];
}
public static function getPages(): array
{
return [
'index' => ListInquiryTemplates::route('/'),
'edit' => EditInquiryTemplate::route('/{record}'),
];
}
}
@@ -0,0 +1,151 @@
<?php
namespace App\Filament\Resources\Communication\Templates\Pages;
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 diese Vorlage 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('Neue Fassung 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('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();
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. Noch kein Anfrage-Einstieg verwendet diese Vorlage.';
}
$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.';
}
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.';
}
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 dieser Vorlage. Bitte zuerst zurückziehen oder auf eine andere Vorlage umstellen." : null;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$data['draft'] = TemplateDraft::clean((array) ($data['draft'] ?? []));
return $data;
}
protected function getRedirectUrl(): ?string
{
return null;
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Filament\Resources\Communication\Templates\Pages;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\Keys;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Filament\Support\ListsCatalog;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Str;
class ListInquiryTemplates extends ListRecords
{
use ListsCatalog;
protected static string $resource = InquiryTemplateResource::class;
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.';
}
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')
->schema([
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(120),
Textarea::make('description')->label('Beschreibung (nur Verwaltung, optional)')->rows(2)->maxLength(400),
])
->action(function (array $data): void {
$draft = InquiryTemplate::emptyDraft();
$draft['steps'] = [['key' => 's'.Str::lower(Str::random(6)), 'title' => 'Ihre Angaben', 'intro' => null, 'items' => []]];
$template = InquiryTemplate::query()->create([
'key' => Keys::from($data['name'], InquiryTemplate::query()->pluck('key')->all()),
'name' => $data['name'],
'description' => $data['description'] ?? null,
'draft' => $draft,
]);
Notification::make()->title('Die Vorlage ist angelegt.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $template]));
}),
];
}
protected function catalogRows(): array
{
$rows = [];
foreach (InquiryTemplate::query()->with('publishedVersion')->withCount('entries')->orderBy('name')->get() as $template) {
$url = InquiryTemplateResource::getUrl('edit', ['record' => $template]);
$archived = $template->archived_at !== null;
$published = $template->isPublished();
$changes = $published && $template->hasUnpublishedChanges();
$steps = count((array) ($template->draft['steps'] ?? []));
$rows[] = [
'schluessel' => 't'.$template->id,
'titel' => $template->name,
'meta' => 'Anfragevorlage · '.$steps.' '.($steps === 1 ? 'Schritt' : 'Schritte').' · '.$template->entries_count.' '.($template->entries_count === 1 ? 'Einstieg' : 'Einstiege'),
'text' => (string) ($template->description ?? ''),
'symbol' => 'modul',
'url' => $url,
'chips' => array_values(array_filter([
$archived ? ['label' => 'Archiviert', 'ton' => 'leise'] : ($published
? ['label' => 'Fassung '.$template->publishedVersion->version.' gültig', 'ton' => 'gut']
: ['label' => 'Noch nicht veröffentlicht', 'ton' => 'offen']),
$changes ? ['label' => 'Änderungen noch nicht veröffentlicht', 'ton' => 'achtung'] : null,
])),
'zustand' => [$archived ? 'archiviert' : ($published ? 'veroeffentlicht' : 'entwurf'), ...($changes ? ['aenderungen'] : [])],
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Zustand',
'veroeffentlicht' => 'Veröffentlicht',
'entwurf' => 'Noch nicht veröffentlicht',
'aenderungen' => 'Mit unveröffentlichten Änderungen',
'archiviert' => 'Archiviert',
];
}
protected function suchPlatzhalter(): string
{
return 'Bezeichnung oder Beschreibung';
}
protected function einheit(): array
{
return ['Anfragevorlage', 'Anfragevorlagen'];
}
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.'];
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Filament\Resources\Communication\Templates\RelationManagers;
use App\Domain\Communication\Inquiry;
use App\Domain\Communication\InquiryTemplate;
use App\Domain\Communication\InquiryTemplateVersion;
use App\Domain\Communication\Publisher;
use App\Filament\Resources\Communication\Templates\InquiryTemplateResource;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Validation\ValidationException;
/**
* Fassungen einer Anfragevorlage: unveränderlich, jederzeit nachvollziehbar. Eine frühere Fassung lässt sich wieder in
* Kraft setzen oder als Entwurf laden.
*/
class VersionsRelationManager extends RelationManager
{
protected static string $relationship = 'versions';
protected static ?string $title = 'Fassungen';
protected static ?bool $isLazyLoaded = false;
public function table(Table $table): Table
{
/** @var InquiryTemplate $template */
$template = $this->getOwnerRecord();
return $table
->columns([
TextColumn::make('version')->label('Fassung')->prefix('Nr. '),
TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i'),
TextColumn::make('published_by')->label('Von')->state(fn (InquiryTemplateVersion $record): string => (string) User::query()->whereKey($record->published_by)->value('name')),
TextColumn::make('note')->label('Bemerkung')->placeholder('–'),
TextColumn::make('state')->label('Zustand')->badge()
->color(fn (string $state): string => $state === 'Gültig' ? 'success' : 'gray')
->state(fn (InquiryTemplateVersion $record): string => $record->id === $this->getOwnerRecord()->published_version_id ? 'Gültig' : 'Früher'),
TextColumn::make('inquiries')->label('Anfragen')->state(fn (InquiryTemplateVersion $record): int => Inquiry::query()->where('template_version_id', $record->id)->count()),
])
->recordActions([
Action::make('restore')
->label('Wieder in Kraft setzen')
->visible(fn (InquiryTemplateVersion $record): bool => $record->id !== $template->fresh()->published_version_id)
->requiresConfirmation()
->modalDescription('Besucher sehen danach wieder diese Fassung. Der Entwurf bleibt unverändert. Eingegangene Anfragen bleiben ihrer damaligen Fassung zugeordnet.')
->action(function (InquiryTemplateVersion $record): void {
try {
app(Publisher::class)->restoreVersion($this->getOwnerRecord(), $record);
} catch (ValidationException $e) {
Notification::make()->title('Nicht möglich')->body(implode(' ', $e->errors()['draft'] ?? []))->danger()->send();
return;
}
Notification::make()->title('Fassung '.$record->version.' ist wieder gültig.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
Action::make('load')
->label('Als Entwurf laden')
->color('gray')
->requiresConfirmation()
->modalDescription('Der aktuelle Entwurf wird durch den Stand dieser Fassung ersetzt. Veröffentlicht wird dadurch nichts.')
->action(function (InquiryTemplateVersion $record): void {
$this->getOwnerRecord()->forceFill(['draft' => $record->source])->save();
Notification::make()->title('Der Entwurf entspricht jetzt Fassung '.$record->version.'.')->success()->send();
$this->redirect(InquiryTemplateResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
])
->defaultSort('version', 'desc')
->paginated(false);
}
}