166 lines
11 KiB
PHP
166 lines
11 KiB
PHP
<?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\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\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;
|
||
|
||
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([
|
||
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. Speichern legt einen Entwurf ab; erst „Auf Bestand anwenden“ aktiviert die Regeln für weitere Importe.')
|
||
->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(),
|
||
Repeater::make('extractions')->label('Informationen aus Text übernehmen')->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(),
|
||
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 = [];
|
||
$blocks = $this->record->property->blockedPeriods()->occupying()->get();
|
||
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');
|
||
$rows[] = [...$event, 'summary' => $engine->values($event['properties'], 'SUMMARY')[0] ?? '(ohne SUMMARY)', 'result' => $result, 'candidates' => $candidates->map(fn (BlockedPeriod $block): array => ['id' => $block->id, 'reason' => $block->reason, 'priority' => $block->leading_priority])->all()];
|
||
}
|
||
|
||
return ['rows' => $rows, 'counts' => $counts, 'rules' => $rules, 'unmatched' => $unmatched];
|
||
}
|
||
|
||
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('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('Auf Bestand 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): void {
|
||
$counts = DB::transaction(function () use ($apply): array {
|
||
$this->record = $this->handleRecordUpdate($this->record, $this->form->getState());
|
||
|
||
return $apply->handle($this->record);
|
||
});
|
||
$this->record->refresh();
|
||
Notification::make()->title($counts['classified'].' Einträge neu klassifiziert')->body($counts['missing_raw'].' Einträge ohne Originaldaten unverändert.')->success()->send();
|
||
}),
|
||
Action::make('configuration')->label('Kalenderverbindung')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
|
||
];
|
||
}
|
||
}
|