Files
2026-10-23 07:14:25 +02:00

130 lines
5.2 KiB
PHP

<?php
namespace App\Actions;
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Mail\ChannelConflict;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Imports the occupations of one portal as blocked periods and reports overlaps with
* occupations from anywhere else immediately (possible double booking).
*/
class SyncChannel
{
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
public function handle(Channel $channel): ChannelSyncLog
{
$startedAt = microtime(true);
try {
$periods = $channel->connector()->fetchOccupations($channel);
} catch (ChannelSyncException $exception) {
$channel->forceFill(['last_synced_at' => now(), 'last_error' => $exception->getMessage()])->save();
return $channel->syncLogs()->create([
'successful' => false,
'message' => $exception->getMessage(),
'duration_ms' => $this->elapsed($startedAt),
]);
}
$today = CarbonImmutable::today();
$suffix = config('channels.uid_suffix');
$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];
$conflicts = [];
DB::transaction(function () use ($channel, $periods, $today, &$counts, &$conflicts): void {
$existing = $channel->blockedPeriods()->where('source', 'channel')->get()->keyBy('external_uid');
$fromEmails = $channel->blockedPeriods()->where('source', 'email')->get();
$seen = [];
foreach ($periods as $period) {
$seen[$period->uid] = true;
$block = $existing->get($period->uid);
if ($block && $block->starts_on->equalTo($period->startsOn) && $block->ends_on->equalTo($period->endsOn)) {
continue;
}
$attributes = [
'property_id' => $channel->property_id,
'starts_on' => $period->startsOn->toDateString(),
'ends_on' => $period->endsOn->toDateString(),
// The portal's SUMMARY is not stored: it may contain guest names (data minimisation).
'reason' => $channel->name,
'source' => 'channel',
];
$confirmedEmailBlock = $block ? null : $fromEmails->first(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->equalTo($period->startsOn) && $emailBlock->ends_on->equalTo($period->endsOn));
if ($confirmedEmailBlock) {
// Already blocked from the portal's e-mail; the calendar only confirms it.
$confirmedEmailBlock->update([...$attributes, 'external_uid' => $period->uid]);
$fromEmails = $fromEmails->reject(fn (BlockedPeriod $emailBlock): bool => $emailBlock->is($confirmedEmailBlock));
$counts['changed']++;
continue;
}
if ($block) {
$block->update($attributes);
$counts['changed']++;
} else {
$block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]);
$counts['added']++;
}
// E-mail blocks of this portal overlapping the calendar entry describe the same booking with deviating dates.
$superseded = $fromEmails->filter(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->lessThan($block->ends_on) && $emailBlock->ends_on->greaterThan($block->starts_on));
$superseded->each->delete();
$fromEmails = $fromEmails->diff($superseded);
array_push($conflicts, ...$this->conflictDetector->conflictsFor($block));
}
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
$stale->each->delete();
$counts['removed'] = $stale->count();
});
$channel->forceFill([
'last_synced_at' => now(),
'last_success_at' => now(),
'last_error' => null,
'alerted_at' => null,
])->save();
if ($conflicts !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
}
return $channel->syncLogs()->create([
'successful' => true,
'events' => count($periods),
...$counts,
'conflicts' => count($conflicts),
'duration_ms' => $this->elapsed($startedAt),
]);
}
private function elapsed(float $startedAt): int
{
return (int) round((microtime(true) - $startedAt) * 1000);
}
}