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
@@ -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=
|
||||
@@ -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`.
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use App\Channels\ICal\ICalConnector;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Channel connectors
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Every portal is connected through a connector. New connectors (e.g. a
|
||||
| channel manager API) implement App\Channels\Contracts\ChannelConnector
|
||||
| and are registered here; they then appear in the admin automatically.
|
||||
|
|
||||
*/
|
||||
|
||||
'connectors' => [
|
||||
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',
|
||||
|
||||
];
|
||||
@@ -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'),
|
||||
],
|
||||
|
||||
];
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* @extends Factory<Channel>
|
||||
*/
|
||||
class ChannelFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* @extends Factory<ChannelTask>
|
||||
*/
|
||||
class ChannelTaskFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('channels', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('channel_sync_logs', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('channel_tasks', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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)
|
||||
@@ -181,6 +181,16 @@ class="mt-1 w-full rounded-lg border-slate-300">
|
||||
@endforeach
|
||||
</div>
|
||||
|
||||
<label class="mt-4 block text-sm">
|
||||
<span class="font-medium text-slate-700">Wie sind Sie auf uns aufmerksam geworden?</span>
|
||||
<select wire:model="referralSource" class="mt-1 w-full rounded-lg border-slate-300">
|
||||
<option value="">Bitte wählen (optional)</option>
|
||||
@foreach (\App\Enums\ReferralSource::cases() as $source)
|
||||
<option value="{{ $source->value }}">{{ $source->getLabel() }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="mt-4 block text-sm">
|
||||
<span class="font-medium text-slate-700">Nachricht</span>
|
||||
<textarea wire:model="message" rows="3" class="mt-1 w-full rounded-lg border-slate-300"></textarea>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<x-mail::message>
|
||||
# Mögliche Doppelbuchung
|
||||
|
||||
Beim Kalender-Abgleich mit **{{ $channel->name }}** wurde eine neue Belegung gefunden, die sich mit einer bestehenden Belegung überschneidet:
|
||||
|
||||
@foreach ($conflicts as $conflict)
|
||||
- {{ $conflict }}
|
||||
@endforeach
|
||||
|
||||
Bitte prüfen Sie das umgehend im Portal und in der Verwaltung. Falls es sich um eine echte Doppelbuchung handelt, sollte einer der Gäste so früh wie möglich informiert werden.
|
||||
|
||||
<x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('index')">
|
||||
Buchungen öffnen
|
||||
</x-mail::button>
|
||||
</x-mail::message>
|
||||
@@ -0,0 +1,19 @@
|
||||
<x-mail::message>
|
||||
# Kalender-Abgleich gestört
|
||||
|
||||
Der Kalender von **{{ $channel->name }}** konnte seit
|
||||
@if ($channel->last_success_at)
|
||||
{{ $channel->last_success_at->format('d.m.Y, H:i') }} Uhr
|
||||
@else
|
||||
der Einrichtung
|
||||
@endif
|
||||
nicht mehr erfolgreich abgeglichen werden. Neue Buchungen über dieses Portal werden bis dahin **nicht** im Kalender gesperrt.
|
||||
|
||||
@if ($channel->last_error)
|
||||
**Letzte Fehlermeldung:** {{ $channel->last_error }}
|
||||
@endif
|
||||
|
||||
Häufige Ursachen: Die iCal-Adresse des Portals hat sich geändert, das Portal ist vorübergehend nicht erreichbar, oder das Inserat wurde deaktiviert.
|
||||
|
||||
Sobald der Abgleich wieder funktioniert, ist keine weitere Aktion nötig.
|
||||
</x-mail::message>
|
||||
@@ -0,0 +1,18 @@
|
||||
<x-mail::message>
|
||||
# {{ $reminder ? 'Noch offen: ' : '' }}Bitte Portal-Kalender anpassen
|
||||
|
||||
@if ($reminder)
|
||||
Diese Aufgaben sind noch nicht erledigt. Solange sie offen sind, kann über das Portal eine Doppelbuchung entstehen.
|
||||
@else
|
||||
Die Belegung hat sich geändert. Diese Portale werden von Hand gepflegt (z. B. wegen Sofortbuchung):
|
||||
@endif
|
||||
|
||||
@foreach ($tasks as $task)
|
||||
- **{{ $task->channel->name }}: {{ $task->action->getLabel() }}** {{ $task->period() }} – {{ $task->reason }}@if ($task->channel->manage_url) · [Kalender öffnen]({{ $task->channel->manage_url }})@endif
|
||||
|
||||
@endforeach
|
||||
|
||||
<x-mail::button :url="\App\Filament\Resources\ChannelTasks\ChannelTaskResource::getUrl('index')">
|
||||
Aufgaben abhaken
|
||||
</x-mail::button>
|
||||
</x-mail::message>
|
||||
@@ -1,11 +1,25 @@
|
||||
<?php
|
||||
|
||||
use App\Actions\AnonymizeGuests;
|
||||
use App\Actions\MonitorChannels;
|
||||
use App\Actions\RemindChannelTasks;
|
||||
use App\Actions\RequestReviews;
|
||||
use Illuminate\Support\Facades\Schedule;
|
||||
|
||||
Schedule::command('bookings:expire-holds')->everyFiveMinutes()->withoutOverlapping();
|
||||
|
||||
Schedule::command('channels:sync')->everyFiveMinutes()->withoutOverlapping(10);
|
||||
|
||||
Schedule::call(fn (MonitorChannels $monitorChannels) => $monitorChannels->handle())
|
||||
->name('channels:monitor')
|
||||
->everyFifteenMinutes()
|
||||
->withoutOverlapping();
|
||||
|
||||
Schedule::call(fn (RemindChannelTasks $remindChannelTasks) => $remindChannelTasks->handle())
|
||||
->name('channels:remind-tasks')
|
||||
->everyFifteenMinutes()
|
||||
->withoutOverlapping();
|
||||
|
||||
Schedule::call(fn (RequestReviews $requestReviews) => $requestReviews->handle())
|
||||
->name('reviews:request')
|
||||
->dailyAt('10:00')
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\ChannelController;
|
||||
use App\Http\Controllers\MarketingConsentController;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('/', function () {
|
||||
@@ -15,3 +17,10 @@
|
||||
Route::get('/angebote/bestaetigen/{guest}', [MarketingConsentController::class, 'confirm'])->name('marketing.confirm');
|
||||
Route::get('/angebote/abmelden/{guest}', [MarketingConsentController::class, 'unsubscribe'])->name('marketing.unsubscribe');
|
||||
});
|
||||
|
||||
Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1');
|
||||
Route::get('/health/sync', [ChannelController::class, 'health'])->name('health.sync');
|
||||
Route::post('/automation/aufgaben/{task}/erledigt', [ChannelController::class, 'completeTask'])
|
||||
->name('channel-tasks.complete')
|
||||
->withoutMiddleware(PreventRequestForgery::class)
|
||||
->middleware('throttle:30,1');
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\MonitorChannels;
|
||||
use App\Actions\RemindChannelTasks;
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
|
||||
use App\Livewire\BookingRequest;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\ChannelSyncAlert;
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\Testing\TestAction;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Client\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ChannelSyncTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Property $property;
|
||||
|
||||
/** Response of every faked HTTP request; replaced per test step. */
|
||||
private mixed $httpResponse = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
|
||||
$this->seed(PropertySeeder::class);
|
||||
$this->property = Property::sole();
|
||||
Mail::fake();
|
||||
Http::fake(fn () => $this->httpResponse);
|
||||
}
|
||||
|
||||
public function test_parser_reads_dates_datetimes_folded_lines_and_skips_cancelled_events(): void
|
||||
{
|
||||
$ics = implode("\r\n", [
|
||||
'BEGIN:VCALENDAR',
|
||||
'BEGIN:VEVENT', 'UID:a1', 'DTSTART;VALUE=DATE:20261107', 'DTEND;VALUE=DATE:20261110', 'SUMMARY:Reserviert \, Familie', 'END:VEVENT',
|
||||
'BEGIN:VEVENT', 'UID:a2', 'DTSTART;TZID=Europe/Berlin:20261201T160000', 'DTEND;TZID=Europe/Berlin:20261205T100000', 'END:VEVENT',
|
||||
'BEGIN:VEVENT', 'UID:a3-very-long-uid-that-is-', ' folded', 'DTSTART:20261231T230000Z', 'DTEND:20270102T090000Z', 'END:VEVENT',
|
||||
'BEGIN:VEVENT', 'UID:a4', 'STATUS:CANCELLED', 'DTSTART;VALUE=DATE:20261115', 'DTEND;VALUE=DATE:20261118', 'END:VEVENT',
|
||||
'BEGIN:VEVENT', 'UID:a5', 'DTSTART;VALUE=DATE:20261120', 'END:VEVENT',
|
||||
'END:VCALENDAR',
|
||||
]);
|
||||
|
||||
$periods = (new ICalParser)->parse($ics);
|
||||
|
||||
$this->assertSame(
|
||||
[['a1', '2026-11-07', '2026-11-10'], ['a2', '2026-12-01', '2026-12-05'], ['a3-very-long-uid-that-is-folded', '2027-01-01', '2027-01-02'], ['a5', '2026-11-20', '2026-11-21']],
|
||||
array_map(fn ($period): array => [$period->uid, $period->startsOn->toDateString(), $period->endsOn->toDateString()], $periods),
|
||||
);
|
||||
$this->assertSame('Reserviert , Familie', $periods[0]->summary);
|
||||
}
|
||||
|
||||
public function test_parser_rejects_non_calendar_responses(): void
|
||||
{
|
||||
$this->expectException(ChannelSyncException::class);
|
||||
|
||||
(new ICalParser)->parse('<html>Login</html>');
|
||||
}
|
||||
|
||||
public function test_sync_adds_changes_and_removes_imported_occupations(): void
|
||||
{
|
||||
$channel = $this->channel('FeWo-direkt');
|
||||
|
||||
$this->fakeFeed([['x1', '20261107', '20261110'], ['x2', '20261201', '20261208'], ['booking-5@fewo-stommer', '20261215', '20261220'], ['old', '20261001', '20261005']]);
|
||||
$first = (new SyncChannel)->handle($channel);
|
||||
|
||||
$this->assertTrue($first->successful);
|
||||
$this->assertSame([2, 2, 0, 0], [$first->events, $first->added, $first->changed, $first->removed]);
|
||||
$this->assertSame(['x1', 'x2'], $channel->blockedPeriods()->pluck('external_uid')->all());
|
||||
|
||||
$this->fakeFeed([['x1', '20261107', '20261111']]);
|
||||
$second = (new SyncChannel)->handle($channel);
|
||||
|
||||
$this->assertSame([0, 1, 1], [$second->added, $second->changed, $second->removed]);
|
||||
$this->assertSame('2026-11-11', $channel->blockedPeriods()->sole()->ends_on->toDateString());
|
||||
$this->assertNotNull($channel->fresh()->last_success_at);
|
||||
}
|
||||
|
||||
public function test_overlap_with_an_existing_booking_is_reported_as_possible_double_booking(): void
|
||||
{
|
||||
Booking::factory()->for($this->property)->create(['arrival' => '2026-11-08', 'departure' => '2026-11-12', 'status' => BookingStatus::Confirmed]);
|
||||
$channel = $this->channel('FeWo-direkt');
|
||||
$this->fakeFeed([['x1', '20261107', '20261110']]);
|
||||
|
||||
$log = (new SyncChannel)->handle($channel);
|
||||
|
||||
$this->assertSame(1, $log->conflicts);
|
||||
Mail::assertSent(ChannelConflict::class);
|
||||
}
|
||||
|
||||
public function test_failed_import_is_logged_and_alerted_once_until_it_works_again(): void
|
||||
{
|
||||
$channel = $this->channel('Ostseeklar');
|
||||
$this->httpResponse = Http::response('Server Error', 500);
|
||||
|
||||
$log = (new SyncChannel)->handle($channel);
|
||||
$this->assertFalse($log->successful);
|
||||
$this->assertNotNull($channel->fresh()->last_error);
|
||||
|
||||
$this->assertSame(1, (new MonitorChannels)->handle());
|
||||
$this->assertSame(0, (new MonitorChannels)->handle());
|
||||
Mail::assertSent(ChannelSyncAlert::class, 1);
|
||||
|
||||
$this->fakeFeed([]);
|
||||
(new SyncChannel)->handle($channel);
|
||||
$this->assertNull($channel->fresh()->alerted_at);
|
||||
}
|
||||
|
||||
public function test_export_feed_contains_all_occupations_except_the_channels_own(): void
|
||||
{
|
||||
$fewo = $this->channel('FeWo-direkt');
|
||||
$ostseeklar = $this->channel('Ostseeklar');
|
||||
$booking = Booking::factory()->for($this->property)->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10', 'status' => BookingStatus::Confirmed]);
|
||||
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
|
||||
BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $fewo->id, 'source' => 'channel', 'starts_on' => '2026-12-01', 'ends_on' => '2026-12-05']);
|
||||
BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $ostseeklar->id, 'source' => 'channel', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-12']);
|
||||
|
||||
$feed = $this->get($fewo->exportUrl())->assertOk()->assertHeader('Content-Type', 'text/calendar; charset=utf-8')->getContent();
|
||||
|
||||
$this->assertStringContainsString("UID:booking-{$booking->id}@fewo-stommer", $feed);
|
||||
$this->assertStringContainsString('DTSTART;VALUE=DATE:20261120', $feed);
|
||||
$this->assertStringContainsString('DTSTART;VALUE=DATE:20261210', $feed);
|
||||
$this->assertStringNotContainsString('DTSTART;VALUE=DATE:20261201', $feed);
|
||||
$this->assertStringNotContainsString($booking->guest->last_name, $feed);
|
||||
$this->get('/kalender/falsch.ics')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_manual_portals_get_tasks_when_occupations_change_elsewhere(): void
|
||||
{
|
||||
$fewo = $this->channel('FeWo-direkt', manual: true);
|
||||
$ostseeklar = $this->channel('Ostseeklar');
|
||||
|
||||
$booking = Booking::factory()->for($this->property)->reserved()->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']);
|
||||
$this->assertSame(0, ChannelTask::count(), 'holds do not create tasks');
|
||||
|
||||
$booking->update(['status' => BookingStatus::Confirmed]);
|
||||
$booking->update(['status' => BookingStatus::Cancelled]);
|
||||
|
||||
$this->fakeFeed([['ok1', '20261201', '20261205']]);
|
||||
(new SyncChannel)->handle($ostseeklar);
|
||||
|
||||
$this->fakeFeed([['fd1', '20261210', '20261212']]);
|
||||
(new SyncChannel)->handle($fewo);
|
||||
|
||||
$this->assertSame(
|
||||
[[ChannelTaskAction::Block, '2026-11-07'], [ChannelTaskAction::Unblock, '2026-11-07'], [ChannelTaskAction::Block, '2026-12-01']],
|
||||
$fewo->tasks()->orderBy('id')->get()->map(fn (ChannelTask $task): array => [$task->action, $task->starts_on->toDateString()])->all(),
|
||||
);
|
||||
$this->assertSame(0, $ostseeklar->tasks()->count());
|
||||
Mail::assertSent(ChannelTasksNotification::class, 3);
|
||||
}
|
||||
|
||||
public function test_open_tasks_are_reminded_once(): void
|
||||
{
|
||||
$task = ChannelTask::factory()->for($this->channel('FeWo-direkt', manual: true))->create();
|
||||
|
||||
$this->assertSame(0, (new RemindChannelTasks)->handle());
|
||||
$this->travel(3)->hours();
|
||||
$this->assertSame(1, (new RemindChannelTasks)->handle());
|
||||
$this->assertSame(0, (new RemindChannelTasks)->handle());
|
||||
|
||||
$this->assertNotNull($task->fresh()->reminded_at);
|
||||
}
|
||||
|
||||
public function test_tasks_are_sent_to_the_automation_and_completed_by_signed_callback(): void
|
||||
{
|
||||
config(['fewo.automation.webhook_url' => 'https://bot.example/tasks', 'fewo.automation.secret' => 'geheim']);
|
||||
$this->httpResponse = Http::response(['queued' => true]);
|
||||
$this->channel('FeWo-direkt', manual: true);
|
||||
|
||||
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
|
||||
|
||||
$task = ChannelTask::sole();
|
||||
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://bot.example/tasks'
|
||||
&& hash_equals(hash_hmac('sha256', $request->body(), 'geheim'), $request->header('X-Signature')[0])
|
||||
&& $request['action'] === 'block');
|
||||
$this->assertNotNull($task->fresh()->automation_sent_at);
|
||||
|
||||
$body = json_encode(['done' => true]);
|
||||
$this->call('POST', route('channel-tasks.complete', $task), [], [], [], ['HTTP_X-Signature' => 'falsch', 'CONTENT_TYPE' => 'application/json'], $body)->assertForbidden();
|
||||
$this->call('POST', route('channel-tasks.complete', $task), [], [], [], ['HTTP_X-Signature' => hash_hmac('sha256', $body, 'geheim'), 'CONTENT_TYPE' => 'application/json'], $body)->assertOk();
|
||||
|
||||
$this->assertSame([ChannelTaskStatus::Done, 'Automatisierung'], [$task->fresh()->status, $task->fresh()->completed_by]);
|
||||
}
|
||||
|
||||
public function test_health_endpoint_reports_sync_state_for_external_monitoring(): void
|
||||
{
|
||||
$this->get('/health/sync')->assertNotFound();
|
||||
config(['fewo.channels.health_token' => 'abc']);
|
||||
|
||||
$channel = $this->channel('FeWo-direkt');
|
||||
$this->getJson('/health/sync?token=abc')->assertStatus(503)->assertJsonPath('status', 'degraded');
|
||||
|
||||
$this->fakeFeed([]);
|
||||
(new SyncChannel)->handle($channel);
|
||||
$this->getJson('/health/sync?token=abc')->assertOk()->assertJsonPath('channels.0.ok', true);
|
||||
}
|
||||
|
||||
public function test_referral_and_utm_parameters_are_stored_with_the_request(): void
|
||||
{
|
||||
Livewire::withQueryParams(['utm_source' => 'instagram', 'utm_campaign' => 'herbst'])
|
||||
->test(BookingRequest::class)
|
||||
->set('arrival', '2026-11-07')
|
||||
->set('departure', '2026-11-10')
|
||||
->set('firstName', 'Anna')
|
||||
->set('lastName', 'Muster')
|
||||
->set('email', 'anna@example.com')
|
||||
->set('referralSource', 'social_media')
|
||||
->set('privacyAccepted', true)
|
||||
->call('submit')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$booking = Booking::sole();
|
||||
$this->assertSame(['social_media', 'instagram', 'herbst'], [$booking->referral_source->value, $booking->utm_source, $booking->utm_campaign]);
|
||||
}
|
||||
|
||||
public function test_channels_are_managed_and_tasks_completed_in_the_admin(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->fakeFeed([['x1', '20261107', '20261110']]);
|
||||
|
||||
Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $this->property, 'pageClass' => EditProperty::class])
|
||||
->callAction(TestAction::make(CreateAction::class)->table(), [
|
||||
'name' => 'FeWo-direkt',
|
||||
'connector' => 'ical',
|
||||
'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/abc.ics'],
|
||||
'requires_manual_blocking' => true,
|
||||
'manage_url' => 'https://www.fewo-direkt.de/vermieter/kalender',
|
||||
])
|
||||
->assertHasNoFormErrors();
|
||||
|
||||
$channel = Channel::sole();
|
||||
Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $this->property, 'pageClass' => EditProperty::class])
|
||||
->callTableAction('sync', $channel)
|
||||
->assertNotified('1 Belegungen eingelesen');
|
||||
|
||||
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
|
||||
$task = ChannelTask::sole();
|
||||
|
||||
Livewire::test(ListChannelTasks::class)
|
||||
->assertCanSeeTableRecords([$task])
|
||||
->callTableAction('done', $task);
|
||||
|
||||
$this->assertSame(ChannelTaskStatus::Done, $task->fresh()->status);
|
||||
}
|
||||
|
||||
private function channel(string $name, bool $manual = false): Channel
|
||||
{
|
||||
return Channel::factory()->for($this->property)->create(['name' => $name, 'requires_manual_blocking' => $manual]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{string, string, string}> $events uid, start, end (Ymd)
|
||||
*/
|
||||
private function fakeFeed(array $events): void
|
||||
{
|
||||
$body = "BEGIN:VCALENDAR\r\n".collect($events)
|
||||
->map(fn (array $event): string => "BEGIN:VEVENT\r\nUID:{$event[0]}\r\nDTSTART;VALUE=DATE:{$event[1]}\r\nDTEND;VALUE=DATE:{$event[2]}\r\nEND:VEVENT\r\n")
|
||||
->implode('')."END:VCALENDAR\r\n";
|
||||
|
||||
$this->httpResponse = Http::response($body, 200, ['Content-Type' => 'text/calendar']);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user