Files
fewo-stommer/app/Actions/SyncChannel.php
T
Lars StommerandClaude Opus 5.5 4f69b426a4 Booking path 1 (offer + guest acceptance), 2FA for all, privacy hardening, brand graphics in theme
- Offer workflow: "Angebot senden" in the admin (dates, guests, promo code, manual price adjustment,
  validity from the property's hold time, message, guest data for the contract) with live price;
  contract draft PDF; signed, versioned offer page for the guest to accept (acceptance record without
  IP) or decline; expiry job, landlord notifications, editable offer texts, wording on the website.
- 2FA is mandatory for every admin account.
- Privacy: complete anonymisation (notes, attribution, review names, offer messages), shorter
  periods for unbinding requests, portal mail excerpts and attribution (configurable proposals),
  iCal summary not stored, known e-mail no longer overwrites guest data, security headers, bearer
  tokens for automations, metadata stripped from photo originals, review link throttled.
- Daily database backup (backup:database) and scripts/backup-pull.sh for the NAS.
- Theme: brand mark in header/footer, favicon/touch icon, wave divider, icons, illustration as
  image placeholder; navy follows the text colour for dark appearances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:38:22 +02:00

129 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 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(config('fewo.notification_email'))->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);
}
}