Files
Lars add2367869
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s
Eindeutige iCal-Kalenderspiegelungen automatisch und widerrufbar zuordnen
2026-10-29 17:01:30 +01:00

213 lines
15 KiB
PHP
Raw Permalink 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\Resources\Channels\Pages;
use App\Actions\AnalyzeChannelCalendar;
use App\Actions\ApplyChannelRules;
use App\Actions\ConfigureChannelExport;
use App\Actions\SaveChannelRules;
use App\Channels\ChannelSyncException;
use App\Channels\ICal\ICalExportFields;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Channels\ICal\ICalRuleEngine;
use App\Filament\Resources\Channels\ChannelResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use Filament\Actions\Action;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ChannelRules extends EditRecord
{
protected static string $resource = ChannelResource::class;
protected static ?string $title = 'Kalenderanalyse, Regeln & Exportfelder';
public function fieldOptions(): array
{
return collect(array_keys($this->record->ical_analysis['fields'] ?? []))->mapWithKeys(fn (string $field): array => [$field => $field])->all();
}
protected function mutateFormDataBeforeFill(array $data): array
{
return ['rules' => $this->record->ical_rules ?? [], 'export_names' => (bool) $this->record->ical_export_names, 'export_mapping' => $this->record->ical_export_mapping ?? []];
}
public function form(Schema $schema): Schema
{
return $schema->components([
TextEntry::make('rule_status')->label('Gespeicherter Regelstand')
->state(fn (): string => $this->savedRulesStatus())
->helperText('Speichern legt einen Entwurf ab. „Speichern & anwenden“ aktiviert ihn für vorhandene Einträge und die nächsten Importe.')
->columnSpanFull(),
Section::make('1. Gefundene Kalenderfelder und Originalereignisse')->description('„Kalender analysieren“ liest die hinterlegte Adresse. Die Analyse verändert keine Belegungen.')
->schema([View::make('filament.resources.channels.rule-analysis')]),
Section::make('2. Erkennungsregeln')->description('Kleinere Prioritätszahlen zuerst. Bei mehreren Treffern gilt die erste passende aktive Regel. „Entwurf speichern“ und „Speichern & anwenden“ stehen oben auf dieser Seite.')
->schema([
Repeater::make('rules')->label('Regeln')->defaultItems(0)->addActionLabel('Regel hinzufügen')->live(debounce: 600)
->itemLabel(fn (array $state): string => $state['name'] ?? 'Neue Regel')
->schema([
TextInput::make('name')->label('Regelname')->required()->maxLength(120),
TextInput::make('priority')->label('Priorität (kleinere Zahl zuerst)')->integer()->minValue(0)->maxValue(10000)->default(100)->required(),
Toggle::make('enabled')->label('Regel aktiviert')->default(true),
Toggle::make('case_sensitive')->label('Groß-/Kleinschreibung beachten')->default(false),
Select::make('match')->label('Bedingungen verknüpfen')->options(['all' => 'UND – alle Bedingungen', 'any' => 'ODER – mindestens eine Bedingung'])->default('all')->required(),
Repeater::make('conditions')->label('Wenn')->minItems(1)->defaultItems(1)->addActionLabel('Bedingung hinzufügen')->columns(3)->schema([
Select::make('field')->label('Gefundenes Feld')->options(fn (): array => $this->fieldOptions())->required()->searchable(),
Select::make('operator')->label('Vergleich')->options(ICalRuleEngine::OPERATORS)->default('equals')->required()->live(),
TextInput::make('value')->label('Vergleichstext')->maxLength(2000)->visible(fn (Get $get): bool => ! in_array($get('operator'), ['exists', 'empty'], true))->live(debounce: 600),
])->columnSpanFull(),
Select::make('event_type')->label('Dann: Ereignistyp')->options(ICalRuleEngine::TYPES)->default('unknown')->required(),
Select::make('origin')->label('Ursprünglicher Buchungskanal')->options(fn (): array => ['unknown' => 'Unbekannt', 'current' => 'Dieser Portalkanal', ...$this->record->property->channels()->get()->mapWithKeys(fn (Channel $channel): array => ['channel:'.$channel->id => $channel->name])->all()])->default('unknown')->required(),
Select::make('representation')->label('Fachliche Einordnung')->options(ICalRuleEngine::REPRESENTATIONS)->default('unspecified')->required()->columnSpanFull()
->helperText('Eine allgemeine Sperre mit „Zusätzliche Sperre“ und unbekanntem Ursprung kann automatisch einer eindeutigen führenden Portalreservierung desselben Zeitraums zugeordnet werden. Eigene Buchungsmerkmale und persönliche Entscheidungen verhindern dies.'),
Repeater::make('extractions')->label('Informationen aus Text übernehmen')
->helperText('Ein Name im Original wird erst mit einer Textextraktion angezeigt. Für einen vollständigen Namen das passende Kalenderfeld und „Vollständiger Gastname“ wählen. Die Vorschau prüft das Ergebnis; es wird kein Gast automatisch angelegt.')
->defaultItems(0)->addActionLabel('Textextraktion hinzufügen')->columns(2)->schema([
Select::make('field')->label('Aus Kalenderfeld')->options(fn (): array => $this->fieldOptions())->required(),
Select::make('target')->label('Übernehmen als')->options(ICalRuleEngine::TARGETS)->required(),
Select::make('method')->label('Textauswahl')->options(ICalRuleEngine::EXTRACTIONS)->default('whole')->required()->live(),
TextInput::make('start')->label('Text nach / Anfangstext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['after', 'between'], true))->live(debounce: 600),
TextInput::make('end')->label('Text vor / Endtext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['before', 'between'], true))->live(debounce: 600),
])->columnSpanFull(),
])->columns(2),
]),
Section::make('3. Live-Vorschau')->description('Auswertung des gespeicherten echten Kalenderstands mit dem aktuellen Regelentwurf. Identische Termine sind lediglich Zuordnungskandidaten.')
->schema([View::make('filament.resources.channels.rule-preview')]),
Section::make('4. Informationen im Export an diesen Zielkanal')->description('Diese Exportkonfiguration wird beim Speichern wirksam. Die Vorschau zeigt den aktuell berechneten Inhalt; ein pausierter Export bleibt eingefroren. Nicht vorhandene Informationen werden ausgelassen.')
->schema([
Toggle::make('export_names')->label('Gastnamen ausdrücklich an diesen Zielkanal weitergeben')->default(false)->live()
->helperText('Gilt für neu erzeugte Exporte. Ein pausierter Export behält seinen gespeicherten Stand bis zur Reaktivierung.'),
Repeater::make('export_mapping')->label('iCal-Felder befüllen')->maxItems(3)->defaultItems(0)->live(debounce: 600)->addActionLabel('Exportfeld hinzufügen')->schema([
Select::make('field')->label('iCal-Zielfeld')->options(ICalExportFields::ICAL_FIELDS)->required(),
Select::make('items')->label('Enthaltene Informationen (in dieser Reihenfolge)')->options(ICalExportFields::FIELDS)->multiple()->required(),
TextInput::make('separator')->label('Trennzeichen')->default(' – ')->maxLength(30),
]),
View::make('filament.resources.channels.export-preview'),
]),
]);
}
public function preview(): array
{
$engine = app(ICalRuleEngine::class);
$rules = array_values($this->data['rules'] ?? []);
$counts = array_fill(0, count($rules), 0);
$unmatched = 0;
$rows = [];
$occupations = $this->record->property->blockedPeriods()->with('channel')->get();
$blocks = $occupations->where('is_representation', false);
foreach ($this->record->ical_analysis['events'] ?? [] as $event) {
$result = $engine->evaluate($this->record, $event['properties'], $rules);
if ($result['matched']) {
$counts[$result['rule_index']]++;
} else {
$unmatched++;
}
$candidates = $blocks->filter(fn (BlockedPeriod $block): bool => $block->starts_on->toDateString() === $event['starts_on'] && $block->ends_on->toDateString() === $event['ends_on'] && ! ($block->channel_id === $this->record->id && $block->external_uid === $event['uid']))->sortByDesc('leading_priority');
$occupation = $occupations->first(fn (BlockedPeriod $block): bool => $block->channel_id === $this->record->id && $block->external_uid === $event['uid']);
$rows[] = [...$event, 'summary' => $engine->values($event['properties'], 'SUMMARY')[0] ?? '(ohne SUMMARY)', 'result' => $result,
'occupation_url' => $occupation ? PortalOccupationResource::getUrl('view', ['record' => $occupation->id]) : null,
'candidates' => $candidates->map(fn (BlockedPeriod $block): array => [
'id' => $block->id, 'reason' => $block->channel?->name ?? $block->reason,
'priority' => $block->leading_priority, 'kind' => $block->occupationKind()->getLabel(),
'url' => in_array($block->source, ['channel', 'email'], true) ? PortalOccupationResource::getUrl('view', ['record' => $block->id]) : null,
])->all()];
}
return ['rows' => $rows, 'counts' => $counts, 'rules' => $rules, 'unmatched' => $unmatched];
}
public function savedRulesStatus(): string
{
$draft = $this->record->ical_rules ?? [];
$active = $this->record->ical_active_rules ?? [];
if ($draft !== $active) {
return 'Gespeicherte Regeln sind noch nicht aktiv. Entwurf: '.count($draft).' Regeln; aktiv: '.count($active).' Regeln.';
}
return $active === [] ? 'Es sind noch keine Erkennungsregeln aktiviert.' : 'Gespeicherter Entwurf und aktive Regeln stimmen überein. Aktiv: '.count($active).' Regeln.';
}
public function exportPreview(): array
{
$channel = clone $this->record;
$channel->forceFill(['ical_export_names' => (bool) ($this->data['export_names'] ?? false), 'ical_export_mapping' => array_values($this->data['export_mapping'] ?? [])]);
return app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($channel))['events'];
}
protected function handleRecordUpdate(Model $record, array $data): Model
{
DB::transaction(function () use ($record, $data): Model {
$channel = app(SaveChannelRules::class)->handle($record, array_values($data['rules'] ?? []));
return app(ConfigureChannelExport::class)->handle($channel, array_values($data['export_mapping'] ?? []), (bool) ($data['export_names'] ?? false));
});
return $record->refresh();
}
protected function getSavedNotificationTitle(): ?string
{
return 'Regelentwurf und Exportkonfiguration gespeichert';
}
protected function getHeaderActions(): array
{
return [
Action::make('saveDraft')->label('Entwurf speichern')->color('gray')
->action(function (): void {
$this->save(shouldRedirect: false);
}),
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
try {
$this->record = $analyze->handle($this->record);
Notification::make()->title($this->record->ical_analysis['count'].' Originalereignisse analysiert')->success()->send();
} catch (ChannelSyncException $exception) {
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
}
}),
Action::make('applyRules')->label('Speichern & anwenden')->requiresConfirmation()
->modalDescription('Der Regelentwurf wird aktiviert und der vorhandene Kalenderbestand neu klassifiziert. IDs, Termine und persönliche Zuordnungen bleiben erhalten. Bekannte Herkunft beeinflusst den kanalspezifischen Export. Bei Namensfreigabe werden die gewählten Exportinformationen ebenfalls gespeichert.')
->action(function (ApplyChannelRules $apply, Action $action): void {
try {
$counts = DB::transaction(function () use ($apply): array {
$this->record = $this->handleRecordUpdate($this->record, $this->form->getState());
return $apply->handle($this->record);
});
} catch (ValidationException $exception) {
$this->record->refresh();
$this->setErrorBag($exception->errors());
Notification::make()->title('Regeln wurden nicht angewendet')
->body(collect($exception->errors())->flatten()->unique()->implode(' '))
->danger()->persistent()->send();
$action->cancel();
}
$this->record->refresh();
$this->rememberData();
Notification::make()->title($counts['classified'].' Einträge neu klassifiziert')
->body($counts['missing_raw'].' Einträge ohne Originaldaten unverändert. Eindeutige allgemeine Belegtmeldungen werden als Kalenderspiegelung zugeordnet; widersprüchliche Einträge bleiben zur Klärung sichtbar.')
->success()->send();
}),
Action::make('configuration')->label('Kalenderverbindung')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
];
}
}