Portal-Synchronisation: unser System führt
- Connector-System (app/Channels, config/channels.php) mit iCal-Connector, robustem Parser und Export-Feed je Portal (ohne eigene Belegungen, ohne Gästedaten) - Abgleich alle 5 Min. mit Protokoll, Echo-Erkennung, Konflikt-Mail bei möglicher Doppelbuchung - Überwachung: Störungs-Mail, Status-Endpunkt /health/sync für n8n - Portal-Aufgaben für Sofortbuchungsportale (FeWo-direkt): automatisch aus Buchungen/Sperren/anderen Portalen, Mail + Erinnerung, Abhaken im Admin - Optionaler signierter Automatisierungs-Webhook mit Rückmeldung - Herkunftsmessung: Abfrage im Formular + UTM-Parameter - Portal-Analyse: AGB-Prüfung Automatisierung, Umsetzungsbeschreibung Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a8e72715ab
commit
0b7205e050
55 files changed
+2290
-3
No files matched your search
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Creates blocking/unblocking tasks for every portal that must be maintained by hand
|
||||
* (e.g. instant booking portals whose calendar import is too slow), notifies the landlord
|
||||
* and hands the task to an optional external automation.
|
||||
*/
|
||||
class CreateChannelTasks
|
||||
{
|
||||
/**
|
||||
* @return list<ChannelTask>
|
||||
*/
|
||||
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()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Mail\ChannelSyncAlert;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Alerts the landlord once per incident when a portal import fails or has not succeeded for too long.
|
||||
* The alert is reset by the next successful sync.
|
||||
*/
|
||||
class MonitorChannels
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$channels = Channel::query()->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
|
||||
*/
|
||||
class RemindChannelTasks
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$tasks = ChannelTask::query()
|
||||
->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
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 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()->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<string>
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Resolves the connectors registered in config/channels.php.
|
||||
*/
|
||||
class ChannelRegistry
|
||||
{
|
||||
/**
|
||||
* @return array<string, class-string<ChannelConnector>>
|
||||
*/
|
||||
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<string, string>
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
return array_map(fn (string $class): string => $class::label(), $this->connectors());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ChannelSyncException extends RuntimeException {}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Contracts;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Models\Channel;
|
||||
use Filament\Schemas\Components\Component;
|
||||
|
||||
/**
|
||||
* Connects one kind of portal or channel manager. Register implementations in config/channels.php.
|
||||
*/
|
||||
interface ChannelConnector
|
||||
{
|
||||
/**
|
||||
* Stable identifier stored on the channel, e.g. "ical".
|
||||
*/
|
||||
public static function key(): string;
|
||||
|
||||
public static function label(): string;
|
||||
|
||||
/**
|
||||
* Admin form fields for the connector's settings; use state paths below "settings.".
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
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<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetchOccupations(Channel $channel): array;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An occupation reported by a portal: nights from startsOn up to (excluding) endsOn.
|
||||
*/
|
||||
final readonly class ExternalPeriod
|
||||
{
|
||||
public function __construct(
|
||||
public string $uid,
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use App\Models\Channel;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
/**
|
||||
* Generic calendar connection that works with almost every portal: we read the portal's iCal export
|
||||
* and the portal reads our feed for this channel.
|
||||
*/
|
||||
class ICalConnector implements ChannelConnector
|
||||
{
|
||||
public function __construct(private ICalParser $parser) {}
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'ical';
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Kalender-Abgleich (iCal)';
|
||||
}
|
||||
|
||||
public static function settingsSchema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('settings.import_url')
|
||||
->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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
|
||||
/**
|
||||
* The calendar a portal imports from us: every occupation of the property except the ones that
|
||||
* came from this very portal (otherwise the portal would block its own bookings twice).
|
||||
* Events carry no guest data.
|
||||
*/
|
||||
class ICalFeed
|
||||
{
|
||||
public function build(Channel $channel): string
|
||||
{
|
||||
$property = $channel->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Minimal RFC 5545 reader for availability feeds: VEVENTs with DTSTART/DTEND (date or date-time),
|
||||
* UID and SUMMARY. Cancelled events and events without a positive length are skipped.
|
||||
*/
|
||||
class ICalParser
|
||||
{
|
||||
/**
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @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<string, array{value: string, params: list<string>}> $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<string>} $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<string> $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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:sync {channel? : ID of a single channel}')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(SyncChannel $syncChannel): int
|
||||
{
|
||||
$channels = Channel::query()->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskAction: string implements HasColor, HasLabel
|
||||
{
|
||||
case Block = 'block';
|
||||
case Unblock = 'unblock';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'Sperren',
|
||||
self::Unblock => 'Freigeben',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'danger',
|
||||
self::Unblock => 'success',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
case Open = 'open';
|
||||
case Done = 'done';
|
||||
case Dismissed = 'dismissed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'Offen',
|
||||
self::Done => 'Erledigt',
|
||||
self::Dismissed => 'Verworfen',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'warning',
|
||||
self::Done => 'success',
|
||||
self::Dismissed => 'gray',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* "How did you find us?" – answered by the guest in the request form.
|
||||
*/
|
||||
enum ReferralSource: string implements HasLabel
|
||||
{
|
||||
case SearchEngine = 'search_engine';
|
||||
case FewoDirekt = 'fewo_direkt';
|
||||
case Ostseeklar = 'ostseeklar';
|
||||
case FerienUndWohnen = 'ferienundwohnen';
|
||||
case TouristInformation = 'tourist_information';
|
||||
case SocialMedia = 'social_media';
|
||||
case Recommendation = 'recommendation';
|
||||
case ReturningGuest = 'returning_guest';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SearchEngine => '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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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([
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks;
|
||||
|
||||
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
|
||||
use App\Filament\Resources\ChannelTasks\Tables\ChannelTasksTable;
|
||||
use App\Models\ChannelTask;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class ChannelTaskResource extends Resource
|
||||
{
|
||||
protected static ?string $model = ChannelTask::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal-Aufgabe';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portal-Aufgaben';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ChannelTasksTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$open = ChannelTask::query()->open()->count();
|
||||
|
||||
return $open > 0 ? (string) $open : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListChannelTasks::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Pages;
|
||||
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListChannelTasks extends ListRecords
|
||||
{
|
||||
protected static string $resource = ChannelTaskResource::class;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Tables;
|
||||
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\ChannelTask;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelTasksTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->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])),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'channels';
|
||||
|
||||
protected static ?string $title = 'Portale & Kanäle';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portale';
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$registry = app(ChannelRegistry::class);
|
||||
|
||||
return $schema
|
||||
->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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
/**
|
||||
* Public endpoints of the channel synchronisation: export feeds for portals, the health check for
|
||||
* external monitoring and the callback of the optional blocking automation.
|
||||
*/
|
||||
class ChannelController extends Controller
|
||||
{
|
||||
public function feed(string $token, ICalFeed $feed): Response
|
||||
{
|
||||
$channel = Channel::query()->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]);
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Reports overlaps between a newly imported portal occupation and occupations from elsewhere.
|
||||
*/
|
||||
class ChannelConflict extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/** @param list<string> $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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Alerts the landlord that a portal import fails or is outdated.
|
||||
*/
|
||||
class ChannelSyncAlert extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Channel $channel) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Kalender-Abgleich gestört: '.$this->channel->name,
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.channel-sync-alert',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Lists portal calendars that have to be blocked or released by hand.
|
||||
*/
|
||||
class ChannelTasksNotification extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/** @param list<ChannelTask> $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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<BlockedPeriodFactory> */
|
||||
@@ -42,6 +45,14 @@ public function property(): BelongsTo
|
||||
return $this->belongsTo(Property::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use Database\Factories\ChannelFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
|
||||
* channel and every channel gets its own export feed without its own occupations.
|
||||
*/
|
||||
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url'])]
|
||||
#[Hidden(['export_token'])]
|
||||
class Channel extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelFactory> */
|
||||
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<string, string>
|
||||
*/
|
||||
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<Property, $this>
|
||||
*/
|
||||
public function property(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Property::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BlockedPeriod, $this>
|
||||
*/
|
||||
public function blockedPeriods(): HasMany
|
||||
{
|
||||
return $this->hasMany(BlockedPeriod::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<ChannelSyncLog, $this>
|
||||
*/
|
||||
public function syncLogs(): HasMany
|
||||
{
|
||||
return $this->hasMany(ChannelSyncLog::class)->latest('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<ChannelTask, $this>
|
||||
*/
|
||||
public function tasks(): HasMany
|
||||
{
|
||||
return $this->hasMany(ChannelTask::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Channel> $query
|
||||
* @return Builder<Channel>
|
||||
*/
|
||||
#[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'))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
|
||||
class ChannelSyncLog extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'successful' => 'boolean',
|
||||
'created_at' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use Database\Factories\ChannelTaskFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A change that has to be made by hand (or by an external automation) on a portal that
|
||||
* cannot be kept in sync fast enough by calendar feeds, e.g. because of instant booking.
|
||||
*/
|
||||
#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error'])]
|
||||
class ChannelTask extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelTaskFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<ChannelTask> $query
|
||||
* @return Builder<ChannelTask>
|
||||
*/
|
||||
#[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');
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,14 @@ public function blockedPeriods(): HasMany
|
||||
return $this->hasMany(BlockedPeriod::class)->orderBy('starts_on');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Channel, $this>
|
||||
*/
|
||||
public function channels(): HasMany
|
||||
{
|
||||
return $this->hasMany(Channel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Amenity, $this>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Actions\CreateChannelTasks;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Models\BlockedPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
|
||||
|
||||
/**
|
||||
* Manual blocks and occupations imported from one portal must also reach the manually maintained
|
||||
* portals – except the portal they came from.
|
||||
*/
|
||||
class BlockedPeriodObserver implements ShouldHandleEventsAfterCommit
|
||||
{
|
||||
public function __construct(private CreateChannelTasks $createChannelTasks) {}
|
||||
|
||||
public function created(BlockedPeriod $block): void
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Actions\CreateChannelTasks;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
|
||||
|
||||
/**
|
||||
* Keeps manually maintained portals in step when a booking starts or stops occupying the calendar.
|
||||
*/
|
||||
class BookingObserver implements ShouldHandleEventsAfterCommit
|
||||
{
|
||||
public function __construct(private CreateChannelTasks $createChannelTasks) {}
|
||||
|
||||
public function created(Booking $booking): void
|
||||
{
|
||||
if ($this->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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
|
||||
class ChannelTaskPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
{
|
||||
return [UserRole::Rentals];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user