Files
fewo-stommer/app/Filament/Resources/Channels/Tables/ChannelsTable.php
T
Lars e5a083ce71
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m41s
Ausstehenden Erstimport von veraltetem Kalender unterscheiden
2026-10-27 17:58:07 +01:00

157 lines
12 KiB
PHP
Raw 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\Tables;
use App\Actions\ConfigureChannel;
use App\Actions\RotateChannelToken;
use App\Actions\SyncChannel;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class ChannelsTable
{
public static function configure(Table $table, ?Property $owner = null): Table
{
return $table
->recordTitleAttribute('name')
->defaultSort('id')
->contentGrid(['md' => 2, '2xl' => 3])
->emptyStateHeading('Noch keine Portalkanäle')
->emptyStateDescription('Legen Sie einen frei benannten Kanal für eine Ihrer Wohnungen an. Sein eigener Exportlink wird beim Speichern automatisch erzeugt.')
->description('Jeder Kanal hat einen eigenen Exportlink. Einstellungen ändern Sie über „Bearbeiten“, Abgleiche und Protokolle finden Sie im Zusatzmenü.')
->modifyQueryUsing(fn (Builder $query) => $query->withCount(['blockedPeriods as review_count' => fn ($blocks) => $blocks->where('needs_review', true)]))
->columns([
Stack::make([
TextColumn::make('name')->label('Portal')->weight('bold')->searchable()->sortable()->wrap()->extraAttributes(['style' => 'overflow-wrap:anywhere']),
TextColumn::make('property.name')->label('Wohnung')->visible($owner === null)->searchable()->color('gray')->wrap(),
TextColumn::make('channel_state')->label('Status')->badge()->wrap()
->state(fn (Channel $record): string => match (true) {
! $record->importsOccupations() => $record->status->getLabel(),
$record->last_error !== null => 'Importfehler',
$record->last_success_at === null => 'Erster Import ausstehend',
$record->isStale() => 'Import veraltet',
default => $record->status->getLabel(),
})
->color(fn (Channel $record): string => match (true) {
! $record->is_active => 'gray',
! $record->importsOccupations() => 'success',
$record->last_error !== null => 'danger',
$record->last_success_at === null => 'warning',
$record->isStale() => 'danger',
default => 'success',
})
->description(fn (Channel $record): ?string => $record->review_count || count($record->sync_warnings ?? []) ? 'Prüffälle: '.$record->review_count.' · Hinweise: '.count($record->sync_warnings ?? []) : null)
->tooltip(fn (Channel $record): ?string => $record->last_error),
TextColumn::make('directions')->label('Richtungen')->color('gray')->wrap()
->state(fn (Channel $record): string => ($record->importsOccupations() ? 'Import aktiv' : 'Import aus').' · '.($record->exportsOccupations() ? 'Export aktiv' : ($record->export_snapshot_at ? 'Export eingefroren' : 'Export aus'))),
TextColumn::make('last_sync')->label('Letzter Sync-Lauf')->wrap()
->state(fn (Channel $record): string => 'Letzter Sync: '.($record->last_synced_at?->format('d.m.Y H:i') ?? 'noch kein Lauf'))
->description(fn (Channel $record): ?string => $record->last_error !== null ? 'Letzter Lauf mit Fehler' : null),
TextColumn::make('last_export_request')->label('Letzter Kalenderabruf')->wrap()->color('gray')
->state(fn (Channel $record): string => 'Letzter Abruf: '.($record->last_export_requested_at?->format('d.m.Y H:i') ?? 'noch keiner'))
->tooltip('Empfangener Aufruf dieses Kanalfeeds. Client und tatsächliche Übernahme im Portal sind damit nicht bestätigt.'),
])->space(2),
])
->headerActions($owner ? [
CreateAction::make()->using(fn (array $data): Channel => app(ConfigureChannel::class)->handle($owner, $data))
->modalDescription('Name und Anbindung wählen. Der eigene Exportlink entsteht automatisch beim Speichern. Die externe Importadresse kann auch später ergänzt werden. Für den normalen kanalübergreifenden Betrieb den regulären Exportmodus bewusst wählen.')
->successNotificationTitle('Portal angelegt – eigener Exportlink automatisch erzeugt'),
] : [])
->recordActions([
Action::make('exportLink')->label('Exportlink')->icon(Heroicon::OutlinedLink)->button()
->modalDescription('Diese Adresse erlaubt den Kalenderabruf. Nur dem vorgesehenen Portal geben. Ein Abruf beweist keine tatsächliche Übernahme.')
->schema([
TextEntry::make('export_url')->label('Vertrauliche Kalenderadresse')->state(fn (Channel $record): string => $record->exportUrl())->copyable()->wrap()->extraAttributes(['style' => 'overflow-wrap:anywhere']),
TextEntry::make('token_transition')->label('Bisheriger Link bleibt gültig bis')->state(fn (Channel $record): string => $record->previous_export_token_expires_at?->format('d.m.Y H:i') ?? 'Keine Übergangsphase'),
])->modalSubmitAction(false)->modalCancelActionLabel('Schließen'),
...($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('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([
TextEntry::make('export_events')->label('Ereignisse im berechneten Feed')->state(fn (Channel $record): int => count(app(ICalParser::class)->parse(app(ICalFeed::class)->build($record)))),
TextEntry::make('held_events')->label('Importe in persönlicher Klärung oder zugeordnete Darstellungen')->state(fn (Channel $record): int => $record->property->blockedPeriods()->where(fn ($query) => $query->where('export_approved', false)->orWhere('is_representation', true))->count()),
]),
Action::make('exportRequests')->label('Kalenderabrufe')->icon(Heroicon::OutlinedClock)
->modalDescription('Die letzten 100 empfangenen Aufrufe dieses Kanalfeeds. Die vom Client gemeldete Kennung ist unbestätigt; auch Browser oder Tests können hier erscheinen. Ein Abruf beweist keine Übernahme im Portal.')
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')
->schema([
RepeatableEntry::make('requests')->label('Abrufhistorie')
->state(fn (Channel $record): array => $record->exportRequests()->get()->map(fn ($entry): array => [
'time' => $entry->requested_at->format('d.m.Y H:i:s'),
'result' => $entry->method.' · HTTP '.$entry->response_status.' · '.match ($entry->export_state) {
'live' => 'Aktueller Stand', 'frozen' => 'Eingefrorener Stand', default => 'Kein Stand verfügbar'
},
'client' => $entry->user_agent ?? 'Keine Clientkennung übermittelt',
])->all())
->schema([TextEntry::make('time')->label('Empfangen'), TextEntry::make('result')->label('Antwort'), TextEntry::make('client')->label('Clientangabe (unbestätigt)')->wrap()]),
]),
Action::make('rotateToken')->label('Exporttoken wechseln')->requiresConfirmation()
->modalDescription('Eine neue Adresse entsteht. Die bisherige bleibt während der Übergangsphase gültig. Die neue Adresse selbst im Portal eintragen; danach Ablauf beachten.')
->schema([TextInput::make('grace_hours')->label('Übergangsphase in Stunden')->integer()->minValue(24)->maxValue(720)->default(168)->required()])
->action(function (Channel $record, array $data, RotateChannelToken $rotate): void {
$rotate->handle($record, (int) $data['grace_hours']);
Notification::make()->title('Token gewechselt – neuen Exportlink im Portal eintragen')->success()->send();
}),
Action::make('sync')
->label('Jetzt abgleichen')
->icon(Heroicon::OutlinedArrowPath)
->visible(fn (Channel $record): bool => $record->importsOccupations())
->action(function (Channel $record, SyncChannel $syncChannel): void {
$log = $syncChannel->handle($record);
$log->successful
? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send()
: Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send();
}),
Action::make('logs')
->label('Protokoll')
->icon(Heroicon::OutlinedListBullet)
->color('gray')
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->schema([
RepeatableEntry::make('recentLogs')
->hiddenLabel()
->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [
'time' => $log->created_at->format('d.m. H:i'),
'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message,
'conflicts' => $log->conflicts ?: '',
'warnings' => implode(' ', $log->warnings ?? []),
])->all())
->table([
TableColumn::make('Zeit'),
TableColumn::make('Ergebnis'),
TableColumn::make('Konflikte'),
TableColumn::make('Hinweise'),
])
->schema([
TextEntry::make('time'),
TextEntry::make('result'),
TextEntry::make('conflicts'),
TextEntry::make('warnings'),
]),
]),
])->label('Weitere Aktionen')->icon(Heroicon::OutlinedEllipsisVertical),
]);
}
}