Files
fewo-stommer/app/Actions/SyncChannel.php
LarsandClaude Opus 5.5 ac9d20b812 Ein Eingang fuer alle Kanaele (Paket 4, Prozessarchitektur v0.10)
Portalbuchungen und -anfragen aus Kalender und Mail werden ueber PortalIntake
zum Vorgang (nur bei sicherer Erkennung), Dubletten ueber Buchungsnummer,
gleiches Portal mit gleichen Naechten und Spiegelung; Unsicheres wird geklaert.
Portalstorno und -aenderung als Aufgabe am Vorgang ohne stille Stornierung.
Schalter je Kanal (Aus als Standard, Beobachten, Anlegen, Anlegen + weiter),
Eingangsprotokoll, Bestandsuebernahme mit Vorschau/Bericht/Ruecknahme,
Sperrnachweis in drei Stufen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:53:35 +01:00

155 lines
10 KiB
PHP

<?php
namespace App\Actions;
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Channels\Intake\PortalIntake;
use App\Enums\ChannelEchoBehavior;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
class SyncChannel
{
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
public function handle(Channel $channel): ChannelSyncLog
{
$startedAt = microtime(true);
$lock = Cache::lock("channel-sync:{$channel->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];
$interpretation = $period->properties !== [] ? app(ApplyChannelRules::class)->attributes($locked, $block ?? $matchedMail, $period->properties) : [];
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 = new BlockedPeriod($attributes);
$block->forceFill($interpretation);
$channel->blockedPeriods()->save($block);
$counts['added']++;
}
if ($period->properties !== []) {
app(ApplyChannelRules::class)->store($block, [...$interpretation, 'ical_properties' => $period->properties, 'ical_raw' => $period->raw]);
}
$existing->put($period->uid, $block);
}
$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.';
}
}
}
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;
}
foreach ($foundConflicts as $conflict) {
$conflicts[$conflict] ??= $block->starts_on;
}
}
$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();
});
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
// One intake for all channels (package 4); a failure there never fails the sync itself.
rescue(fn () => app(PortalIntake::class)->afterSync($channel->fresh()));
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
'conflicts' => count($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();
}
}
}