From add2367869cd942aa65e2419672faa21e0dcf873 Mon Sep 17 00:00:00 2001 From: Lars Date: Thu, 29 Oct 2026 17:01:30 +0100 Subject: [PATCH] Eindeutige iCal-Kalenderspiegelungen automatisch und widerrufbar zuordnen --- app/Actions/ApplyChannelRules.php | 1 + app/Actions/ClassifyPortalOccupation.php | 3 + .../ReconcileChannelRepresentations.php | 113 ++++++ app/Actions/ResolveChannelOccupation.php | 5 +- app/Actions/SyncChannel.php | 33 +- app/Availability/OccupancyOverview.php | 7 +- .../Resources/Channels/Pages/ChannelRules.php | 5 +- .../PortalOccupationResource.php | 9 +- app/Models/BlockedPeriod.php | 12 +- ...atic_representation_to_blocked_periods.php | 32 ++ docs/STATUS.md | 2 + docs/architecture/ical-kanalkonfiguration.md | 9 + docs/architecture/ical-regelengine.md | 6 +- .../pages/occupancy-calendar.blade.php | 8 +- .../resources/channels/rule-preview.blade.php | 4 +- .../AutomaticChannelRepresentationTest.php | 322 ++++++++++++++++++ 16 files changed, 540 insertions(+), 31 deletions(-) create mode 100644 app/Actions/ReconcileChannelRepresentations.php create mode 100644 database/migrations/2026_10_29_164621_add_automatic_representation_to_blocked_periods.php create mode 100644 tests/Feature/AutomaticChannelRepresentationTest.php diff --git a/app/Actions/ApplyChannelRules.php b/app/Actions/ApplyChannelRules.php index d12cea2..050fd14 100644 --- a/app/Actions/ApplyChannelRules.php +++ b/app/Actions/ApplyChannelRules.php @@ -68,6 +68,7 @@ public function handle(Channel $channel): array $this->store($block, [...$attributes, 'ical_properties' => $properties, 'ical_raw' => $event['raw'] ?? $block->ical_raw]); $counts['classified']++; } + app(ReconcileChannelRepresentations::class)->handle($channel->property); return $counts; }); diff --git a/app/Actions/ClassifyPortalOccupation.php b/app/Actions/ClassifyPortalOccupation.php index fad641c..116b9e3 100644 --- a/app/Actions/ClassifyPortalOccupation.php +++ b/app/Actions/ClassifyPortalOccupation.php @@ -6,6 +6,7 @@ use App\Enums\OccupationKind; use App\Models\BlockedPeriod; use App\Models\Channel; +use App\Models\Property; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Validator; @@ -30,6 +31,7 @@ public function handle(BlockedPeriod $occupation, OccupationKind $kind, ?int $or throw ValidationException::withMessages(['origin_channel_id' => 'Privat und ein externer Buchungskanal können nicht gleichzeitig gewählt werden.']); } DB::transaction(function () use ($occupation, $kind, $originId, $details): void { + Property::query()->whereKey($occupation->property_id)->lockForUpdate()->firstOrFail(); $record = BlockedPeriod::query()->whereKey($occupation->id)->lockForUpdate()->firstOrFail(); if (! in_array($record->source, ['channel', 'email'], true) || $record->is_representation) { throw ValidationException::withMessages(['occupation_kind' => 'Nur eigenständige Portalereignisse können hier eingeordnet werden.']); @@ -44,6 +46,7 @@ public function handle(BlockedPeriod $occupation, OccupationKind $kind, ?int $or 'block_purpose' => $kind === OccupationKind::Block ? (array_key_exists('block_purpose', $details) ? $details['block_purpose'] : $record->block_purpose) : null, 'block_note' => $kind === OccupationKind::Block ? (array_key_exists('block_note', $details) ? $details['block_note'] : $record->block_note) : null, ])->save(); + app(ReconcileChannelRepresentations::class)->handle($record->property); }); } } diff --git a/app/Actions/ReconcileChannelRepresentations.php b/app/Actions/ReconcileChannelRepresentations.php new file mode 100644 index 0000000..b342d87 --- /dev/null +++ b/app/Actions/ReconcileChannelRepresentations.php @@ -0,0 +1,113 @@ +whereKey($property->id)->lockForUpdate()->firstOrFail(); + $blocks = $property->blockedPeriods()->with('channel')->withCount('channelRepresentations')->orderBy('id')->lockForUpdate()->get()->keyBy('id'); + $independent = $blocks->filter(fn (BlockedPeriod $block): bool => ! $block->is_representation || $block->representation_automatic); + $mirrors = $independent->filter(fn (BlockedPeriod $block): bool => $this->isMirror($block)); + $leaders = $independent->filter(fn (BlockedPeriod $block): bool => $this->isLeader($block)); + $bookings = $property->bookings()->occupying()->get(['id', 'arrival', 'departure']); + $targets = []; + foreach ($mirrors as $mirror) { + $matches = $leaders->filter(fn (BlockedPeriod $leader): bool => $leader->channel_id !== $mirror->channel_id && $this->sameDates($leader, $mirror)); + if ($matches->count() !== 1) { + continue; + } + $leader = $matches->sole(); + $contradiction = $independent->contains(fn (BlockedPeriod $other): bool => $other->id !== $mirror->id && $other->id !== $leader->id + && $other->starts_on->lessThan($leader->ends_on) && $other->ends_on->greaterThan($leader->starts_on) + && ! ($mirrors->has($other->id) && $this->sameDates($other, $leader))); + if ($contradiction || $bookings->contains(fn ($booking): bool => $booking->arrival->lessThan($leader->ends_on) && $booking->departure->greaterThan($leader->starts_on))) { + continue; + } + $targets[$mirror->id] = $leader; + } + + $counts = ['linked' => 0, 'unlinked' => 0]; + foreach ($blocks as $block) { + $leader = $targets[$block->id] ?? null; + if ($leader === null) { + if ($block->representation_automatic) { + $block->forceFill(['representation_automatic' => false, 'is_representation' => false, 'canonical_block_id' => null, 'export_approved' => false, + 'needs_review' => true, 'review_note' => self::RECHECK_NOTE])->save(); + $counts['unlinked']++; + } + + continue; + } + $newLink = ! $block->is_representation || $block->canonical_block_id !== $leader->id; + $block->forceFill(['representation_automatic' => true, 'is_representation' => true, 'canonical_block_id' => $leader->id, + 'needs_review' => false, 'review_note' => self::LINK_NOTE]); + if ($block->isDirty()) { + $block->save(); + } + $counts['linked'] += (int) $newLink; + if ($leader->reviewed_at === null) { + if ($leader->channel?->echo_behavior !== ChannelEchoBehavior::Reexports) { + $leader->forceFill(['export_approved' => true]); + } + if ($leader->review_note === self::OVERLAP_NOTE) { + $leader->forceFill(['needs_review' => false, 'review_note' => null]); + } + if ($leader->isDirty()) { + $leader->save(); + } + } + } + + return $counts; + }); + } + + private function isMirror(BlockedPeriod $block): bool + { + $interpretation = $block->ical_interpretation ?? []; + + return $block->source === 'channel' && $block->channel_id !== null && $block->missing_imports === 0 + && $block->occupation_kind === null && $block->guest_id === null && ! $block->is_private + && $block->block_purpose === null && blank($block->block_note) && $block->reviewed_at === null + && $block->origin_channel_id === null && $block->linked_booking_id === null && $block->channel_representations_count === 0 + && $block->ical_event_type === 'block' && ($interpretation['matched'] ?? false) + && ($interpretation['representation'] ?? null) === 'additional_block' && ($interpretation['origin_channel_id'] ?? null) === null + && blank($interpretation['fields']['booking_reference'] ?? null) && blank($interpretation['fields']['guest_full_name'] ?? null) + && blank($interpretation['fields']['guest_first_name'] ?? null) && $this->hasCompatibleReview($block); + } + + private function isLeader(BlockedPeriod $block): bool + { + return $block->source === 'channel' && $block->channel_id !== null && ! $block->is_representation + && $block->occupationKind() === OccupationKind::Reservation && $block->ical_event_type === 'portal_reservation' + && $block->missing_imports === 0 && ! $block->is_private && $block->leading_priority > 0 + && $block->origin_channel_id === $block->channel_id && ($block->ical_interpretation['matched'] ?? false) + && ($block->ical_interpretation['representation'] ?? null) === 'leading_candidate' && $this->hasCompatibleReview($block); + } + + private function hasCompatibleReview(BlockedPeriod $block): bool + { + return ! $block->needs_review || in_array($block->review_note, [self::OVERLAP_NOTE, self::LINK_NOTE, self::RECHECK_NOTE], true); + } + + private function sameDates(BlockedPeriod $first, BlockedPeriod $second): bool + { + return $first->starts_on->equalTo($second->starts_on) && $first->ends_on->equalTo($second->ends_on); + } +} diff --git a/app/Actions/ResolveChannelOccupation.php b/app/Actions/ResolveChannelOccupation.php index 5ecd1cb..5650d2f 100644 --- a/app/Actions/ResolveChannelOccupation.php +++ b/app/Actions/ResolveChannelOccupation.php @@ -5,6 +5,7 @@ use App\Models\BlockedPeriod; use App\Models\Booking; use App\Models\Channel; +use App\Models\Property; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; @@ -13,6 +14,7 @@ class ResolveChannelOccupation public function handle(BlockedPeriod $block, string $resolution, ?int $targetId = null, ?int $originId = null): BlockedPeriod { return DB::transaction(function () use ($block, $resolution, $targetId, $originId): BlockedPeriod { + Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail(); $block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail(); if (! in_array($block->source, ['channel', 'email'], true)) { throw ValidationException::withMessages(['resolution' => 'Nur importierte Portalereignisse benötigen diese Zuordnung.']); @@ -42,7 +44,8 @@ public function handle(BlockedPeriod $block, string $resolution, ?int $targetId 'linked_booking_id' => $resolution === 'booking' ? $target->id : null, 'review_note' => 'Persönlich zugeordnet; nur die führende Belegung steuert Verfügbarkeit und Export.']; } - $block->update($attributes); + $block->forceFill(['representation_automatic' => false])->fill($attributes)->save(); + app(ReconcileChannelRepresentations::class)->handle($block->property); return $block->refresh(); }); diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php index 2787c3c..e78effe 100644 --- a/app/Actions/SyncChannel.php +++ b/app/Actions/SyncChannel.php @@ -95,21 +95,6 @@ public function handle(Channel $channel): ChannelSyncLog app(ApplyChannelRules::class)->store($block, [...$interpretation, 'ical_properties' => $period->properties, 'ical_raw' => $period->raw]); } $existing->put($period->uid, $block); - $overlap = $channel->blockedPeriods()->occupying()->overlapping($block->starts_on, $block->ends_on)->whereKeyNot($block->id)->exists(); - $foundConflicts = $block->is_representation ? [] : $this->conflictDetector->conflictsFor($block); - $linked = $block->canonicalBlock ?? $block->linkedBooking; - $linkedStart = $linked instanceof Booking ? $linked->arrival : $linked?->starts_on; - $linkedEnd = $linked instanceof Booking ? $linked->departure : $linked?->ends_on; - $representationChanged = $block->is_representation && ($linked === null || ! $block->starts_on->equalTo($linkedStart) || ! $block->ends_on->equalTo($linkedEnd)); - if ($representationChanged || (! $block->is_representation && $block->reviewed_at === null && ($overlap || $emails->isNotEmpty() || $foundConflicts !== [] || ! $block->export_approved))) { - $note = 'Mehrere Belegungsrepräsentationen oder Überschneidungen prüfen; keine automatische Zusammenführung anhand von Terminen.'; - $block->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly(); - foreach ($emails as $mailBlock) { - $mailBlock->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly(); - } - $warnings[] = $note; - } - array_push($conflicts, ...$foundConflicts); } $missing = $rows->filter(fn (BlockedPeriod $block): bool => ! $block->trashed() && ! isset($seen[$block->external_uid]) && $block->ends_on->greaterThan($today)); if ($missing->count() > config('channels.max_automatic_removals', 5)) { @@ -128,6 +113,24 @@ public function handle(Channel $channel): ChannelSyncLog } } } + app(ReconcileChannelRepresentations::class)->handle($channel->property); + foreach ($channel->blockedPeriods()->with(['canonicalBlock', 'linkedBooking'])->where('source', 'channel')->whereIn('external_uid', array_keys($seen))->get() as $block) { + $overlap = $channel->blockedPeriods()->occupying()->overlapping($block->starts_on, $block->ends_on)->whereKeyNot($block->id)->exists(); + $foundConflicts = $block->is_representation ? [] : $this->conflictDetector->conflictsFor($block); + $linked = $block->canonicalBlock ?? $block->linkedBooking; + $linkedStart = $linked instanceof Booking ? $linked->arrival : $linked?->starts_on; + $linkedEnd = $linked instanceof Booking ? $linked->departure : $linked?->ends_on; + $representationChanged = $block->is_representation && ($linked === null || ! $block->starts_on->equalTo($linkedStart) || ! $block->ends_on->equalTo($linkedEnd)); + if ($representationChanged || (! $block->is_representation && $block->reviewed_at === null && ($overlap || $emails->isNotEmpty() || $foundConflicts !== [] || ! $block->export_approved))) { + $note = ReconcileChannelRepresentations::OVERLAP_NOTE; + $block->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly(); + foreach ($emails as $mailBlock) { + $mailBlock->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly(); + } + $warnings[] = $note; + } + array_push($conflicts, ...$foundConflicts); + } $warnings = array_values(array_unique($warnings)); $locked->forceFill(['last_synced_at' => now(), 'last_success_at' => now(), 'last_error' => null, 'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save(); diff --git a/app/Availability/OccupancyOverview.php b/app/Availability/OccupancyOverview.php index e113f9f..1e79cfe 100644 --- a/app/Availability/OccupancyOverview.php +++ b/app/Availability/OccupancyOverview.php @@ -25,7 +25,8 @@ class OccupancyOverview public function records(?int $propertyId = null, ?int $guestId = null, bool $includeBlocks = false, ?CarbonImmutable $from = null, ?CarbonImmutable $until = null): Collection { Gate::authorize('viewAny', Booking::class); - $bookings = Booking::query()->with(['guest', 'property', 'originChannel', 'importChannel'])->withCount('channelRepresentations') + $representations = ['channelRepresentations' => fn ($query) => $query->select(['id', 'channel_id', 'canonical_block_id', 'linked_booking_id'])->with('channel:id,name')]; + $bookings = Booking::query()->with(['guest', 'property', 'originChannel', 'importChannel'])->with($representations)->withCount('channelRepresentations') ->when($propertyId, fn ($query) => $query->where('property_id', $propertyId)) ->when($guestId, fn ($query) => $query->where('guest_id', $guestId)) ->when($from, fn ($query) => $query->whereDate('departure', '>=', $from)) @@ -46,11 +47,12 @@ public function records(?int $propertyId = null, ?int $guestId = null, bool $inc 'occupies' => in_array($booking->status, BookingStatus::occupying(), true) || $booking->isHoldActive(), 'needs_review' => false, 'review_note' => null, 'reason' => null, 'archived' => false, 'representations' => $booking->channel_representations_count, + 'mirrored_channels' => $booking->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(), 'url' => BookingResource::getUrl('view', ['record' => $booking->id]), 'guest_url' => $booking->guest_id ? GuestResource::getUrl('edit', ['record' => $booking->guest_id]) : null, ]); } - $blocks = BlockedPeriod::query()->select(['id', 'tenant_id', 'property_id', 'guest_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'occupation_kind', 'block_purpose', 'block_note', 'is_private', 'ical_event_type', 'ical_interpretation', 'is_representation', 'needs_review', 'review_note', 'deleted_at'])->withTrashed()->occupying()->with(['guest', 'property', 'channel', 'originChannel'])->withCount('channelRepresentations') + $blocks = BlockedPeriod::query()->select(['id', 'tenant_id', 'property_id', 'guest_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'occupation_kind', 'block_purpose', 'block_note', 'is_private', 'ical_event_type', 'ical_interpretation', 'is_representation', 'needs_review', 'review_note', 'deleted_at'])->withTrashed()->occupying()->with(['guest', 'property', 'channel', 'originChannel'])->with($representations)->withCount('channelRepresentations') ->when(! $includeBlocks, fn ($query) => $query->reservations()) ->when($propertyId, fn ($query) => $query->where('property_id', $propertyId)) ->when($guestId, fn ($query) => $query->where('guest_id', $guestId)->reservations()) @@ -73,6 +75,7 @@ public function records(?int $propertyId = null, ?int $guestId = null, bool $inc 'status_key' => $block->trashed() ? 'archived' : 'imported', 'color' => $block->needs_review ? 'warning' : $kind->getColor(), 'occupies' => ! $block->trashed(), 'needs_review' => $block->needs_review, 'review_note' => $block->review_note, 'reason' => $block->blockDescription(), 'archived' => $block->trashed(), 'representations' => $block->channel_representations_count, + 'mirrored_channels' => $block->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(), 'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]), 'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null, ]); diff --git a/app/Filament/Resources/Channels/Pages/ChannelRules.php b/app/Filament/Resources/Channels/Pages/ChannelRules.php index d06854c..c68cb51 100644 --- a/app/Filament/Resources/Channels/Pages/ChannelRules.php +++ b/app/Filament/Resources/Channels/Pages/ChannelRules.php @@ -73,7 +73,8 @@ public function form(Schema $schema): Schema ])->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(), + 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([ @@ -202,7 +203,7 @@ protected function getHeaderActions(): array $this->record->refresh(); $this->rememberData(); Notification::make()->title($counts['classified'].' Einträge neu klassifiziert') - ->body($counts['missing_raw'].' Einträge ohne Originaldaten unverändert. Zeitgleiche Einträge anderer Kalender bleiben bis zur ausdrücklichen Zuordnung getrennt.') + ->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])), diff --git a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php index 233b483..9f67535 100644 --- a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php +++ b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php @@ -71,7 +71,7 @@ public static function table(Table $table): Table ->defaultSort('starts_on')->columns([ TextColumn::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y')->sortable(), TextColumn::make('ends_on')->label('Abreise / Ende')->date('d.m.Y'), - TextColumn::make('business_kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->occupationKind()->getLabel())->badge(), + TextColumn::make('business_kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Kalenderspiegelung' : $record->occupationKind()->getLabel())->badge(), TextColumn::make('guest_name')->label('Gast / Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->guestName())->placeholder('Zuordnung offen') ->description(fn (BlockedPeriod $record): string => $record->guest_id ? 'Gast zugeordnet' : 'Keine bestätigte Gastzuordnung'), TextColumn::make('channel.name')->label('Importkanal'), @@ -120,7 +120,7 @@ public static function infolist(Schema $schema): Schema TextEntry::make('property.name')->label('Wohnung'), TextEntry::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y'), TextEntry::make('ends_on')->label('Abreise / erster freier Tag')->date('d.m.Y'), - TextEntry::make('kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->occupationKind()->getLabel()), + TextEntry::make('kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Kalenderspiegelung' : $record->occupationKind()->getLabel()), TextEntry::make('booking_channel')->label('Buchungskanal')->state(fn (BlockedPeriod $record): string => $record->bookingChannelLabel()), TextEntry::make('block_description')->label('Zweck / Grund der Sperrzeit')->state(fn (BlockedPeriod $record): ?string => $record->blockDescription()) ->visible(fn (BlockedPeriod $record): bool => $record->occupationKind() === OccupationKind::Block)->placeholder('Noch nicht angegeben'), @@ -131,7 +131,10 @@ public static function infolist(Schema $schema): Schema TextEntry::make('assignment')->label('Gastzuordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Wird an der führenden Belegung gepflegt' : ($record->guest_id ? 'Persönlich zugeordnet' : 'Noch offen; Namensfragment allein ist kein Identitätsnachweis')), TextEntry::make('calendar_state')->label('Kalenderstatus')->state(fn (BlockedPeriod $record): string => $record->trashed() ? 'Nicht mehr im Feed – keine Aussage über den Stornogrund' : ($record->is_representation ? 'Weitere Darstellung einer führenden Belegung' : 'Belegt den Zeitraum')), TextEntry::make('leading_record')->label('Führende Belegung')->state(fn (BlockedPeriod $record): string => $record->linkedBooking ? 'Buchung '.$record->linkedBooking->reference : ($record->canonical_block_id ? 'Kalenderbelegung #'.$record->canonical_block_id : 'Dieser Eintrag')) - ->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : null), + ->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : ($record->canonical_block_id ? static::getUrl('view', ['record' => $record->canonical_block_id]) : null)), + TextEntry::make('representation_assignment')->label('Zuordnung der Kalenderdarstellung') + ->state(fn (BlockedPeriod $record): string => $record->representation_automatic ? 'Automatisch; wird bei jedem Abgleich erneut geprüft' : 'Persönlich bestätigt') + ->visible(fn (BlockedPeriod $record): bool => $record->is_representation), TextEntry::make('review_note')->label('Prüfhinweis')->placeholder('Kein zusätzlicher Prüfhinweis')->columnSpanFull(), ]), Section::make('Kalenderquelle')->schema([ diff --git a/app/Models/BlockedPeriod.php b/app/Models/BlockedPeriod.php index 66b7030..5ea1e5a 100644 --- a/app/Models/BlockedPeriod.php +++ b/app/Models/BlockedPeriod.php @@ -32,7 +32,7 @@ class BlockedPeriod extends Model /** @use HasFactory */ use BelongsToTenant, HasChannelProvenance, HasFactory, SoftDeletes; - protected $attributes = ['is_representation' => false, 'export_approved' => true]; + protected $attributes = ['is_representation' => false, 'representation_automatic' => false, 'export_approved' => true]; /** * Get the attributes that should be cast. @@ -50,6 +50,7 @@ protected function casts(): array 'needs_review' => 'boolean', 'missing_imports' => 'integer', 'is_representation' => 'boolean', + 'representation_automatic' => 'boolean', 'export_approved' => 'boolean', 'reviewed_at' => 'immutable_datetime', 'ical_properties' => 'encrypted:array', @@ -119,6 +120,10 @@ public function guestName(): ?string public function bookingChannelLabel(): string { + if ($this->is_representation) { + return $this->canonicalBlock?->bookingChannelLabel() ?? $this->linkedBooking?->bookingChannelLabel() ?? 'Führende Belegung nicht verfügbar'; + } + return $this->is_private ? 'Privat' : ($this->originChannel?->name ?? $this->channel?->name ?? ($this->source === 'manual' ? 'Eigene Sperre' : 'Ursprung unbekannt')); } @@ -170,8 +175,9 @@ protected function unclear(Builder $query): Builder { return $query->whereIn('source', ['channel', 'email'])->where(fn (Builder $query) => $query ->where('needs_review', true) - ->orWhere('occupation_kind', OccupationKind::Unknown) - ->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where(fn (Builder $query) => $query->whereNull('ical_event_type')->orWhere('ical_event_type', '!=', 'portal_reservation')))); + ->orWhere(fn (Builder $query) => $query->where('is_representation', false)->where(fn (Builder $query) => $query + ->where('occupation_kind', OccupationKind::Unknown) + ->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where(fn (Builder $query) => $query->whereNull('ical_event_type')->orWhere('ical_event_type', '!=', 'portal_reservation')))))); } /** @param Builder $query diff --git a/database/migrations/2026_10_29_164621_add_automatic_representation_to_blocked_periods.php b/database/migrations/2026_10_29_164621_add_automatic_representation_to_blocked_periods.php new file mode 100644 index 0000000..86ca2d9 --- /dev/null +++ b/database/migrations/2026_10_29_164621_add_automatic_representation_to_blocked_periods.php @@ -0,0 +1,32 @@ +boolean('representation_automatic')->default(false); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + if (DB::table('blocked_periods')->where('representation_automatic', true)->exists()) { + throw new RuntimeException('Automatische Kalenderspiegelungen zuerst auflösen; ihre Kennzeichnung darf nicht verloren gehen.'); + } + Schema::table('blocked_periods', function (Blueprint $table) { + $table->dropColumn('representation_automatic'); + }); + } +}; diff --git a/docs/STATUS.md b/docs/STATUS.md index f1f94e5..923abf7 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,7 @@ # Projektstand +**Automatische iCal-Kalenderspiegelungen (29.10.2026, lokal geprüft):** Eindeutig per aktiver Regel erkannte zusätzliche allgemeine Belegtmeldungen ohne eigene Buchungsmerkmale werden einer einzigen führenden Portalreservierung eines anderen Kanals mit exakt gleichen Terminen zugeordnet. Keine Terminheuristik bei unbekannten Ereignissen, mehreren Quellbuchungen, widersprüchlichen Überschneidungen oder persönlichen Entscheidungen. Import und Regelanwendung prüfen die gesamte Wohnung; Kalender zeigt eine Belegung mit „Auch bei … gespiegelt“, geklärte Spiegelungen verschwinden aus Klärungsliste und Zähler. Neue Kennzeichnung `representation_automatic` trennt persönliche und automatische Zuordnungen. Nur automatische Verknüpfungen werden bei Änderungen, fehlender Quelle oder neuer Mehrdeutigkeit gelöst; weiterhin gemeldete Nächte bleiben intern belegt und vom Rückexport ausgeschlossen. Persönliche Entscheidungen bleiben erhalten. Konfliktprüfung erfolgt nach der Zuordnung, vermeidet falsche Doppelbuchungsmeldungen und erhält tatsächliche Konflikte. **198 relevante Tests / 1188 Assertions und Pint erfolgreich**, davon 24 neue Tests / 136 Assertions mit beiden Importreihenfolgen, Regelanwendung auf Bestand, Änderungen, fehlender Quelle/Wiederkehr, Buchungsmerkmalen, Mehrdeutigkeit und Mandantentrennung. Additive Migration, kein Bestandsumbau in der Migration. [Regeln und Lebenszyklus](architecture/ical-regelengine.md#führende-repräsentation-und-zuordnung). + **Abbruch beim Anwenden von iCal-Regeln korrigiert (29.10.2026, bereitgestellt):** Destination Solution rein lesend geprüft: Entwurf vorhanden, aktive Regeln leer; nachfolgender Import unterscheidet sich von der Vorschau nur in DTSTAMP, bei gleichen Terminen und gleichem Regelergebnis. Bisher blockierte die Prüfung auf veraltete Originaldaten auch diese reine Zeitstempeländerung; die Validierungsnachricht blieb hinter dem Bestätigungsdialog unsichtbar. Reine DTSTAMP-/LAST-MODIFIED-Änderungen werden jetzt nur bei vollständig gleichem Regelergebnis toleriert, neueste importierte Originale bleiben erhalten. Fachliche Änderungen oder ein durch Zeitstempel geändertes Regelergebnis verlangen weiterhin eine neue Vorschau. Validierungsabbrüche schließen den Dialog, zeigen eine dauerhafte Meldung und behalten die Formulareingaben; gespeicherter Regelstand wird nach dem Transaktionsrückbau neu geladen. Erfolg schließt die Bestätigung und aktualisiert den aktiven Regelstand. **174 relevante Tests / 1052 Assertions und Pint erfolgreich**, darin 41 Regelengine-Tests / 289 Assertions und sieben zusätzliche Fälle mit tatsächlichem Öffnen und Bestätigen des Dialogs, Aktualisierungsrennen, fehlerhafter Extraktion und Formularvalidierung. Keine echten Kanalregeln aktiviert, keine Kalenderdaten zusammengeführt; identische Tage allein bleiben kein Identitätsnachweis. [Befund und Bedienung](architecture/ical-regelengine.md#vorschau-entwurf-und-aktivierung). Mit `a0497fc` über den vorhandenen PipelineManager bereitgestellt; Release `20261029152758-a0497fcc`, Serverrevision, private Sicherung (31.620.399 Bytes) und HTTP 200 für Gesundheit/Anmeldung bestätigt. Neue Regelseite unangemeldet zur Anmeldung umgeleitet. Die ausgelieferte Zeitstempelprüfung zusätzlich rein lesend gegen den echten Destination-Bestand ausgeführt: akzeptiert; Entwurf erkennt Portalreservierung/Führungskandidat. Aktive Regeln weiterhin leer, keine persönliche Anwendung vorweggenommen. Keine neue Migration oder zusätzliche visuelle Browserabnahme. Gitea-Status-API HTTP 401; Auslesen gespeicherter Git-Zugangsdaten dafür durch automatische Freigabeprüfung abgelehnt und nicht ausgeführt. Deployment über vorhandene SSH-Zugänge und aktive Serverrevision bestätigt, kein ungeprüfter API-Erfolgsstatus behauptet. **iCal-Kompatibilität für fehlenden DTSTAMP (29.10.2026, bereitgestellt):** Ferienundwohnen-Feed liefert elf Ereignisse ohne DTSTAMP, aber mit gültigem ereignisbezogenem UTC-LAST-MODIFIED. Ablehnung mit neuem Test reproduziert; Parser verwendet LAST-MODIFIED nur bei vollständig fehlendem DTSTAMP als Ersatzprüfung. Leere/ungültige vorhandene DTSTAMP, unbrauchbare oder doppelte Zeitstempel und beschädigte Feeds bleiben abgewiesen. Keine künstlichen Originalfelder, keine geänderte UID-/Datums- oder Stornologik. **101 relevante Tests / 530 Assertions und Pint erfolgreich**, darunter zehn zusätzliche ungültige Profile sowie Importwiederholung und Datumsänderung mit fehlendem DTSTAMP. Echte, Git-ignorierte Originaldatei separat ohne Datenbankzugriff lokal erfolgreich gelesen: elf Ereignisse/Belegungen, erste Anreise/Abreise 10.–24.11.2026, letzte 03.–10.10.2027. Vorhandene Verbindung 5 hat den Import derzeit ausgeschaltet; nicht aktiviert und keine echten Belegungen importiert. Mit `2ae48e7` durch [Pipeline 4698](https://gitea.stommer.de/Lars/fewo-stommer/actions/runs/4698) erfolgreich bereitgestellt; gesamte Feature-Suite, Build, Sicherung und Deployment erfolgreich, Release `20261029150456-2ae48e77`, Serverrevision und Gesundheitscheck HTTP 200 bestätigt. Anschließender echter Abruf auf Strato über ICalConnector und Parser erfolgreich: elf Ereignisse/Belegungen, elf eindeutige UIDs, alle Originale ohne DTSTAMP und mit LAST-MODIFIED. Verbindung 5 weiterhin Import aus, null Bestandszeilen vor/nach dieser rein lesenden Prüfung. Keine Migration und kein manueller Bestandsimport. [Kompatibilitätsgrenze](architecture/ical-kanalkonfiguration.md#6-import-änderungen-und-entfernung). diff --git a/docs/architecture/ical-kanalkonfiguration.md b/docs/architecture/ical-kanalkonfiguration.md index 4f13a50..370c8d0 100644 --- a/docs/architecture/ical-kanalkonfiguration.md +++ b/docs/architecture/ical-kanalkonfiguration.md @@ -254,3 +254,12 @@ ## 12. Migration, offene Risiken und Codeverweise | Tokenrotation | [`RotateChannelToken::handle`](../../app/Actions/RotateChannelToken.php) | | Schema und kompatible Kanalübernahme | [Migration](../../database/migrations/2026_10_27_154125_add_generic_ical_controls_and_provenance.php) | | Ausführbare Nachweise | [`GenericChannelIntegrationTest`](../../tests/Feature/GenericChannelIntegrationTest.php), [`ChannelSyncTest`](../../tests/Feature/ChannelSyncTest.php), [`PortalMailTest`](../../tests/Feature/PortalMailTest.php), [`TenantServiceGateTest`](../../tests/Feature/TenantServiceGateTest.php), [`TenantScheduleTest`](../../tests/Feature/TenantScheduleTest.php) | + + +## Automatische Zuordnung eindeutiger Kalenderspiegelungen (29.10.2026) + +Eine per aktiver Regel erkannte allgemeine zusätzliche Sperrmeldung ohne Gast-/Buchungsmerkmale und mit unbekanntem Ursprung wird genau einer führenden Portalreservierung eines anderen Kanals mit identischen Anreise-/Abreisedaten zugeordnet, sofern keine widersprüchlichen Belegungen oder persönlichen Entscheidungen vorliegen. Die führende Buchung erscheint einmal; „Auch bei … gespiegelt“ nennt die weiteren Kalender. Die Originalereignisse bleiben unter „Alle Importereignisse“ nachvollziehbar. Unbekannte Ereignisse ohne passende Regel werden weiterhin nicht allein anhand von Terminen zusammengeführt. + +Die Prüfung erfolgt nach erfolgreichem Import sowie beim Anwenden der Regeln. Eine automatische Zuordnung wird bei Änderungen oder fehlenden Quellereignissen wieder gelöst: Eine weiterhin gemeldete Sperre hält intern ihre Nächte belegt, bleibt vom Rückexport ausgeschlossen und erscheint zur Klärung. Persönliche Zuordnungen bleiben erhalten; eine persönliche Bestätigung als eigenständig verhindert erneutes automatisches Verknüpfen. Mehrere Quellbuchungen, abweichende Zeiträume und eigene Buchungsmerkmale bleiben Prüffälle. + +Schemaergänzung: `representation_automatic`, Standard false für bestehende persönliche Zuordnungen. Migration klassifiziert keine echten Belegungen; diese werden erst im regulären Import oder beim Anwenden aktiver Regeln geprüft. Rückbau wird bei vorhandenen automatischen Zuordnungen verweigert, damit diese nicht unbemerkt als persönliche Zuordnungen fortbestehen. diff --git a/docs/architecture/ical-regelengine.md b/docs/architecture/ical-regelengine.md index 0330b28..8b7bada 100644 --- a/docs/architecture/ical-regelengine.md +++ b/docs/architecture/ical-regelengine.md @@ -41,9 +41,11 @@ ## Führende Repräsentation und Zuordnung Eine erkannte Portalreservierung kann als führender Kandidat mit Vorrang gegenüber einer allgemeinen Sperre gekennzeichnet werden. Bei identischen Terminen zeigt die Vorschau mögliche Zusammenhänge mit vorhandenen Sperren und die Begründung **„exakt derselbe Zeitraum“**. -Dieser Hinweis ist kein Identitätsnachweis. Eine Regel erzeugt keine automatische Zusammenführung und hebt keine zusätzliche Sperre ungeprüft auf. Unter **Ungeklärte Belegungen → Details → Belegung zuordnen / klären** wird die Identität persönlich bestätigt. Führende Kandidaten stehen dort bei den gleich terminierten Zielen zuerst. Bestätigte Verknüpfungen und persönlich bekannte Herkunft werden durch die Regelauswertung erhalten. +Seit der Erweiterung vom 29.10.2026 können eindeutig erkannte Kalenderspiegelungen automatisch zugeordnet werden: Eine aktive Regel erkennt eine allgemeine Sperre als **Zusätzliche Sperre** mit unbekanntem Ursprung, ohne extrahierten Gastnamen oder Buchungsreferenz. Für exakt denselben Zeitraum existiert genau eine führende Portalreservierung eines anderen Kanals, deren Ursprung der eigene Quellkanal ist. Weitere widersprüchliche oder überlappende Belegungen, fehlende Importereignisse, persönliche Einordnungen und eigene Buchungsmerkmale verhindern die automatische Zuordnung. Priorität entscheidet bei mehreren möglichen Quellbuchungen nicht über die Identität. Andere Wohnungen und Mandanten werden nicht einbezogen. Persönliche Verknüpfungen bleiben erhalten. -Die Vorschau verlinkt den bereits importierten Eintrag und die zeitgleichen Kandidaten direkt zu ihren Belegungsdetails. Bei einer führenden Reservierung bleibt dieser Datensatz bestehen; die weitere Darstellung wird in deren eigenen Details der führenden Belegung zugeordnet. Dafür müssen die Termine und die fachliche Identität persönlich geprüft sein. Eine gemeinsame Zeitspanne allein reicht nicht. +Import und „Speichern & anwenden“ prüfen die Zuordnung für die gesamte betroffene Wohnung. Kalender und Buchungsliste zeigen die führende Belegung einmal und nennen die beteiligten Kalender als **Auch bei … gespiegelt**. Aufgelöste Spiegelungen zählen nicht als ungeklärte Belegung. Originalereignis, UID, Importkanal und lokaler Datensatz bleiben erhalten; Details und die Liste „Alle Importereignisse“ bleiben zugänglich. Automatische Zuordnungen sind mit `representation_automatic` ausdrücklich von persönlichen Zuordnungen getrennt. Die Vorschau verlinkt Einträge und Kandidaten weiterhin zu ihren Details. + +Bei Änderungen der Termine, neuen Buchungsmerkmalen, Mehrdeutigkeit oder einem fehlenden Quellereignis wird nur die automatische Zuordnung gelöst. Ein weiterhin gemeldeter Spiegel hält seine Nächte vorsorglich wieder selbst belegt und erscheint zur Klärung; sein Rückexport bleibt gesperrt. Stimmen beide Quellen wieder eindeutig überein, kann die Zuordnung erneut automatisch erfolgen. Persönliche Zuordnungen folgen weiterhin ihrer führenden Belegung und werden nicht automatisch aufgehoben. „Eigenständige Belegung bestätigen“ verhindert eine erneute automatische Zuordnung dieses Eintrags. Ausschließlich durch eindeutig zugeordnete Spiegel verursachte Konflikte werden nicht als Doppelbuchung gemeldet. Im Zuordnungsdialog heißt diese Auswahl **Weitere Darstellung einer Kalenderbelegung (Portalreservierung oder Sperrzeit)**. Die Ziele zeigen ihre tatsächliche Belegungsart und den erfassten Quellenhinweis. **Weitere Darstellung einer eigenen Buchung** ist für vollständige Buchungsvorgänge aus FewoPortal vorgesehen; eine importierte Portalreservierung wird als Kalenderbelegung gewählt. diff --git a/resources/views/filament/pages/occupancy-calendar.blade.php b/resources/views/filament/pages/occupancy-calendar.blade.php index 8154853..07c4093 100644 --- a/resources/views/filament/pages/occupancy-calendar.blade.php +++ b/resources/views/filament/pages/occupancy-calendar.blade.php @@ -64,6 +64,7 @@ {{ $event['kind'] === 'booking' || $event['kind'] === 'reservation' ? $event['guest'] : $event['kind_label'] }} {{ $event['source'] }} · {{ $event['status'] }} + @if ($event['mirrored_channels'])Auch bei {{ implode(', ', $event['mirrored_channels']) }} gespiegelt@endif @if ($event['kind'] === 'block' && filled($event['reason'])) Grund: {{ $event['reason'] }} @endif @@ -92,7 +93,12 @@
Zuordnung offen @endif - {{ $event['source'] }} + + {{ $event['source'] }} + @if ($event['mirrored_channels']) +
Auch bei {{ implode(', ', $event['mirrored_channels']) }} gespiegelt + @endif + {{ $event['review_note'] ?? ($event['kind'] === 'block' ? $event['reason'] : null) }}@if ($event['representations'])
{{ $event['representations'] }} zugeordnete Kalenderdarstellung(en)@endif @empty diff --git a/resources/views/filament/resources/channels/rule-preview.blade.php b/resources/views/filament/resources/channels/rule-preview.blade.php index 9179a02..8e3c3eb 100644 --- a/resources/views/filament/resources/channels/rule-preview.blade.php +++ b/resources/views/filament/resources/channels/rule-preview.blade.php @@ -1,7 +1,7 @@ @php($preview = $this->preview())

{{ count($preview['rows']) }} Originalereignisse · {{ $preview['unmatched'] }} noch nicht erkannt.

-

Dies ist die Vorschau des aktuellen Entwurfs. Die Einordnung im Belegungsplan ändert sich erst durch „Speichern & anwenden“. Ein Führungskandidat wird dadurch noch nicht automatisch mit anderen Einträgen zusammengeführt.

+

Dies ist die Vorschau des aktuellen Entwurfs. Die Einordnung im Belegungsplan ändert sich erst durch „Speichern & anwenden“. Eine allgemeine zusätzliche Sperre ohne eigene Buchungsmerkmale wird einer eindeutig passenden führenden Portalreservierung automatisch als Kalenderspiegelung zugeordnet. Zeitgleiche Termine allein reichen dafür nicht.

@foreach ($preview['rules'] as $index => $rule)

{{ $rule['name'] ?? 'Neue Regel' }}: {{ $preview['counts'][$index] ?? 0 }} Treffer nach Priorität.

@endforeach @@ -24,7 +24,7 @@ @if ($row['candidates'])

Mögliche Zusammenhänge: exakt derselbe Zeitraum

-

Das ist ein Hinweis, kein Identitätsnachweis. Den führenden Datensatz bestehen lassen. In den Details der zusätzlichen Darstellung über „Belegung zuordnen / klären“ die führende Belegung persönlich auswählen.

+

Das ist zunächst ein Hinweis. Die automatische Zuordnung benötigt eine erkannte allgemeine Sperrmeldung, genau eine führende Portalreservierung und keine widersprüchlichen Belegungen. Persönliche Zuordnungen bleiben erhalten. Unklare Fälle in den Belegungsdetails über „Belegung zuordnen / klären“ prüfen.

@foreach ($row['candidates'] as $candidate)

Kalendereintrag #{{ $candidate['id'] }} · {{ $candidate['reason'] }} · {{ $candidate['kind'] }} · Führungsvorrang {{ $candidate['priority'] }} @if ($candidate['url']) diff --git a/tests/Feature/AutomaticChannelRepresentationTest.php b/tests/Feature/AutomaticChannelRepresentationTest.php new file mode 100644 index 0000000..3e81ca6 --- /dev/null +++ b/tests/Feature/AutomaticChannelRepresentationTest.php @@ -0,0 +1,322 @@ +channels(); + Http::preventStrayRequests(); + Http::fake([ + 'https://portal.example/source.ics' => Http::response(self::feed('primary', 'Reservation: Nora Beispiel')), + 'https://portal.example/mirror.ics' => Http::response(self::feed('mirror', 'Blocked')), + ]); + Mail::fake(); + + foreach ($primaryFirst ? [$source, $mirror] : [$mirror, $source] as $channel) { + $this->assertTrue(app(SyncChannel::class)->handle($channel)->successful); + } + + $primary = $source->blockedPeriods()->sole(); + $copy = $mirror->blockedPeriods()->sole(); + $this->assertTrue($copy->is_representation); + $this->assertTrue($copy->representation_automatic); + $this->assertSame($primary->id, $copy->canonical_block_id); + $this->assertNull($copy->reviewed_at); + $this->assertNull($copy->origin_channel_id); + $this->assertFalse($copy->needs_review); + $this->assertFalse($primary->needs_review); + $this->assertTrue($primary->export_approved); + $this->assertSame('mirror', $copy->external_uid); + $this->assertStringContainsString('SUMMARY:Blocked', $copy->ical_raw); + $this->assertSame(0, Guest::count()); + $this->assertSame(0, BlockedPeriod::query()->unclear()->count()); + $this->assertSame(2, $property->blockedPeriods()->count()); + $this->actingAs(User::factory()->create()); + $record = app(OccupancyOverview::class)->records($property->id, includeBlocks: true)->sole(); + $this->assertSame(['Zweiter Kalender'], $record['mirrored_channels']); + $this->assertSame('Nora Beispiel', $record['guest']); + Livewire::test(OccupancyCalendar::class, ['propertyId' => $property->id, 'month' => '2027-05']) + ->assertSee('Auch bei Zweiter Kalender gespiegelt')->assertDontSee('occupancy-event kind-unknown', escape: false); + $target = Channel::factory()->for($property)->create(); + $this->assertStringContainsString('block-'.$primary->id.'@', app(ICalFeed::class)->build($mirror)); + $this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($source)); + $export = app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($target)); + $this->assertCount(1, $export['events']); + $this->assertSame('block-'.$primary->id.'@fewo-stommer', $export['events'][0]['uid']); + $modified = $copy->updated_at; + $this->travel(5)->minutes(); + app(SyncChannel::class)->handle($mirror); + $this->assertTrue($copy->fresh()->updated_at->equalTo($modified)); + Mail::assertNotSent(ChannelConflict::class); + Http::assertSentCount(3); + } + + public static function importOrders(): array + { + return ['primary first' => [true], 'mirror first' => [false]]; + } + + #[DataProvider('ambiguousCases')] + public function test_missing_evidence_contradictions_and_personal_decisions_prevent_automatic_linking(string $case): void + { + [$property, $source, $mirror] = $this->channels(); + [$primary, $copy] = $this->occupations($source, $mirror); + match ($case) { + 'unmatched' => $copy->forceFill(['ical_interpretation' => []])->saveQuietly(), + 'source booking' => $copy->forceFill(['ical_event_type' => 'portal_reservation'])->saveQuietly(), + 'reference' => $copy->forceFill(['ical_interpretation' => [...$copy->ical_interpretation, 'fields' => ['booking_reference' => 'EXTERNAL-123']]])->saveQuietly(), + 'name' => $copy->forceFill(['ical_interpretation' => [...$copy->ical_interpretation, 'fields' => ['guest_full_name' => 'Anderer Gast']]])->saveQuietly(), + 'origin' => $copy->forceFill(['origin_channel_id' => $mirror->id])->saveQuietly(), + 'same channel' => $copy->forceFill(['channel_id' => $source->id])->saveQuietly(), + 'different dates' => $copy->forceFill(['ends_on' => '2027-05-31'])->saveQuietly(), + 'personal decision' => $copy->forceFill(['reviewed_at' => now()])->saveQuietly(), + 'manual block' => $copy->forceFill(['occupation_kind' => 'block'])->saveQuietly(), + 'private' => $copy->forceFill(['is_private' => true])->saveQuietly(), + 'missing event' => $primary->forceFill(['missing_imports' => 1])->saveQuietly(), + 'multiple primaries' => $primary->replicate()->forceFill(['external_uid' => 'second-primary'])->saveQuietly(), + 'local booking' => Booking::factory()->for($property)->create(['arrival' => '2027-05-23', 'departure' => '2027-05-30', 'status' => 'confirmed']), + 'unknown overlap' => BlockedPeriod::factory()->for($property)->create(['source' => 'channel', 'starts_on' => '2027-05-25', 'ends_on' => '2027-05-28']), + 'custom review' => $copy->forceFill(['needs_review' => true, 'review_note' => 'Stornierung persönlich prüfen'])->saveQuietly(), + }; + + app(ReconcileChannelRepresentations::class)->handle($property); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertNull($copy->fresh()->canonical_block_id); + $this->assertFalse($primary->fresh()->is_representation); + } + + public static function ambiguousCases(): array + { + $cases = ['unmatched', 'source booking', 'reference', 'name', 'origin', 'same channel', 'different dates', 'personal decision', 'manual block', 'private', 'missing event', 'multiple primaries', 'local booking', 'unknown overlap', 'custom review']; + + return array_combine($cases, array_map(fn (string $case): array => [$case], $cases)); + } + + public function test_applying_rules_reconciles_existing_imports_without_fetching_or_recreating_them(): void + { + [$property, $source, $mirror] = $this->channels(); + [$primary, $copy] = $this->occupations($source, $mirror); + $primary->forceFill(['ical_event_type' => 'unknown', 'leading_priority' => 0, 'ical_interpretation' => []])->saveQuietly(); + $source->forceFill(['ical_rules' => [self::primaryRule()], 'ical_active_rules' => []])->save(); + Http::preventStrayRequests(); + + app(ApplyChannelRules::class)->handle($source); + + $this->assertTrue($copy->fresh()->is_representation); + $this->assertSame($primary->id, $copy->fresh()->canonical_block_id); + $this->assertSame(2, $property->blockedPeriods()->count()); + Http::assertNothingSent(); + } + + public function test_changed_dates_detach_the_mirror_until_both_sources_agree_again(): void + { + [$property, $source, $mirror] = $this->channels(); + Http::preventStrayRequests(); + Http::fake([ + 'https://portal.example/source.ics' => Http::sequence()->push(self::feed('primary', 'Reservation: Nora Beispiel'))->push(self::feed('primary', 'Reservation: Nora Beispiel', '20270601', '20270608')), + 'https://portal.example/mirror.ics' => Http::sequence()->push(self::feed('mirror', 'Blocked'))->push(self::feed('mirror', 'Blocked', '20270601', '20270608')), + ]); + Mail::fake(); + app(SyncChannel::class)->handle($source); + app(SyncChannel::class)->handle($mirror); + $primary = $source->blockedPeriods()->sole(); + $copy = $mirror->blockedPeriods()->sole(); + $this->assertTrue($copy->is_representation); + + app(SyncChannel::class)->handle($source); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertTrue($copy->fresh()->needs_review); + $this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, CarbonImmutable::parse('2027-05-23'), CarbonImmutable::parse('2027-05-30'))); + app(SyncChannel::class)->handle($mirror); + $this->assertTrue($copy->fresh()->is_representation); + $this->assertSame($primary->id, $copy->fresh()->canonical_block_id); + $this->assertFalse($copy->fresh()->needs_review); + $this->assertSame('2027-06-01', $copy->fresh()->starts_on->toDateString()); + Http::assertSentCount(4); + } + + public function test_missing_primary_reopens_a_still_reported_mirror_and_restoration_relinks_it(): void + { + [$property, $source, $mirror] = $this->channels(); + Http::preventStrayRequests(); + Http::fake([ + 'https://portal.example/source.ics' => Http::sequence()->push(self::feed('primary', 'Reservation: Nora Beispiel'))->push(self::feed())->push(self::feed())->push(self::feed('primary', 'Reservation: Nora Beispiel')), + 'https://portal.example/mirror.ics' => Http::response(self::feed('mirror', 'Blocked')), + ]); + Mail::fake(); + app(SyncChannel::class)->handle($source); + app(SyncChannel::class)->handle($mirror); + $primary = $source->blockedPeriods()->sole(); + $copy = $mirror->blockedPeriods()->sole(); + + app(SyncChannel::class)->handle($source); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertTrue($copy->fresh()->needs_review); + app(SyncChannel::class)->handle($source); + $this->assertSoftDeleted($primary); + $this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, $copy->starts_on, $copy->ends_on)); + $this->assertFalse($copy->fresh()->export_approved); + $this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($source)); + app(SyncChannel::class)->handle($source); + $this->assertSame($primary->id, $source->blockedPeriods()->sole()->id); + $this->assertTrue($copy->fresh()->is_representation); + Http::assertSentCount(5); + } + + public function test_new_booking_evidence_in_a_mirror_breaks_the_automatic_link(): void + { + [$property, $source, $mirror] = $this->channels(); + $mirror->forceFill(['ical_active_rules' => [self::primaryRule(), self::mirrorRule()]])->save(); + Http::preventStrayRequests(); + Http::fake([ + 'https://portal.example/source.ics' => Http::response(self::feed('primary', 'Reservation: Nora Beispiel')), + 'https://portal.example/mirror.ics' => Http::sequence()->push(self::feed('mirror', 'Blocked'))->push(self::feed('mirror', 'Reservation: Anderer Gast')), + ]); + Mail::fake(); + app(SyncChannel::class)->handle($source); + app(SyncChannel::class)->handle($mirror); + $copy = $mirror->blockedPeriods()->sole(); + $this->assertTrue($copy->is_representation); + + app(SyncChannel::class)->handle($mirror); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertTrue($copy->fresh()->needs_review); + $this->assertSame('reservation', $copy->fresh()->occupationKind()->value); + $this->assertSame('Anderer Gast', $copy->fresh()->guestName()); + Http::assertSentCount(3); + } + + public function test_personal_independent_confirmation_prevents_relinking_and_manual_aliases_are_preserved(): void + { + [$property, $source, $mirror] = $this->channels(); + [$primary, $copy] = $this->occupations($source, $mirror); + app(ReconcileChannelRepresentations::class)->handle($property); + $this->assertTrue($copy->fresh()->representation_automatic); + + app(ResolveChannelOccupation::class)->handle($copy, 'independent'); + app(ReconcileChannelRepresentations::class)->handle($property); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertFalse($copy->fresh()->representation_automatic); + app(ResolveChannelOccupation::class)->handle($copy, 'block', $primary->id); + $primary->delete(); + app(ReconcileChannelRepresentations::class)->handle($property); + $this->assertTrue($copy->fresh()->is_representation); + $this->assertFalse($copy->fresh()->representation_automatic); + } + + public function test_a_second_primary_breaks_an_existing_link_instead_of_using_priority_to_guess(): void + { + [$property, $source, $mirror] = $this->channels(); + [$primary, $copy] = $this->occupations($source, $mirror); + app(ReconcileChannelRepresentations::class)->handle($property); + $this->assertTrue($copy->fresh()->is_representation); + $primary->replicate()->forceFill(['external_uid' => 'second-primary', 'leading_priority' => 1])->saveQuietly(); + + app(ReconcileChannelRepresentations::class)->handle($property); + + $this->assertFalse($copy->fresh()->is_representation); + $this->assertTrue($copy->fresh()->needs_review); + $this->assertNull($copy->fresh()->canonical_block_id); + } + + public function test_reconciliation_does_not_cross_the_current_tenant_boundary(): void + { + [$property, $source, $mirror] = $this->channels(); + [$primary, $copy] = $this->occupations($source, $mirror); + $other = Property::factory()->for(Tenant::factory())->create(); + app(TenantContext::class)->set($other->tenant); + + try { + app(ReconcileChannelRepresentations::class)->handle($property); + $this->fail('A foreign property must not be reconciled.'); + } catch (ModelNotFoundException) { + app(TenantContext::class)->set($property->tenant); + $this->assertFalse($copy->fresh()->is_representation); + $this->assertFalse($primary->fresh()->is_representation); + } + } + + private function channels(): array + { + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00')); + $this->seed(PropertySeeder::class); + $property = Property::sole(); + app(TenantContext::class)->set($property->tenant); + $source = Channel::factory()->for($property)->create(['name' => 'Buchungsquelle', 'settings' => ['import_url' => 'https://portal.example/source.ics']]); + $analysis = app(ICalAnalysis::class)->summarize(app(ICalParser::class)->parseDocument(self::feed('primary', 'Reservation: Nora Beispiel'))); + $source->forceFill(['ical_active_rules' => [self::primaryRule()], 'ical_analysis' => $analysis])->save(); + $mirror = Channel::factory()->for($property)->create(['name' => 'Zweiter Kalender', 'settings' => ['import_url' => 'https://portal.example/mirror.ics']]); + $mirror->forceFill(['ical_active_rules' => [self::mirrorRule()]])->save(); + + return [$property, $source, $mirror]; + } + + private function occupations(Channel $source, Channel $mirror): array + { + $blocks = []; + foreach ([[$source, 'primary', 'Reservation: Nora Beispiel'], [$mirror, 'mirror', 'Blocked']] as [$channel, $uid, $summary]) { + $event = app(ICalParser::class)->parseDocument(self::feed($uid, $summary))['events'][0]; + $block = BlockedPeriod::factory()->for($channel->property)->create(['source' => 'channel', 'channel_id' => $channel->id, 'external_uid' => $uid, 'starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']); + $block->forceFill([...app(ApplyChannelRules::class)->attributes($channel, null, $event['properties']), 'ical_properties' => $event['properties'], 'ical_raw' => $event['raw']])->saveQuietly(); + $blocks[] = $block; + } + + return $blocks; + } + + private static function primaryRule(): array + { + return ['name' => 'Buchung', 'priority' => 10, 'enabled' => true, 'case_sensitive' => false, 'match' => 'all', 'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reservation: ']], 'event_type' => 'portal_reservation', 'origin' => 'current', 'representation' => 'leading_candidate', 'extractions' => [['field' => 'SUMMARY', 'target' => 'guest_full_name', 'method' => 'after', 'start' => 'Reservation: ']]]; + } + + private static function mirrorRule(): array + { + return [...self::primaryRule(), 'name' => 'Belegtmeldung', 'conditions' => [['field' => 'SUMMARY', 'operator' => 'equals', 'value' => 'Blocked']], 'event_type' => 'block', 'origin' => 'unknown', 'representation' => 'additional_block', 'extractions' => []]; + } + + private static function feed(?string $uid = null, string $summary = '', string $start = '20270523', string $end = '20270530'): string + { + $event = $uid === null ? '' : "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261029T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:{$summary}\r\nEND:VEVENT\r\n"; + + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic//DE\r\n{$event}END:VCALENDAR\r\n"; + } +}