diff --git a/.env.example b/.env.example index a3e07d9..663911c 100644 --- a/.env.example +++ b/.env.example @@ -73,3 +73,8 @@ FEWO_BANK_BIC= FEWO_BANK_NAME= FEWO_REVIEW_REQUEST_AFTER_DAYS=2 FEWO_GUEST_RETENTION_YEARS=10 +FEWO_CHANNEL_STALE_AFTER_MINUTES=60 +FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120 +FEWO_HEALTH_TOKEN= +FEWO_AUTOMATION_WEBHOOK_URL= +FEWO_AUTOMATION_SECRET= diff --git a/AGENTS.md b/AGENTS.md index ac11386..3b175e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,7 @@ # Ferienwohnung Stommer - Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status. - Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly. - Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. +- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal analysis: `docs/PORTALE.md`. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/CLAUDE.md b/CLAUDE.md index ac11386..3b175e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,6 +11,7 @@ # Ferienwohnung Stommer - Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status. - Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly. - Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. +- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal analysis: `docs/PORTALE.md`. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/app/Actions/CreateChannelTasks.php b/app/Actions/CreateChannelTasks.php new file mode 100644 index 0000000..4265655 --- /dev/null +++ b/app/Actions/CreateChannelTasks.php @@ -0,0 +1,92 @@ + + */ + public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null): array + { + if ($endsOn->lessThanOrEqualTo(today())) { + return []; + } + + $channels = $property->channels()->active() + ->where('requires_manual_blocking', true) + ->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId)) + ->get(); + + $tasks = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([ + 'action' => $action, + 'starts_on' => $startsOn->toDateString(), + 'ends_on' => $endsOn->toDateString(), + 'reason' => $reason, + ]))->all(); + + if ($tasks === []) { + return []; + } + + rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks))); + + foreach ($tasks as $task) { + $this->sendToAutomation($task); + } + + return $tasks; + } + + /** + * POSTs the task to the automation webhook, signed with HMAC-SHA256 (header X-Signature). + * The automation confirms via the signed callback URL contained in the payload. + */ + public function sendToAutomation(ChannelTask $task): void + { + $url = config('fewo.automation.webhook_url'); + $secret = config('fewo.automation.secret'); + if (blank($url) || blank($secret)) { + return; + } + + $body = json_encode([ + 'task_id' => $task->id, + 'channel' => $task->channel->name, + 'connector' => $task->channel->connector, + 'action' => $task->action->value, + 'starts_on' => $task->starts_on->toDateString(), + 'ends_on' => $task->ends_on->toDateString(), + 'manage_url' => $task->channel->manage_url, + 'callback_url' => URL::route('channel-tasks.complete', $task), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + + try { + Http::timeout(10) + ->withHeaders(['X-Signature' => hash_hmac('sha256', $body, $secret)]) + ->withBody($body, 'application/json') + ->post($url) + ->throw(); + + $task->update(['automation_sent_at' => now(), 'automation_error' => null]); + } catch (Throwable $exception) { + $task->update(['automation_error' => $exception->getMessage()]); + } + } +} diff --git a/app/Actions/CreateReservation.php b/app/Actions/CreateReservation.php index 3f78019..aea5f48 100644 --- a/app/Actions/CreateReservation.php +++ b/app/Actions/CreateReservation.php @@ -13,6 +13,7 @@ use App\Pricing\PriceCalculator; use App\Pricing\QuoteException; use App\Pricing\StayRequest; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; use Throwable; @@ -30,13 +31,14 @@ public function __construct( /** * @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData + * @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from * * @throws QuoteException * @throws ReservationException */ - public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking + public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking { - $booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking { + $booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking { Property::whereKey($property->getKey())->lockForUpdate()->first(); if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) { @@ -52,6 +54,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData, 'guest_id' => $guest->id, 'status' => BookingStatus::Reserved, 'source' => $source, + ...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']), 'arrival' => $stay->arrival->toDateString(), 'departure' => $stay->departure->toDateString(), 'guests' => $stay->guests, diff --git a/app/Actions/MonitorChannels.php b/app/Actions/MonitorChannels.php new file mode 100644 index 0000000..ad8e2af --- /dev/null +++ b/app/Actions/MonitorChannels.php @@ -0,0 +1,27 @@ +active()->whereNull('alerted_at')->get() + ->filter(fn (Channel $channel): bool => $channel->isStale()); + + foreach ($channels as $channel) { + Mail::to(config('fewo.notification_email'))->send(new ChannelSyncAlert($channel)); + $channel->forceFill(['alerted_at' => now()])->save(); + } + + return $channels->count(); + } +} diff --git a/app/Actions/RemindChannelTasks.php b/app/Actions/RemindChannelTasks.php new file mode 100644 index 0000000..297c44a --- /dev/null +++ b/app/Actions/RemindChannelTasks.php @@ -0,0 +1,32 @@ +open() + ->whereNull('reminded_at') + ->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes'))) + ->with('channel') + ->get(); + + if ($tasks->isEmpty()) { + return 0; + } + + Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks->all(), reminder: true)); + ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]); + + return $tasks->count(); + } +} diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php new file mode 100644 index 0000000..d8f27ac --- /dev/null +++ b/app/Actions/SyncChannel.php @@ -0,0 +1,132 @@ +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()->get()->keyBy('external_uid'); + $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(), + 'reason' => "{$channel->name}".($period->summary ? ": {$period->summary}" : ''), + 'source' => 'channel', + ]; + + if ($block) { + $block->update($attributes); + $counts['changed']++; + } else { + $block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]); + $counts['added']++; + } + + array_push($conflicts, ...$this->conflictsFor($channel, $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), + ]); + } + + /** + * Occupations from other sources that overlap the imported block. + * + * @return list + */ + private function conflictsFor(Channel $channel, BlockedPeriod $block): array + { + $property = $channel->property; + $imported = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y'); + + $bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get() + ->map(fn (Booking $booking): string => "{$channel->name} meldet {$imported}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})"); + + $blocks = $property->blockedPeriods() + ->overlapping($block->starts_on, $block->ends_on) + ->whereKeyNot($block->getKey()) + ->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id)) + ->with('channel') + ->get() + ->map(fn (BlockedPeriod $other): string => "{$channel->name} meldet {$imported}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})"); + + return [...$bookings->all(), ...$blocks->all()]; + } + + private function elapsed(float $startedAt): int + { + return (int) round((microtime(true) - $startedAt) * 1000); + } +} diff --git a/app/Channels/ChannelRegistry.php b/app/Channels/ChannelRegistry.php new file mode 100644 index 0000000..e88b01c --- /dev/null +++ b/app/Channels/ChannelRegistry.php @@ -0,0 +1,37 @@ +> + */ + public function connectors(): array + { + return collect(config('channels.connectors')) + ->mapWithKeys(fn (string $class): array => [$class::key() => $class]) + ->all(); + } + + public function resolve(string $key): ChannelConnector + { + $class = $this->connectors()[$key] ?? throw new InvalidArgumentException("Unknown channel connector [{$key}]."); + + return app($class); + } + + /** + * @return array + */ + public function options(): array + { + return array_map(fn (string $class): string => $class::label(), $this->connectors()); + } +} diff --git a/app/Channels/ChannelSyncException.php b/app/Channels/ChannelSyncException.php new file mode 100644 index 0000000..86d399d --- /dev/null +++ b/app/Channels/ChannelSyncException.php @@ -0,0 +1,7 @@ + + */ + public static function settingsSchema(): array; + + /** + * Whether occupations can currently be imported (e.g. an import URL is configured). + */ + public function canImport(Channel $channel): bool; + + /** + * All occupations the portal currently reports. + * + * @return list + * + * @throws ChannelSyncException + */ + public function fetchOccupations(Channel $channel): array; +} diff --git a/app/Channels/ExternalPeriod.php b/app/Channels/ExternalPeriod.php new file mode 100644 index 0000000..a152582 --- /dev/null +++ b/app/Channels/ExternalPeriod.php @@ -0,0 +1,18 @@ +label('iCal-Export-Adresse des Portals') + ->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.') + ->url() + ->maxLength(2048), + ]; + } + + public function canImport(Channel $channel): bool + { + return filled($channel->setting('import_url')); + } + + public function fetchOccupations(Channel $channel): array + { + $url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url')); + + try { + $response = Http::timeout(20) + ->retry(2, 1000) + ->withHeaders(['Accept' => 'text/calendar']) + ->get($url) + ->throw(); + } catch (ConnectionException|RequestException $exception) { + throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception); + } + + return $this->parser->parse($response->body()); + } +} diff --git a/app/Channels/ICal/ICalFeed.php b/app/Channels/ICal/ICalFeed.php new file mode 100644 index 0000000..591586a --- /dev/null +++ b/app/Channels/ICal/ICalFeed.php @@ -0,0 +1,70 @@ +property; + $from = CarbonImmutable::today()->subDays(30); + $until = CarbonImmutable::today()->addYears(2); + $suffix = config('channels.uid_suffix'); + + $events = []; + + foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) { + /** @var Booking $booking */ + $events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at); + } + + $blocks = $property->blockedPeriods() + ->overlapping($from, $until) + ->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id)) + ->get(); + + foreach ($blocks as $block) { + $events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at); + } + + return implode("\r\n", [ + 'BEGIN:VCALENDAR', + 'VERSION:2.0', + 'PRODID:-//Ferienwohnung Stommer//Belegung//DE', + 'CALSCALE:GREGORIAN', + 'METHOD:PUBLISH', + 'X-WR-CALNAME:'.$this->escape($property->name), + ...$events, + 'END:VCALENDAR', + ])."\r\n"; + } + + private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string + { + return implode("\r\n", [ + 'BEGIN:VEVENT', + "UID:{$uid}", + 'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'), + 'DTSTART;VALUE=DATE:'.$start->format('Ymd'), + 'DTEND;VALUE=DATE:'.$end->format('Ymd'), + 'SUMMARY:Belegt', + 'TRANSP:OPAQUE', + 'END:VEVENT', + ]); + } + + private function escape(string $text): string + { + return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text); + } +} diff --git a/app/Channels/ICal/ICalParser.php b/app/Channels/ICal/ICalParser.php new file mode 100644 index 0000000..f47779a --- /dev/null +++ b/app/Channels/ICal/ICalParser.php @@ -0,0 +1,121 @@ + + * + * @throws ChannelSyncException + */ + public function parse(string $ics): array + { + if (! str_contains($ics, 'BEGIN:VCALENDAR')) { + throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.'); + } + + $lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics))); + + $periods = []; + $event = null; + foreach ($lines as $line) { + $line = rtrim($line, "\r"); + + if ($line === 'BEGIN:VEVENT') { + $event = []; + + continue; + } + + if ($line === 'END:VEVENT') { + if ($event !== null && ($period = $this->toPeriod($event))) { + $periods[] = $period; + } + $event = null; + + continue; + } + + if ($event !== null && str_contains($line, ':')) { + [$nameWithParams, $value] = explode(':', $line, 2); + $parts = explode(';', $nameWithParams); + $event[strtoupper($parts[0])] = ['value' => $value, 'params' => array_slice($parts, 1)]; + } + } + + return $periods; + } + + /** + * @param array}> $event + */ + private function toPeriod(array $event): ?ExternalPeriod + { + if (! isset($event['DTSTART']) || strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') { + return null; + } + + $start = $this->toDate($event['DTSTART']); + $end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay(); + + if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) { + return null; + } + + $uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString()); + + return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null)); + } + + /** + * @param array{value: string, params: list} $property + */ + private function toDate(array $property): ?CarbonImmutable + { + $value = trim($property['value']); + + if (preg_match('/^\d{8}$/', $value)) { + return CarbonImmutable::createFromFormat('!Ymd', $value); + } + + if (preg_match('/^(\d{8})T(\d{6})(Z?)$/', $value, $match)) { + $timezone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']); + + return CarbonImmutable::createFromFormat('YmdHis', $match[1].$match[2], $timezone) + ->setTimezone(config('app.timezone')) + ->startOfDay(); + } + + return null; + } + + /** + * @param list $params + */ + private function timezone(array $params): string + { + foreach ($params as $param) { + if (str_starts_with(strtoupper($param), 'TZID=')) { + $tz = trim(substr($param, 5), '"'); + + return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone'); + } + } + + return config('app.timezone'); + } + + private function unescape(?string $text): ?string + { + return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text); + } +} diff --git a/app/Console/Commands/SyncChannels.php b/app/Console/Commands/SyncChannels.php new file mode 100644 index 0000000..f3f15a5 --- /dev/null +++ b/app/Console/Commands/SyncChannels.php @@ -0,0 +1,35 @@ +active() + ->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id)) + ->get() + ->filter(fn (Channel $channel): bool => $channel->importsOccupations()); + + foreach ($channels as $channel) { + $log = $syncChannel->handle($channel); + + $log->successful + ? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}") + : $this->error("✗ {$channel->name}: {$log->message}"); + } + + return self::SUCCESS; + } +} diff --git a/app/Enums/ChannelTaskAction.php b/app/Enums/ChannelTaskAction.php new file mode 100644 index 0000000..f4de97b --- /dev/null +++ b/app/Enums/ChannelTaskAction.php @@ -0,0 +1,28 @@ + 'Sperren', + self::Unblock => 'Freigeben', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Block => 'danger', + self::Unblock => 'success', + }; + } +} diff --git a/app/Enums/ChannelTaskStatus.php b/app/Enums/ChannelTaskStatus.php new file mode 100644 index 0000000..25c2510 --- /dev/null +++ b/app/Enums/ChannelTaskStatus.php @@ -0,0 +1,31 @@ + 'Offen', + self::Done => 'Erledigt', + self::Dismissed => 'Verworfen', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Open => 'warning', + self::Done => 'success', + self::Dismissed => 'gray', + }; + } +} diff --git a/app/Enums/ReferralSource.php b/app/Enums/ReferralSource.php new file mode 100644 index 0000000..c0e48d0 --- /dev/null +++ b/app/Enums/ReferralSource.php @@ -0,0 +1,36 @@ + 'Suchmaschine (z. B. Google)', + self::FewoDirekt => 'FeWo-direkt', + self::Ostseeklar => 'Ostseeklar', + self::FerienUndWohnen => 'ferienundwohnen.de', + self::TouristInformation => 'Tourist-Information Kühlungsborn', + self::SocialMedia => 'Social Media', + self::Recommendation => 'Empfehlung', + self::ReturningGuest => 'Ich war schon Gast', + self::Other => 'Sonstiges', + }; + } +} diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index b86a0d9..b312e36 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -66,6 +66,11 @@ public static function configure(Schema $schema): Schema TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null), TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'), TextEntry::make('source')->label('Quelle'), + TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'), + TextEntry::make('utm') + ->label('Kampagne (UTM)') + ->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null) + ->visible(fn (Booking $record): bool => filled($record->utm_source)), ]), Section::make('Gast') ->schema([ diff --git a/app/Filament/Resources/ChannelTasks/ChannelTaskResource.php b/app/Filament/Resources/ChannelTasks/ChannelTaskResource.php new file mode 100644 index 0000000..dec7b66 --- /dev/null +++ b/app/Filament/Resources/ChannelTasks/ChannelTaskResource.php @@ -0,0 +1,56 @@ +open()->count(); + + return $open > 0 ? (string) $open : null; + } + + public static function getNavigationBadgeColor(): string + { + return 'danger'; + } + + public static function getPages(): array + { + return [ + 'index' => ListChannelTasks::route('/'), + ]; + } +} diff --git a/app/Filament/Resources/ChannelTasks/Pages/ListChannelTasks.php b/app/Filament/Resources/ChannelTasks/Pages/ListChannelTasks.php new file mode 100644 index 0000000..886ff47 --- /dev/null +++ b/app/Filament/Resources/ChannelTasks/Pages/ListChannelTasks.php @@ -0,0 +1,11 @@ +defaultSort('created_at', 'desc') + ->description('Diese Portale werden zusätzlich von Hand gepflegt. Bitte die Änderung im Portal vornehmen und hier abhaken.') + ->columns([ + TextColumn::make('channel.name')->label('Portal')->weight('medium'), + TextColumn::make('action')->label('Aktion')->badge(), + TextColumn::make('period')->label('Zeitraum')->state(fn (ChannelTask $record): string => $record->period()), + TextColumn::make('reason')->label('Anlass')->wrap(), + TextColumn::make('status')->label('Status')->badge() + ->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null), + TextColumn::make('created_at')->label('Seit')->since(), + TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true), + ]) + ->filters([ + SelectFilter::make('status') + ->label('Status') + ->options(ChannelTaskStatus::class) + ->default(ChannelTaskStatus::Open->value), + ]) + ->recordActions([ + Action::make('openPortal') + ->label('Portal öffnen') + ->icon(Heroicon::OutlinedArrowTopRightOnSquare) + ->color('gray') + ->url(fn (ChannelTask $record): ?string => $record->channel->manage_url, shouldOpenInNewTab: true) + ->visible(fn (ChannelTask $record): bool => filled($record->channel->manage_url)), + Action::make('done') + ->label('Erledigt') + ->icon(Heroicon::OutlinedCheck) + ->color('success') + ->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open) + ->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)), + Action::make('dismiss') + ->label('Verwerfen') + ->icon(Heroicon::OutlinedXMark) + ->color('gray') + ->requiresConfirmation() + ->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open) + ->action(fn (ChannelTask $record) => $record->update(['status' => ChannelTaskStatus::Dismissed])), + ]); + } +} diff --git a/app/Filament/Resources/Properties/PropertyResource.php b/app/Filament/Resources/Properties/PropertyResource.php index c997963..17c3047 100644 --- a/app/Filament/Resources/Properties/PropertyResource.php +++ b/app/Filament/Resources/Properties/PropertyResource.php @@ -6,6 +6,7 @@ use App\Filament\Resources\Properties\Pages\EditProperty; use App\Filament\Resources\Properties\Pages\ListProperties; use App\Filament\Resources\Properties\RelationManagers\BlockedPeriodsRelationManager; +use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager; use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager; use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager; use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager; @@ -50,6 +51,7 @@ public static function getRelations(): array SpecialOffersRelationManager::class, ExtrasRelationManager::class, BlockedPeriodsRelationManager::class, + ChannelsRelationManager::class, ]; } diff --git a/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php new file mode 100644 index 0000000..5ff6dbb --- /dev/null +++ b/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php @@ -0,0 +1,155 @@ +columns(2) + ->components([ + TextInput::make('name') + ->label('Name') + ->placeholder('z. B. FeWo-direkt') + ->required() + ->maxLength(100), + Select::make('connector') + ->label('Anbindung') + ->options($registry->options()) + ->default('ical') + ->live() + ->required(), + Group::make() + ->columnSpanFull() + ->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []), + TextEntry::make('export_url') + ->label('Unsere Kalender-Adresse für dieses Portal') + ->helperText('Diese Adresse im Portal unter „Kalender importieren“ eintragen. Sie enthält alle Belegungen außer denen dieses Portals.') + ->state(fn (?Channel $record): ?string => $record?->exportUrl()) + ->copyable() + ->visible(fn (?Channel $record): bool => $record !== null) + ->columnSpanFull(), + Toggle::make('requires_manual_blocking') + ->label('Zusätzlich von Hand sperren (Sofortbuchung)') + ->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.') + ->live() + ->columnSpanFull(), + TextInput::make('manage_url') + ->label('Link zum Kalender im Vermieterbereich') + ->url() + ->maxLength(2048) + ->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking')) + ->columnSpanFull(), + Toggle::make('is_active') + ->label('Aktiv') + ->default(true), + ]); + } + + public function table(Table $table): Table + { + return $table + ->recordTitleAttribute('name') + ->description('Unser System ist führend: Belegungen der Portale werden alle 5 Minuten eingelesen, jedes Portal erhält einen eigenen Kalender mit allen übrigen Belegungen.') + ->columns([ + TextColumn::make('name')->label('Portal')->weight('medium'), + TextColumn::make('status') + ->label('Status') + ->badge() + ->state(fn (Channel $record): string => match (true) { + ! $record->is_active => 'Inaktiv', + ! $record->importsOccupations() => 'Nur Export', + $record->last_error !== null => 'Fehler', + $record->isStale() => 'Veraltet', + default => 'OK', + }) + ->color(fn (string $state): string => match ($state) { + 'OK' => 'success', + 'Fehler', 'Veraltet' => 'danger', + default => 'gray', + }) + ->tooltip(fn (Channel $record): ?string => $record->last_error), + TextColumn::make('last_success_at')->label('Letzter Abgleich')->since()->placeholder('–'), + TextColumn::make('requires_manual_blocking') + ->label('Handpflege') + ->formatStateUsing(fn (bool $state): string => $state ? 'ja' : '–'), + ]) + ->headerActions([ + CreateAction::make(), + ]) + ->recordActions([ + Action::make('sync') + ->label('Jetzt abgleichen') + ->icon(Heroicon::OutlinedArrowPath) + ->visible(fn (Channel $record): bool => $record->importsOccupations()) + ->action(function (Channel $record, SyncChannel $syncChannel): void { + $log = $syncChannel->handle($record); + + $log->successful + ? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send() + : Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send(); + }), + Action::make('logs') + ->label('Protokoll') + ->icon(Heroicon::OutlinedListBullet) + ->color('gray') + ->modalSubmitAction(false) + ->modalCancelActionLabel('Schließen') + ->schema([ + RepeatableEntry::make('recentLogs') + ->hiddenLabel() + ->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [ + 'time' => $log->created_at->format('d.m. H:i'), + 'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message, + 'conflicts' => $log->conflicts ?: '', + ])->all()) + ->table([ + TableColumn::make('Zeit'), + TableColumn::make('Ergebnis'), + TableColumn::make('Konflikte'), + ]) + ->schema([ + TextEntry::make('time'), + TextEntry::make('result'), + TextEntry::make('conflicts'), + ]), + ]), + EditAction::make(), + DeleteAction::make(), + ]); + } +} diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php new file mode 100644 index 0000000..525d036 --- /dev/null +++ b/app/Http/Controllers/ChannelController.php @@ -0,0 +1,68 @@ +where('export_token', $token)->where('is_active', true)->firstOrFail(); + + return response($feed->build($channel), 200, [ + 'Content-Type' => 'text/calendar; charset=utf-8', + 'Content-Disposition' => 'inline; filename="belegung.ics"', + 'Cache-Control' => 'no-cache, max-age=0', + ]); + } + + public function health(Request $request): JsonResponse + { + $token = config('fewo.channels.health_token'); + abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404); + + $channels = Channel::query()->active()->get()->map(fn (Channel $channel): array => [ + 'name' => $channel->name, + 'imports' => $channel->importsOccupations(), + 'ok' => ! $channel->isStale(), + 'last_success_at' => $channel->last_success_at?->toIso8601String(), + 'last_error' => $channel->last_error, + ]); + $openTasks = ChannelTask::query()->open()->count(); + + $ok = $channels->every(fn (array $channel): bool => $channel['ok']); + + return response()->json([ + 'status' => $ok ? 'ok' : 'degraded', + 'open_tasks' => $openTasks, + 'channels' => $channels->values(), + ], $ok ? 200 : 503); + } + + /** + * The automation reports a task as done. The raw body must be signed like the outgoing webhook. + */ + public function completeTask(Request $request, ChannelTask $task): JsonResponse + { + $secret = config('fewo.automation.secret'); + $signature = (string) $request->header('X-Signature'); + abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403); + + if ($task->status === ChannelTaskStatus::Open) { + $task->complete('Automatisierung'); + } + + return response()->json(['status' => $task->status->value]); + } +} diff --git a/app/Livewire/BookingRequest.php b/app/Livewire/BookingRequest.php index 7ff7a31..a0332fe 100644 --- a/app/Livewire/BookingRequest.php +++ b/app/Livewire/BookingRequest.php @@ -5,6 +5,7 @@ use App\Actions\CreateReservation; use App\Actions\RequestMarketingConsent; use App\Availability\AvailabilityChecker; +use App\Enums\ReferralSource; use App\Exceptions\ReservationException; use App\Models\Booking; use App\Models\Extra; @@ -17,6 +18,7 @@ use Illuminate\Contracts\View\View; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\RateLimiter; +use Illuminate\Validation\Rule; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Component; @@ -66,6 +68,12 @@ class BookingRequest extends Component /** Optional opt-in for offer e-mails (confirmed by double opt-in). */ public bool $marketingOptIn = false; + public string $referralSource = ''; + + /** @var array{utm_source?: string, utm_medium?: string, utm_campaign?: string} UTM parameters of the landing URL */ + #[Locked] + public array $utm = []; + /** Honeypot, must stay empty. */ public string $website = ''; @@ -76,6 +84,10 @@ public function mount(?Property $property = null): void { $this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id; $this->month = CarbonImmutable::today()->format('Y-m'); + $this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign'])) + ->filter(fn ($value): bool => is_string($value) && $value !== '') + ->map(fn (string $value): string => mb_substr($value, 0, 100)) + ->all(); } #[Computed] @@ -228,6 +240,7 @@ public function submit(CreateReservation $createReservation): void 'city' => $this->city ?: null, ], $this->message ?: null, + attribution: [...$this->utm, 'referral_source' => $this->referralSource ?: null], ); } catch (QuoteException|ReservationException $exception) { $this->addError('arrival', $exception->getMessage()); @@ -262,6 +275,7 @@ protected function rules(): array 'postalCode' => ['nullable', 'string', 'max:20'], 'city' => ['nullable', 'string', 'max:255'], 'message' => ['nullable', 'string', 'max:5000'], + 'referralSource' => ['nullable', Rule::enum(ReferralSource::class)], 'privacyAccepted' => ['accepted'], ]; } diff --git a/app/Mail/ChannelConflict.php b/app/Mail/ChannelConflict.php new file mode 100644 index 0000000..29b3da4 --- /dev/null +++ b/app/Mail/ChannelConflict.php @@ -0,0 +1,35 @@ + $conflicts */ + public function __construct(public Channel $channel, public array $conflicts) {} + + public function envelope(): Envelope + { + return new Envelope( + subject: 'Achtung: mögliche Doppelbuchung über '.$this->channel->name, + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.channel-conflict', + ); + } +} diff --git a/app/Mail/ChannelSyncAlert.php b/app/Mail/ChannelSyncAlert.php new file mode 100644 index 0000000..a02b7db --- /dev/null +++ b/app/Mail/ChannelSyncAlert.php @@ -0,0 +1,34 @@ +channel->name, + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.channel-sync-alert', + ); + } +} diff --git a/app/Mail/ChannelTasksNotification.php b/app/Mail/ChannelTasksNotification.php new file mode 100644 index 0000000..dac470e --- /dev/null +++ b/app/Mail/ChannelTasksNotification.php @@ -0,0 +1,35 @@ + $tasks */ + public function __construct(public array $tasks, public bool $reminder = false) {} + + public function envelope(): Envelope + { + return new Envelope( + subject: ($this->reminder ? 'Erinnerung: ' : '').count($this->tasks).' Kalender-Aufgabe(n) auf Portalen', + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.channel-tasks', + ); + } +} diff --git a/app/Models/BlockedPeriod.php b/app/Models/BlockedPeriod.php index 75984be..3e7185f 100644 --- a/app/Models/BlockedPeriod.php +++ b/app/Models/BlockedPeriod.php @@ -2,9 +2,11 @@ namespace App\Models; +use App\Observers\BlockedPeriodObserver; use Carbon\CarbonInterface; use Database\Factories\BlockedPeriodFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\ObservedBy; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -15,7 +17,8 @@ * Dates that are not bookable (own use, maintenance, bookings from portals). * Like bookings, ends_on is the first free day again. */ -#[Fillable(['property_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])] +#[ObservedBy(BlockedPeriodObserver::class)] +#[Fillable(['property_id', 'channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])] class BlockedPeriod extends Model { /** @use HasFactory */ @@ -42,6 +45,14 @@ public function property(): BelongsTo return $this->belongsTo(Property::class); } + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } + /** * @param Builder $query * @return Builder diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 63db371..192378b 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -3,9 +3,12 @@ namespace App\Models; use App\Enums\BookingStatus; +use App\Enums\ReferralSource; +use App\Observers\BookingObserver; use Carbon\CarbonInterface; use Database\Factories\BookingFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\ObservedBy; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -17,11 +20,16 @@ * A reservation or booking. arrival is the first night, departure the day the guest leaves, * so a departure and the next arrival on the same day do not collide. */ +#[ObservedBy(BookingObserver::class)] #[Fillable([ 'property_id', 'guest_id', 'status', 'source', + 'referral_source', + 'utm_source', + 'utm_medium', + 'utm_campaign', 'arrival', 'departure', 'guests', @@ -59,6 +67,7 @@ protected function casts(): array { return [ 'status' => BookingStatus::class, + 'referral_source' => ReferralSource::class, 'arrival' => 'immutable_date', 'departure' => 'immutable_date', 'extras' => 'array', diff --git a/app/Models/Channel.php b/app/Models/Channel.php new file mode 100644 index 0000000..fdcad9d --- /dev/null +++ b/app/Models/Channel.php @@ -0,0 +1,123 @@ + */ + use HasFactory; + + protected static function booted(): void + { + static::creating(function (Channel $channel): void { + $channel->export_token ??= Str::random(48); + }); + } + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'settings' => 'array', + 'is_active' => 'boolean', + 'requires_manual_blocking' => 'boolean', + 'last_synced_at' => 'immutable_datetime', + 'last_success_at' => 'immutable_datetime', + 'alerted_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function property(): BelongsTo + { + return $this->belongsTo(Property::class); + } + + /** + * @return HasMany + */ + public function blockedPeriods(): HasMany + { + return $this->hasMany(BlockedPeriod::class); + } + + /** + * @return HasMany + */ + public function syncLogs(): HasMany + { + return $this->hasMany(ChannelSyncLog::class)->latest('id'); + } + + /** + * @return HasMany + */ + public function tasks(): HasMany + { + return $this->hasMany(ChannelTask::class); + } + + /** + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function active(Builder $query): Builder + { + return $query->where('is_active', true); + } + + public function connector(): ChannelConnector + { + return app(ChannelRegistry::class)->resolve($this->connector); + } + + public function importsOccupations(): bool + { + return $this->is_active && $this->connector()->canImport($this); + } + + public function exportUrl(): string + { + return route('channels.feed', ['token' => $this->export_token]); + } + + public function setting(string $key): mixed + { + return $this->settings[$key] ?? null; + } + + /** + * The import is considered stale when no successful sync happened within the threshold. + */ + public function isStale(): bool + { + return $this->importsOccupations() + && ($this->last_success_at === null || $this->last_success_at->lessThan(now()->subMinutes(config('fewo.channels.stale_after_minutes')))); + } +} diff --git a/app/Models/ChannelSyncLog.php b/app/Models/ChannelSyncLog.php new file mode 100644 index 0000000..16d56ab --- /dev/null +++ b/app/Models/ChannelSyncLog.php @@ -0,0 +1,34 @@ + + */ + protected function casts(): array + { + return [ + 'successful' => 'boolean', + 'created_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } +} diff --git a/app/Models/ChannelTask.php b/app/Models/ChannelTask.php new file mode 100644 index 0000000..6898ed6 --- /dev/null +++ b/app/Models/ChannelTask.php @@ -0,0 +1,77 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'action' => ChannelTaskAction::class, + 'status' => ChannelTaskStatus::class, + 'starts_on' => 'immutable_date', + 'ends_on' => 'immutable_date', + 'completed_at' => 'immutable_datetime', + 'reminded_at' => 'immutable_datetime', + 'automation_sent_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } + + /** + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function open(Builder $query): Builder + { + return $query->where('status', ChannelTaskStatus::Open); + } + + public function complete(string $completedBy): void + { + $this->update([ + 'status' => ChannelTaskStatus::Done, + 'completed_by' => $completedBy, + 'completed_at' => now(), + ]); + } + + /** + * Human readable period, e.g. "14.06.2027 – 21.06.2027". + */ + public function period(): string + { + return $this->starts_on->format('d.m.Y').' – '.$this->ends_on->format('d.m.Y'); + } +} diff --git a/app/Models/Property.php b/app/Models/Property.php index 79c064e..68d95da 100644 --- a/app/Models/Property.php +++ b/app/Models/Property.php @@ -69,6 +69,14 @@ public function blockedPeriods(): HasMany return $this->hasMany(BlockedPeriod::class)->orderBy('starts_on'); } + /** + * @return HasMany + */ + public function channels(): HasMany + { + return $this->hasMany(Channel::class); + } + /** * @return HasMany */ diff --git a/app/Observers/BlockedPeriodObserver.php b/app/Observers/BlockedPeriodObserver.php new file mode 100644 index 0000000..c937b0c --- /dev/null +++ b/app/Observers/BlockedPeriodObserver.php @@ -0,0 +1,45 @@ +tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block); + } + + public function updated(BlockedPeriod $block): void + { + if (! $block->wasChanged(['starts_on', 'ends_on'])) { + return; + } + + $this->tasks($block, CarbonImmutable::parse($block->getOriginal('starts_on')), CarbonImmutable::parse($block->getOriginal('ends_on')), ChannelTaskAction::Unblock); + $this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block); + } + + public function deleted(BlockedPeriod $block): void + { + $this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Unblock); + } + + private function tasks(BlockedPeriod $block, CarbonImmutable $startsOn, CarbonImmutable $endsOn, ChannelTaskAction $action): void + { + $reason = $block->channel ? "Belegung über {$block->channel->name}" : 'Sperrzeit'.($block->reason ? ": {$block->reason}" : ''); + + $this->createChannelTasks->handle($block->property, $startsOn, $endsOn, $action, $reason, $block->channel_id); + } +} diff --git a/app/Observers/BookingObserver.php b/app/Observers/BookingObserver.php new file mode 100644 index 0000000..13a2788 --- /dev/null +++ b/app/Observers/BookingObserver.php @@ -0,0 +1,52 @@ +occupies($booking->status)) { + $this->tasks($booking, ChannelTaskAction::Block); + } + } + + public function updated(Booking $booking): void + { + if (! $booking->wasChanged('status')) { + return; + } + + $before = $this->occupies($booking->getOriginal('status')); + $after = $this->occupies($booking->status); + + if (! $before && $after) { + $this->tasks($booking, ChannelTaskAction::Block); + } elseif ($before && ! $after) { + $this->tasks($booking, ChannelTaskAction::Unblock); + } + } + + private function occupies(BookingStatus|string|null $status): bool + { + $status = is_string($status) ? BookingStatus::tryFrom($status) : $status; + + return in_array($status, BookingStatus::occupying(), true); + } + + private function tasks(Booking $booking, ChannelTaskAction $action): void + { + $this->createChannelTasks->handle($booking->property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}"); + } +} diff --git a/app/Policies/ChannelTaskPolicy.php b/app/Policies/ChannelTaskPolicy.php new file mode 100644 index 0000000..1180e30 --- /dev/null +++ b/app/Policies/ChannelTaskPolicy.php @@ -0,0 +1,13 @@ + [ + ICalConnector::class, + ], + + /* + | Suffix of the UIDs in our own feeds. Events carrying it that come back + | from a portal are echoes of our own export and are ignored on import. + */ + 'uid_suffix' => '@fewo-stommer', + +]; diff --git a/config/fewo.php b/config/fewo.php index 970cf75..4497f1b 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -46,4 +46,28 @@ */ 'guest_retention_years' => (int) env('FEWO_GUEST_RETENTION_YEARS', 10), + /* + |-------------------------------------------------------------------------- + | Portal synchronisation + |-------------------------------------------------------------------------- + */ + + 'channels' => [ + // An import without success for this long triggers an alert. + 'stale_after_minutes' => (int) env('FEWO_CHANNEL_STALE_AFTER_MINUTES', 60), + // Open manual blocking tasks are reminded after this time. + 'task_reminder_after_minutes' => (int) env('FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES', 120), + // Token for GET /health/sync (external monitoring, e.g. n8n). Empty = endpoint disabled. + 'health_token' => env('FEWO_HEALTH_TOKEN'), + ], + + /* + | Optional external automation (e.g. a browser bot on a private server) that carries out + | manual blocking tasks. Tasks are POSTed signed with HMAC-SHA256 of the body. + */ + 'automation' => [ + 'webhook_url' => env('FEWO_AUTOMATION_WEBHOOK_URL'), + 'secret' => env('FEWO_AUTOMATION_SECRET'), + ], + ]; diff --git a/database/factories/ChannelFactory.php b/database/factories/ChannelFactory.php new file mode 100644 index 0000000..a46827f --- /dev/null +++ b/database/factories/ChannelFactory.php @@ -0,0 +1,30 @@ + + */ +class ChannelFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'property_id' => Property::factory(), + 'name' => fake()->randomElement(['FeWo-direkt', 'Ostseeklar', 'ferienundwohnen.de']), + 'connector' => 'ical', + 'settings' => ['import_url' => 'https://portal.example/ical/'.fake()->uuid().'.ics'], + 'is_active' => true, + 'requires_manual_blocking' => false, + ]; + } +} diff --git a/database/factories/ChannelTaskFactory.php b/database/factories/ChannelTaskFactory.php new file mode 100644 index 0000000..4a62376 --- /dev/null +++ b/database/factories/ChannelTaskFactory.php @@ -0,0 +1,32 @@ + + */ +class ChannelTaskFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'channel_id' => Channel::factory(), + 'action' => ChannelTaskAction::Block, + 'starts_on' => now()->addDays(30)->toDateString(), + 'ends_on' => now()->addDays(37)->toDateString(), + 'reason' => 'Buchung', + 'status' => ChannelTaskStatus::Open, + ]; + } +} diff --git a/database/migrations/2026_10_22_110339_create_channels_table.php b/database/migrations/2026_10_22_110339_create_channels_table.php new file mode 100644 index 0000000..f5f7e0d --- /dev/null +++ b/database/migrations/2026_10_22_110339_create_channels_table.php @@ -0,0 +1,39 @@ +id(); + $table->foreignId('property_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->string('connector'); + $table->json('settings')->nullable(); + $table->string('export_token', 64)->unique(); + $table->boolean('is_active')->default(true); + $table->boolean('requires_manual_blocking')->default(false); + $table->string('manage_url')->nullable(); + $table->dateTime('last_synced_at')->nullable(); + $table->dateTime('last_success_at')->nullable(); + $table->text('last_error')->nullable(); + $table->dateTime('alerted_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('channels'); + } +}; diff --git a/database/migrations/2026_10_22_110342_create_channel_sync_logs_table.php b/database/migrations/2026_10_22_110342_create_channel_sync_logs_table.php new file mode 100644 index 0000000..8676fdf --- /dev/null +++ b/database/migrations/2026_10_22_110342_create_channel_sync_logs_table.php @@ -0,0 +1,38 @@ +id(); + $table->foreignId('channel_id')->constrained()->cascadeOnDelete(); + $table->boolean('successful'); + $table->unsignedSmallInteger('events')->default(0); + $table->unsignedSmallInteger('added')->default(0); + $table->unsignedSmallInteger('changed')->default(0); + $table->unsignedSmallInteger('removed')->default(0); + $table->unsignedSmallInteger('conflicts')->default(0); + $table->text('message')->nullable(); + $table->unsignedInteger('duration_ms')->default(0); + $table->timestamp('created_at')->useCurrent(); + + $table->index(['channel_id', 'created_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('channel_sync_logs'); + } +}; diff --git a/database/migrations/2026_10_22_110344_create_channel_tasks_table.php b/database/migrations/2026_10_22_110344_create_channel_tasks_table.php new file mode 100644 index 0000000..5dfa753 --- /dev/null +++ b/database/migrations/2026_10_22_110344_create_channel_tasks_table.php @@ -0,0 +1,38 @@ +id(); + $table->foreignId('channel_id')->constrained()->cascadeOnDelete(); + $table->string('action'); + $table->date('starts_on'); + $table->date('ends_on'); + $table->string('reason'); + $table->string('status')->default('open')->index(); + $table->string('completed_by')->nullable(); + $table->dateTime('completed_at')->nullable(); + $table->dateTime('reminded_at')->nullable(); + $table->dateTime('automation_sent_at')->nullable(); + $table->text('automation_error')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('channel_tasks'); + } +}; diff --git a/database/migrations/2026_10_22_110346_add_channel_and_referral_fields.php b/database/migrations/2026_10_22_110346_add_channel_and_referral_fields.php new file mode 100644 index 0000000..d5e91d3 --- /dev/null +++ b/database/migrations/2026_10_22_110346_add_channel_and_referral_fields.php @@ -0,0 +1,41 @@ +foreignId('channel_id')->nullable()->after('property_id')->constrained()->cascadeOnDelete(); + $table->index(['channel_id', 'external_uid']); + }); + + Schema::table('bookings', function (Blueprint $table) { + $table->string('referral_source')->nullable()->after('source'); + $table->string('utm_source')->nullable()->after('referral_source'); + $table->string('utm_medium')->nullable()->after('utm_source'); + $table->string('utm_campaign')->nullable()->after('utm_medium'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('bookings', function (Blueprint $table) { + $table->dropColumn(['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']); + }); + + Schema::table('blocked_periods', function (Blueprint $table) { + $table->dropIndex(['channel_id', 'external_uid']); + $table->dropConstrainedForeignId('channel_id'); + }); + } +}; diff --git a/docs/PORTALE.md b/docs/PORTALE.md index 939d25f..883750e 100644 --- a/docs/PORTALE.md +++ b/docs/PORTALE.md @@ -89,6 +89,23 @@ ### Sofortbuchung bei FeWo-direkt – das eigentliche Risiko - Technisch machbar (z. B. Playwright), **nicht** auf Strato (kein Browser) – passender Ort: Ihr privater Server (FastAPI/n8n), angesteuert per Webhook aus unserem System. - **Risiken:** Nutzungsbedingungen verbieten automatisierten Zugriff häufig (für FeWo-direkt vor Umsetzung zu prüfen – die AGB-Seite war beim Abruf gesperrt); Kontosperre möglich; Zwei-Faktor-Anmeldung, Captchas und Oberflächenänderungen machen den Bot fehleranfällig. Deshalb nur mit Fehlerüberwachung und Rückfall auf Variante 1. +### AGB-Prüfung Automatisierung (Stand 22.10.2026) + +- **Vrbo-Vermieter-AGB (Host Terms, § 14):** Vermieter dürfen den Dienst und seine Datenbanken nicht „automatisiert oder manuell“ kopieren oder verwerten und Inhalte oder Gästekommunikation nicht mit „robots, spiders or other automatic instruments“ überwachen. Das Setzen von Sperren per Bot ist nicht wörtlich genannt, fällt aber in eine Grauzone; Folge eines Verstoßes kann die Sperrung des Kontos sein. +- **FeWo-direkt (deutsche AGB):** Abruf beim Prüfen gesperrt (HTTP 429) – bitte im Vermieterbereich die aktuellen Nutzungsbedingungen einsehen. +- **Bewertung:** Kein Bot für FeWo-direkt ohne schriftliche Zustimmung von FeWo-direkt. Die Schnittstelle für eine externe Automatisierung (signierter Webhook + Rückmeldung) ist trotzdem gebaut – für Portale, die Automatisierung erlauben, oder falls FeWo-direkt zustimmt. + +## 4b. Umsetzung im System + +- **Admin › Wohnung › Portale & Kanäle:** Portal anlegen, iCal-Adresse des Portals eintragen, unsere Export-Adresse ins Portal kopieren, „Zusätzlich von Hand sperren“ für Sofortbuchungsportale (FeWo-direkt) aktivieren und Link zum Vermieterkalender hinterlegen. +- **Abgleich** alle 5 Min. (`channels:sync`), Protokoll je Portal, „Jetzt abgleichen“ per Klick. +- **Konflikt-Mail** sofort bei Überschneidung einer neuen Portalbelegung mit einer bestehenden Belegung. +- **Störungs-Mail** einmal pro Störung, wenn ein Portal 60 Min. lang nicht abgeglichen werden konnte. +- **Portal-Aufgaben** (Admin › Vermietung › Portal-Aufgaben): entstehen automatisch bei Bestätigung/Stornierung von Buchungen, bei Sperrzeiten und bei Belegungen anderer Portale; Mail sofort, Erinnerung nach 2 Std. +- **Status für n8n:** `GET /health/sync?token=…` (200 = ok, 503 = gestört) mit offenen Aufgaben und Zustand je Portal. +- **Automatisierungs-Webhook (optional):** `FEWO_AUTOMATION_WEBHOOK_URL` + `FEWO_AUTOMATION_SECRET`; Aufgaben werden als JSON mit `X-Signature` (HMAC-SHA256) gesendet, Erledigung per signiertem POST an die mitgelieferte `callback_url`. +- **Herkunft** jeder Anfrage („Wie sind Sie auf uns aufmerksam geworden?“ + UTM-Parameter) wird an der Buchung gespeichert. + ## 5. Offene Fragen an die Anbieter - **Tourist-Info / DS:** Provision und Gebühren in Kühlungsborn? Ist Online-Buchung Pflicht für den Verzeichniseintrag? Welche Channel-Manager sind zugelassen? @@ -112,4 +129,5 @@ ## Quellen - feratel / Channel-Manager: [Smoobu ↔ feratel Deskline](https://support.smoobu.com/hc/en-us/articles/360020483459-How-to-connect-Feratel-Deskline), [Beds24 ↔ feratel](https://wiki.beds24.com/wikiDE/index.php/Feratel), [Smoobu ↔ Ostsee-Ferienwohnungen.de/BestFewo](https://support.smoobu.com/hc/en-us/articles/5600409673490-How-do-I-connect-Optimale-Pr%C3%A4sentation-BestFewo-Ostsee-Ferienwohnungen-de-and-Secra-to-Smoobu) - Ostseeklar: [Vermieter-Info](https://www.ostseeklar.de/vermieter.php), [Feondi-Schnittstelle Ostseeklar](https://www.fewo-verwalter.de/service/schnittstellen-beschreibung/schnittstelle-ostseeklar-de.html) - Weitere: [Holidu iCal](https://www.holidu.com/help/host/managing-your-listings/how-do-i-configure-an-icalsync-to-connect-my-calendar-with-other-platforms), [Channel-Manager-Vergleich 2026](https://www.oasify.de/ratgeber/channel-manager-ferienwohnung-vergleich), [Doppelbuchungsrisiko iCal](https://www.almenrausch.at/magazin/detail/doppelbuchung-in-der-ferienwohnung/) +- Vrbo-AGB: [Host Terms](https://www.vrbo.com/en-ca/lp/b/host-terms-notice), [Guest Terms](https://www.vrbo.com/lp/b/terms-of-service) - Channel-Manager & Vrbo: [Smoobu ↔ Vrbo/FeWo-direkt per iCal](https://support.smoobu.com/hc/en-us/articles/360018462060-Connect-Vrbo-FeWo-direkt-to-Smoobu-by-iCal), [Smoobu Preise](https://support.smoobu.com/hc/en-us/articles/360003170680-How-much-does-Smoobu-cost-Plans-and-pricing-explained), [Smoobu API](https://docs.smoobu.com/), [Smoobu Webhooks](https://support.smoobu.com/hc/en-us/articles/360003170740-Use-the-Smoobu-API-get-an-API-key-set-up-webhooks-and-sign-your-requests), [Beds24 Preise](https://www.beds24.com/pricing.html), [Beds24 VRBO Setup](https://wiki.beds24.com/index.php/VRBO_Setup), [Beds24 API V2](https://wiki.beds24.com/index.php/Category:API_V2), [Beds24 Webhooks](https://wiki.beds24.com/index.php/Booking_Webhooks), [Lodgify Vrbo-Anbindung](https://help.lodgify.com/hc/en-us/articles/21094192692380), [Host Port: Vrbo-Anbindung](https://hostport.co/blog/best-channel-managers-vrbo), [Vrbo-Partnerprogramme](https://www.rentalscaleup.com/airbnb-vrbo-and-booking-software-partner-programs-how-to-qualify-and-should-property-managers-care/), [Smoobu Erfahrungen (Capterra)](https://www.capterra.com.de/software/160106/smoobu), [Trustpilot](https://at.trustpilot.com/review/smoobu.com?page=10), [Hostradar-Test](https://hostradar.eu/en/reviews/smoobu/), [BGH I ZR 224/12 (Screen Scraping)](https://gesetze.co/urteile/I_ZR_224-12) diff --git a/resources/views/livewire/booking-request.blade.php b/resources/views/livewire/booking-request.blade.php index 0863891..e4bcddb 100644 --- a/resources/views/livewire/booking-request.blade.php +++ b/resources/views/livewire/booking-request.blade.php @@ -181,6 +181,16 @@ class="mt-1 w-full rounded-lg border-slate-300"> @endforeach + +