tenant_id}:{$channel->id}", 120); if (! $lock->get()) { return $channel->syncLogs()->create(['successful' => false, 'message' => 'Für diesen Kanal läuft bereits ein Abgleich.']); } try { $channel->refresh(); if (! $channel->importsOccupations()) { return $channel->syncLogs()->create(['successful' => false, 'message' => 'Import ist pausiert oder noch nicht eingerichtet.']); } $importUrl = $channel->setting('import_url'); $periods = $channel->connector()->fetchOccupations($channel); $suffix = config('channels.uid_suffix'); if (! is_string($suffix) || $suffix === '') { throw new ChannelSyncException('Der UID-Echofilter ist nicht eingerichtet.'); } $today = CarbonImmutable::today(); $periods = array_values(array_filter($periods, fn (ExternalPeriod $period): bool => $period->endsOn->greaterThan($today) && ! str_ends_with($period->uid, $suffix))); $counts = ['added' => 0, 'changed' => 0, 'removed' => 0]; $warnings = []; $conflicts = []; DB::transaction(function () use ($channel, $periods, $importUrl, $today, &$counts, &$warnings, &$conflicts): void { $locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail(); if (! $locked->importsOccupations() || $locked->setting('import_url') !== $importUrl) { throw new ChannelSyncException('Die Kanalkonfiguration wurde während des Abrufs geändert.'); } Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail(); $rows = $channel->blockedPeriods()->withTrashed()->where('source', 'channel')->get(); if ($rows->groupBy('external_uid')->contains(fn ($group): bool => $group->count() > 1) || $rows->contains(fn (BlockedPeriod $block): bool => blank($block->external_uid))) { throw new ChannelSyncException('Vorhandene Kalender-Dubletten oder fehlende UIDs benötigen eine manuelle Prüfung. Der Bestand bleibt erhalten.'); } $existing = $rows->keyBy('external_uid'); $emails = $channel->blockedPeriods()->where('source', 'email')->get(); $seen = []; foreach ($periods as $period) { $seen[$period->uid] = true; $block = $existing->get($period->uid); $matchedMail = $block ? null : $emails->firstWhere('external_uid', 'email:'.$period->uid); $attributes = ['property_id' => $channel->property_id, 'starts_on' => $period->startsOn->toDateString(), 'ends_on' => $period->endsOn->toDateString(), 'reason' => $channel->name, 'source' => 'channel', 'external_uid' => $period->uid, 'missing_imports' => 0]; if ($matchedMail) { $block = $matchedMail; $block->update($attributes); $emails = $emails->reject(fn (BlockedPeriod $mail): bool => $mail->is($block)); $counts['changed']++; } elseif ($block) { if ($block->trashed()) { $block->fill($attributes)->restore(); $counts['added']++; } elseif (! $block->starts_on->equalTo($period->startsOn) || ! $block->ends_on->equalTo($period->endsOn)) { $block->update($attributes); $counts['changed']++; } elseif ($block->missing_imports !== 0) { $block->forceFill(['missing_imports' => 0])->saveQuietly(); } } else { $overlap = $channel->property->blockedPeriods()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists() || $channel->property->bookings()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists(); $attributes['export_approved'] = ! $overlap && $locked->echo_behavior !== ChannelEchoBehavior::Reexports; $block = $channel->blockedPeriods()->create($attributes); $counts['added']++; } $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)) { $warnings[] = 'Ungewöhnlich viele Ereignisse fehlen. Keine automatische Entfernung; Portalkalender persönlich prüfen.'; foreach ($missing as $block) { $block->forceFill(['needs_review' => true, 'review_note' => end($warnings)])->saveQuietly(); } } else { foreach ($missing as $block) { $block->increment('missing_imports'); if ($block->missing_imports >= config('channels.removal_confirmation_runs', 2)) { $block->delete(); $counts['removed']++; } else { $warnings[] = 'Fehlende Ereignisse bleiben bis zum nächsten bestätigenden Kalenderstand gesperrt.'; } } } $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(); }); if ($conflicts !== []) { rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, array_values(array_unique($conflicts))))); } return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts, 'conflicts' => count(array_unique($conflicts)), 'warnings' => $warnings, 'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]); } catch (ChannelSyncException $exception) { $channel->forceFill(['last_synced_at' => now(), 'last_error_at' => now(), 'last_error' => $exception->getMessage()])->save(); return $channel->syncLogs()->create(['successful' => false, 'message' => $exception->getMessage(), 'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]); } finally { $lock->release(); } } }