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:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 11:13:55 +02:00
1 parent a8e72715ab
commit 0b7205e050
55 files changed
+2290 -3

No files matched your search

+37
View File
@@ -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());
}
}
+7
View File
@@ -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;
}
+18
View File
@@ -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,
) {}
}
+63
View File
@@ -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());
}
}
+70
View File
@@ -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);
}
}
+121
View File
@@ -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);
}
}