Visuelle iCal-Regelengine mit Originaldaten und individuellen Exportfeldern integrieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m37s

This commit is contained in:
Lars committed 2026-10-27 19:00:25 +01:00
1 parent c4ebccbbea
commit e9db98701b
30 files changed
+1269 -15

No files matched your search

@@ -3,6 +3,7 @@
namespace App\Filament\Resources\Channels;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\Channels\Pages\ChannelRules;
use App\Filament\Resources\Channels\Pages\CreateChannel;
use App\Filament\Resources\Channels\Pages\EditChannel;
use App\Filament\Resources\Channels\Pages\ListChannels;
@@ -58,6 +59,7 @@ public static function getPages(): array
'index' => ListChannels::route('/'),
'create' => CreateChannel::route('/create'),
'edit' => EditChannel::route('/{record}/edit'),
'rules' => ChannelRules::route('/{record}/rules'),
];
}
}
@@ -0,0 +1,165 @@
<?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])),
];
}
}
@@ -2,8 +2,12 @@
namespace App\Filament\Resources\Channels\Pages;
use App\Actions\AnalyzeChannelCalendar;
use App\Actions\ConfigureChannel;
use App\Channels\ChannelSyncException;
use App\Filament\Resources\Channels\ChannelResource;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
@@ -11,6 +15,21 @@ class EditChannel extends EditRecord
{
protected static string $resource = ChannelResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record])),
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
try {
$analyze->handle($this->record);
$this->redirect(ChannelResource::getUrl('rules', ['record' => $this->record]));
} catch (ChannelSyncException $exception) {
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
}
}),
];
}
protected function mutateFormDataBeforeFill(array $data): array
{
return [...$data, 'settings' => $this->record->settings];
@@ -2,11 +2,14 @@
namespace App\Filament\Resources\Channels\Tables;
use App\Actions\AnalyzeChannelCalendar;
use App\Actions\ConfigureChannel;
use App\Actions\RotateChannelToken;
use App\Actions\SyncChannel;
use App\Channels\ChannelSyncException;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
@@ -84,6 +87,15 @@ public static function configure(Table $table, ?Property $owner = null): Table
...($owner ? [EditAction::make()->mutateRecordDataUsing(fn (array $data, Channel $record): array => [...$data, 'settings' => $record->settings])
->using(fn (Channel $record, array $data): Channel => app(ConfigureChannel::class)->handle($owner, $data, $record))] : [EditAction::make()]),
ActionGroup::make([
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (Channel $record): string => ChannelResource::getUrl('rules', ['record' => $record])),
Action::make('analyze')->label('Kalender analysieren')->action(function (Channel $record, AnalyzeChannelCalendar $analyze, $livewire): void {
try {
$analyze->handle($record);
$livewire->redirect(ChannelResource::getUrl('rules', ['record' => $record]));
} catch (ChannelSyncException $exception) {
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
}
}),
Action::make('coverage')->label('Exportumfang prüfen')->modalSubmitAction(false)->modalCancelActionLabel('Schließen')
->modalDescription('Aktuell berechneter Umfang der nächsten aktiven Ausgabe. Bei pausiertem Export bleibt der gespeicherte Stand maßgeblich.')
->schema([