Eindeutige iCal-Kalenderspiegelungen automatisch und widerrufbar zuordnen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s

This commit is contained in:
Lars committed 2026-10-29 17:01:30 +01:00
1 parent 8b36e07dc4
commit add2367869
16 files changed
+540 -31

No files matched your search

+1
View File
@@ -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;
});
+3
View File
@@ -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);
});
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Actions;
use App\Enums\ChannelEchoBehavior;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
class ReconcileChannelRepresentations
{
public const OVERLAP_NOTE = 'Mehrere Belegungsrepräsentationen oder Überschneidungen prüfen; keine automatische Zusammenführung anhand von Terminen.';
private const LINK_NOTE = 'Automatisch als Kalenderspiegelung einer eindeutig passenden führenden Portalreservierung zugeordnet.';
private const RECHECK_NOTE = 'Automatische Kalenderspiegelung nicht mehr eindeutig. Quellen, Termine und mögliche Stornierung prüfen; der weiterhin gemeldete Zeitraum bleibt belegt.';
/** @return array{linked: int, unlinked: int} */
public function handle(Property $property): array
{
return DB::transaction(function () use ($property): array {
$property = Property::query()->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);
}
}
+4 -1
View File
@@ -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();
});
+18 -15
View File
@@ -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();