Visuelle iCal-Regelengine mit Originaldaten und individuellen Exportfeldern integrieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m37s
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m37s
This commit is contained in:
1 parent
c4ebccbbea
commit
e9db98701b
30 files changed
+1269
-15
No files matched your search
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalAnalysis;
|
||||
use App\Channels\ICal\ICalConnector;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AnalyzeChannelCalendar
|
||||
{
|
||||
public function handle(Channel $channel): Channel
|
||||
{
|
||||
if ($channel->connector !== 'ical' || blank($channel->setting('import_url')) || ! $channel->servesItsLandlord()) {
|
||||
throw new ChannelSyncException('Für die Analyse eine iCal-Importadresse hinterlegen und den Kalenderdienst freischalten.');
|
||||
}
|
||||
$url = $channel->setting('import_url');
|
||||
$analysis = app(ICalAnalysis::class)->summarize(app(ICalConnector::class)->fetchDocument($channel));
|
||||
|
||||
return DB::transaction(function () use ($channel, $url, $analysis): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
if ($locked->setting('import_url') !== $url) {
|
||||
throw new ChannelSyncException('Die Importadresse wurde während der Analyse geändert. Bitte erneut analysieren.');
|
||||
}
|
||||
$locked->forceFill(['ical_analysis' => $analysis, 'ical_analyzed_at' => now()])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ApplyChannelRules
|
||||
{
|
||||
public function attributes(Channel $channel, ?BlockedPeriod $block, array $properties): array
|
||||
{
|
||||
$result = app(ICalRuleEngine::class)->evaluate($channel, $properties);
|
||||
$attributes = ['ical_interpretation' => $result, 'ical_event_type' => $result['event_type'],
|
||||
'leading_priority' => $result['representation'] === 'leading_candidate' ? max(1, 10001 - $result['priority']) : 0];
|
||||
$previousOrigin = $block?->ical_interpretation['origin_channel_id'] ?? null;
|
||||
if ($block === null || ($block->reviewed_at === null && ($block->origin_channel_id === null || $block->origin_channel_id === $previousOrigin))) {
|
||||
$attributes['origin_channel_id'] = $result['origin_channel_id'];
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
public function store(BlockedPeriod $block, array $attributes): void
|
||||
{
|
||||
foreach ($attributes as $field => $value) {
|
||||
if ($block->getAttribute($field) !== $value) {
|
||||
$block->forceFill([$field => $value]);
|
||||
}
|
||||
}
|
||||
if ($block->isDirty()) {
|
||||
$block->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{classified: int, missing_raw: int} */
|
||||
public function handle(Channel $channel): array
|
||||
{
|
||||
return DB::transaction(function () use ($channel): array {
|
||||
$channel = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
app(ICalRuleEngine::class)->validate($channel, $channel->ical_rules ?? []);
|
||||
$channel->forceFill(['ical_active_rules' => $channel->ical_rules ?? []])->save();
|
||||
Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail();
|
||||
$events = collect($channel->ical_analysis['events'] ?? [])->keyBy('uid');
|
||||
$counts = ['classified' => 0, 'missing_raw' => 0];
|
||||
foreach ($channel->blockedPeriods()->where('source', 'channel')->lockForUpdate()->get() as $block) {
|
||||
$event = $events->get($block->external_uid);
|
||||
if ($event && $block->ical_raw !== null && $channel->ical_analyzed_at !== null
|
||||
&& $block->updated_at->greaterThan($channel->ical_analyzed_at) && $block->ical_raw !== $event['raw']) {
|
||||
throw ValidationException::withMessages(['rules' => 'Der Importbestand hat sich seit der Vorschau geändert. Den Kalender erneut analysieren und die Vorschau prüfen.']);
|
||||
}
|
||||
$properties = $event['properties'] ?? $block->ical_properties;
|
||||
if ($properties === null) {
|
||||
$counts['missing_raw']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$attributes = $this->attributes($channel, $block, $properties);
|
||||
if ($event && $event['starts_on'] !== null && ($block->starts_on->toDateString() !== $event['starts_on'] || $block->ends_on->toDateString() !== $event['ends_on'])) {
|
||||
$attributes = [...$attributes, 'needs_review' => true, 'review_note' => 'Die Analyse meldet einen anderen Zeitraum. Die Klassifikation ändert keine Termine; Kalenderabgleich und Zuordnung prüfen.'];
|
||||
}
|
||||
$this->store($block, [...$attributes, 'ical_properties' => $properties, 'ical_raw' => $event['raw'] ?? $block->ical_raw]);
|
||||
$counts['classified']++;
|
||||
}
|
||||
|
||||
return $counts;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public function handle(Property $property, array $data, ?Channel $channel = null
|
||||
$candidate->fill($data);
|
||||
$candidate->property_id = $property->id;
|
||||
$candidate->tenant_id = $property->tenant_id;
|
||||
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url')) {
|
||||
$candidate->forceFill(['ical_analysis' => null, 'ical_analyzed_at' => null]);
|
||||
}
|
||||
if ($stored) {
|
||||
$candidate->is_active = $candidate->status === ChannelStatus::Active;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalExportFields;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ConfigureChannelExport
|
||||
{
|
||||
public function handle(Channel $channel, array $mapping, bool $allowNames): Channel
|
||||
{
|
||||
Validator::make(['export_mapping' => $mapping], [
|
||||
'export_mapping' => ['array', 'max:3'],
|
||||
'export_mapping.*.field' => ['required', 'distinct', Rule::in(array_keys(ICalExportFields::ICAL_FIELDS))],
|
||||
'export_mapping.*.items' => ['required', 'array', 'min:1'],
|
||||
'export_mapping.*.items.*' => ['required', Rule::in(array_keys(ICalExportFields::FIELDS))],
|
||||
'export_mapping.*.separator' => ['nullable', 'string', 'max:30'],
|
||||
])->validate();
|
||||
foreach ($mapping as $row) {
|
||||
if (! $allowNames && array_intersect($row['items'], ['guest_first_name', 'guest_full_name']) !== []) {
|
||||
throw ValidationException::withMessages(['export_names' => 'Für Gastnamen die Namensweitergabe an genau diesen Zielkanal ausdrücklich einschalten.']);
|
||||
}
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($channel, $mapping, $allowNames): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
$locked->forceFill(['ical_export_mapping' => array_values($mapping), 'ical_export_names' => $allowNames])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SaveChannelRules
|
||||
{
|
||||
public function handle(Channel $channel, array $rules): Channel
|
||||
{
|
||||
return DB::transaction(function () use ($channel, $rules): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
$validated = app(ICalRuleEngine::class)->validate($locked, $rules);
|
||||
$locked->forceFill(['ical_rules' => $validated])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public function handle(Channel $channel): ChannelSyncLog
|
||||
$attributes = ['property_id' => $channel->property_id, 'starts_on' => $period->startsOn->toDateString(),
|
||||
'ends_on' => $period->endsOn->toDateString(), 'reason' => $channel->name, 'source' => 'channel',
|
||||
'external_uid' => $period->uid, 'missing_imports' => 0];
|
||||
$interpretation = $period->properties !== [] ? app(ApplyChannelRules::class)->attributes($locked, $block ?? $matchedMail, $period->properties) : [];
|
||||
if ($matchedMail) {
|
||||
$block = $matchedMail;
|
||||
$block->update($attributes);
|
||||
@@ -85,9 +86,14 @@ public function handle(Channel $channel): ChannelSyncLog
|
||||
$overlap = $channel->property->blockedPeriods()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists()
|
||||
|| $channel->property->bookings()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists();
|
||||
$attributes['export_approved'] = ! $overlap && $locked->echo_behavior !== ChannelEchoBehavior::Reexports;
|
||||
$block = $channel->blockedPeriods()->create($attributes);
|
||||
$block = new BlockedPeriod($attributes);
|
||||
$block->forceFill($interpretation);
|
||||
$channel->blockedPeriods()->save($block);
|
||||
$counts['added']++;
|
||||
}
|
||||
if ($period->properties !== []) {
|
||||
app(ApplyChannelRules::class)->store($block, [...$interpretation, 'ical_properties' => $period->properties, 'ical_raw' => $period->raw]);
|
||||
}
|
||||
$existing->put($period->uid, $block);
|
||||
$overlap = $channel->blockedPeriods()->occupying()->overlapping($block->starts_on, $block->ends_on)->whereKeyNot($block->id)->exists();
|
||||
$foundConflicts = $block->is_representation ? [] : $this->conflictDetector->conflictsFor($block);
|
||||
|
||||
@@ -14,5 +14,7 @@ public function __construct(
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
public array $properties = [],
|
||||
public ?string $raw = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
class ICalAnalysis
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function summarize(array $document): array
|
||||
{
|
||||
$events = [];
|
||||
$fields = [];
|
||||
$engine = new ICalRuleEngine;
|
||||
foreach ($document['events'] as $event) {
|
||||
$period = $event['period'];
|
||||
$events[] = ['uid' => $event['uid'], 'properties' => $event['properties'], 'raw' => $event['raw'],
|
||||
'starts_on' => $period?->startsOn->toDateString(), 'ends_on' => $period?->endsOn->toDateString(), 'occupying' => $period !== null];
|
||||
foreach (array_keys($event['properties']) as $field) {
|
||||
$fields[$field] ??= ['count' => 0, 'values' => [], 'patterns' => []];
|
||||
$fields[$field]['count']++;
|
||||
foreach (array_unique($engine->values($event['properties'], $field)) as $value) {
|
||||
$fields[$field]['values'][$value] = ($fields[$field]['values'][$value] ?? 0) + 1;
|
||||
$pattern = $value;
|
||||
foreach ([' - ', ': ', ' / '] as $delimiter) {
|
||||
if (($position = mb_strpos($value, $delimiter)) !== false) {
|
||||
$pattern = mb_substr($value, 0, $position + mb_strlen($delimiter)).'…';
|
||||
break;
|
||||
}
|
||||
}
|
||||
$fields[$field]['patterns'][$pattern] = ($fields[$field]['patterns'][$pattern] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
ksort($fields);
|
||||
foreach ($fields as &$field) {
|
||||
arsort($field['values']);
|
||||
arsort($field['patterns']);
|
||||
$field['values'] = array_slice($field['values'], 0, 10, true);
|
||||
$field['patterns'] = array_slice($field['patterns'], 0, 10, true);
|
||||
}
|
||||
|
||||
return ['count' => count($events), 'events' => $events, 'fields' => $fields, 'calendar' => $document['calendar']];
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,17 @@ public function canImport(Channel $channel): bool
|
||||
}
|
||||
|
||||
public function fetchOccupations(Channel $channel): array
|
||||
{
|
||||
return $this->parser->parse($this->fetchCalendar($channel));
|
||||
}
|
||||
|
||||
/** @return array{events: list<array>, calendar: array} */
|
||||
public function fetchDocument(Channel $channel): array
|
||||
{
|
||||
return $this->parser->parseDocument($this->fetchCalendar($channel));
|
||||
}
|
||||
|
||||
private function fetchCalendar(Channel $channel): string
|
||||
{
|
||||
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
|
||||
|
||||
@@ -60,6 +71,6 @@ public function fetchOccupations(Channel $channel): array
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden. Netzwerkverbindung und Portaladresse prüfen.', previous: $exception);
|
||||
}
|
||||
|
||||
return $this->parser->parse($response->body());
|
||||
return $response->body();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
|
||||
class ICalExportFields
|
||||
{
|
||||
public const FIELDS = ['occupation_label' => 'Belegungsbeschreibung', 'guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'note' => 'Zusätzliche Textinformation', 'property_name' => 'Wohnungsname', 'channel_name' => 'Bekannter Ursprung / Importkanal', 'arrival' => 'Anreise', 'departure' => 'Abreise', 'nights' => 'Anzahl Nächte'];
|
||||
|
||||
public const ICAL_FIELDS = ['SUMMARY' => 'SUMMARY – Bezeichnung', 'DESCRIPTION' => 'DESCRIPTION – Beschreibung', 'LOCATION' => 'LOCATION – Ort / Wohnung'];
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function properties(Channel $channel, Booking|BlockedPeriod $occupation): array
|
||||
{
|
||||
$context = $this->context($occupation);
|
||||
if (! $channel->ical_export_names) {
|
||||
unset($context['guest_first_name'], $context['guest_full_name']);
|
||||
}
|
||||
$properties = ['SUMMARY' => 'Belegt'];
|
||||
foreach ($channel->ical_export_mapping ?? [] as $mapping) {
|
||||
if (! isset(self::ICAL_FIELDS[$mapping['field'] ?? ''])) {
|
||||
continue;
|
||||
}
|
||||
$parts = [];
|
||||
foreach ($mapping['items'] ?? [] as $item) {
|
||||
if (isset(self::FIELDS[$item]) && filled($context[$item] ?? null)) {
|
||||
$parts[] = $context[$item];
|
||||
}
|
||||
}
|
||||
if ($parts !== []) {
|
||||
$properties[$mapping['field']] = implode($mapping['separator'] ?? ' – ', $parts);
|
||||
}
|
||||
}
|
||||
|
||||
return $properties;
|
||||
}
|
||||
|
||||
/** @return array<string, string|null> */
|
||||
public function context(Booking|BlockedPeriod $occupation): array
|
||||
{
|
||||
$booking = $occupation instanceof Booking;
|
||||
$start = $booking ? $occupation->arrival : $occupation->starts_on;
|
||||
$end = $booking ? $occupation->departure : $occupation->ends_on;
|
||||
$context = ['occupation_label' => $booking ? 'Buchung' : (ICalRuleEngine::TYPES[$occupation->ical_event_type] ?? 'Belegt'),
|
||||
'property_name' => $occupation->property->name, 'arrival' => $start->format('d.m.Y'), 'departure' => $end->format('d.m.Y'),
|
||||
'nights' => (string) (int) $start->diffInDays($end),
|
||||
'channel_name' => $booking ? null : ($occupation->originChannel?->name ?? $occupation->channel?->name)];
|
||||
if ($booking) {
|
||||
return [...$context, 'guest_first_name' => $occupation->guest?->first_name, 'guest_full_name' => $occupation->guest?->full_name, 'booking_reference' => $occupation->reference];
|
||||
}
|
||||
$fields = array_intersect_key($occupation->ical_interpretation['fields'] ?? [], self::FIELDS);
|
||||
|
||||
return [...$context, ...$fields];
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,9 @@ public function build(Channel $channel): string
|
||||
$bookings->where(fn ($query) => $query->whereNull('import_channel_id')->orWhere('import_channel_id', '!=', $channel->id))
|
||||
->where(fn ($query) => $query->whereNull('origin_channel_id')->orWhere('origin_channel_id', '!=', $channel->id));
|
||||
}
|
||||
foreach ($bookings->orderBy('id')->get() as $booking) {
|
||||
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
|
||||
/** @var Booking $booking */
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at);
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
|
||||
}
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
@@ -45,8 +45,8 @@ public function build(Channel $channel): string
|
||||
$blocks->whereNull('channel_id')->whereNull('origin_channel_id')->where('source', 'manual');
|
||||
}
|
||||
|
||||
foreach ($blocks->orderBy('id')->get() as $block) {
|
||||
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at);
|
||||
foreach ($blocks->with(['property', 'channel', 'originChannel'])->orderBy('id')->get() as $block) {
|
||||
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at, (new ICalExportFields)->properties($channel, $block));
|
||||
}
|
||||
|
||||
$lines = [
|
||||
@@ -63,7 +63,7 @@ public function build(Channel $channel): string
|
||||
return implode("\r\n", array_map(fn (string $line): string => $this->fold($line), explode("\r\n", implode("\r\n", $lines))))."\r\n";
|
||||
}
|
||||
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified, array $properties): string
|
||||
{
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VEVENT',
|
||||
@@ -71,7 +71,7 @@ private function event(string $uid, CarbonInterface $start, CarbonInterface $end
|
||||
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
|
||||
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
|
||||
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
|
||||
'SUMMARY:Belegt',
|
||||
...array_map(fn (string $field, string $value): string => $field.':'.$this->escape($value), array_keys($properties), array_values($properties)),
|
||||
'TRANSP:OPAQUE',
|
||||
'END:VEVENT',
|
||||
]);
|
||||
|
||||
@@ -12,6 +12,12 @@ class ICalParser
|
||||
{
|
||||
/** @return list<ExternalPeriod> */
|
||||
public function parse(string $ics): array
|
||||
{
|
||||
return array_values(array_filter(array_column($this->parseDocument($ics)['events'], 'period')));
|
||||
}
|
||||
|
||||
/** @return array{events: list<array>, calendar: array} */
|
||||
public function parseDocument(string $ics): array
|
||||
{
|
||||
if (str_starts_with($ics, "\xEF\xBB\xBF")) {
|
||||
$ics = substr($ics, 3);
|
||||
@@ -25,11 +31,17 @@ public function parse(string $ics): array
|
||||
$calendar = [];
|
||||
$event = [];
|
||||
$periods = [];
|
||||
$properties = [];
|
||||
$eventLines = [];
|
||||
$identities = [];
|
||||
$propertyIdentities = [];
|
||||
$started = false;
|
||||
$closed = false;
|
||||
foreach ($lines as $line) {
|
||||
$line = rtrim($line, "\r");
|
||||
if (in_array('VEVENT', $stack, true)) {
|
||||
$eventLines[] = $line;
|
||||
}
|
||||
if ($line === '' && $stack === []) {
|
||||
continue;
|
||||
}
|
||||
@@ -57,6 +69,8 @@ public function parse(string $ics): array
|
||||
}
|
||||
if ($component === 'VEVENT') {
|
||||
$event = [];
|
||||
$properties = [];
|
||||
$eventLines = [$line];
|
||||
}
|
||||
$stack[] = $component;
|
||||
|
||||
@@ -76,8 +90,16 @@ public function parse(string $ics): array
|
||||
if (isset($identities[$uid]) && $identities[$uid] !== $identity) {
|
||||
throw new ChannelSyncException('Eine UID enthält widersprüchliche Ereignisse; bitte den Portalkalender prüfen.');
|
||||
}
|
||||
if (! isset($identities[$uid]) && $period !== null) {
|
||||
$periods[] = $period;
|
||||
$normalized = $properties;
|
||||
ksort($normalized);
|
||||
if (isset($propertyIdentities[$uid]) && $propertyIdentities[$uid] !== $normalized) {
|
||||
throw new ChannelSyncException('Eine UID enthält widersprüchliche Originalangaben; bitte den Kalender prüfen.');
|
||||
}
|
||||
$propertyIdentities[$uid] = $normalized;
|
||||
if (! isset($identities[$uid])) {
|
||||
$raw = implode("\r\n", $eventLines)."\r\n";
|
||||
$enriched = $period === null ? null : new ExternalPeriod($period->uid, $period->startsOn, $period->endsOn, $period->summary, $properties, $raw);
|
||||
$periods[] = ['uid' => $uid, 'properties' => $properties, 'raw' => $raw, 'period' => $enriched];
|
||||
}
|
||||
$identities[$uid] = $identity;
|
||||
}
|
||||
@@ -103,6 +125,10 @@ public function parse(string $ics): array
|
||||
}
|
||||
$event[$name] = $property;
|
||||
}
|
||||
if (in_array('VEVENT', $stack, true)) {
|
||||
$prefix = count($stack) > 2 ? implode('.', array_slice($stack, 2)).'.' : '';
|
||||
$properties[$prefix.$name][] = $property;
|
||||
}
|
||||
}
|
||||
if (! $closed || $stack !== [] || ($calendar['VERSION']['value'] ?? '') !== '2.0' || blank($calendar['PRODID']['value'] ?? null)) {
|
||||
throw new ChannelSyncException('Kalender ist unvollständig; VERSION, PRODID und geschlossene Komponenten sind erforderlich.');
|
||||
@@ -111,7 +137,12 @@ public function parse(string $ics): array
|
||||
throw new ChannelSyncException('Erwartet wird ein vollständiger Kalenderstand, keine einzelne Kalendernachricht.');
|
||||
}
|
||||
|
||||
return $periods;
|
||||
return ['events' => $periods, 'calendar' => $calendar];
|
||||
}
|
||||
|
||||
public static function text(string $value): string
|
||||
{
|
||||
return preg_replace_callback('/\\\\([nN,;\\\\])/', fn (array $match): string => in_array($match[1], ['n', 'N'], true) ? "\n" : $match[1], $value);
|
||||
}
|
||||
|
||||
/** @param array<string, array{value: string, params: list<string>}> $event */
|
||||
@@ -152,7 +183,7 @@ private function toPeriod(array $event): ?ExternalPeriod
|
||||
}
|
||||
$summary = $event['SUMMARY']['value'] ?? null;
|
||||
|
||||
return new ExternalPeriod($event['UID']['value'], $start, $end, $summary === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $summary));
|
||||
return new ExternalPeriod($event['UID']['value'], $start, $end, $summary === null ? null : self::text($summary));
|
||||
}
|
||||
|
||||
/** @param array{value: string, params: list<string>} $property */
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ICalRuleEngine
|
||||
{
|
||||
public const OPERATORS = ['equals' => 'Ist gleich', 'not_equals' => 'Ist nicht gleich', 'starts_with' => 'Beginnt mit', 'ends_with' => 'Endet mit', 'contains' => 'Enthält', 'exists' => 'Ist vorhanden', 'empty' => 'Ist leer'];
|
||||
|
||||
public const TYPES = ['unknown' => 'Nicht erkannt', 'portal_reservation' => 'Portalreservierung', 'block' => 'Allgemeine Sperre'];
|
||||
|
||||
public const REPRESENTATIONS = ['unspecified' => 'Unbestimmt', 'leading_candidate' => 'Kandidat für führende Belegung', 'additional_block' => 'Zusätzliche Sperre'];
|
||||
|
||||
public const TARGETS = ['guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'occupation_label' => 'Belegungsbeschreibung', 'note' => 'Zusätzliche Textinformation'];
|
||||
|
||||
public const EXTRACTIONS = ['whole' => 'Gesamter Text', 'after' => 'Text nach', 'before' => 'Text vor', 'between' => 'Text zwischen'];
|
||||
|
||||
/** @return list<string> */
|
||||
public function values(array $properties, string $field): array
|
||||
{
|
||||
return array_map(fn (array $property): string => ICalParser::text($property['value']), $properties[$field] ?? []);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function evaluate(Channel $channel, array $properties, ?array $rules = null): array
|
||||
{
|
||||
$rules = collect($rules ?? $channel->ical_active_rules ?? [])->values()
|
||||
->map(fn (array $rule, int $index): array => [...$rule, '_index' => $index])
|
||||
->sortBy(fn (array $rule): array => [(int) ($rule['priority'] ?? 100), $rule['_index']]);
|
||||
foreach ($rules as $rule) {
|
||||
if (! ($rule['enabled'] ?? true) || empty($rule['conditions'])) {
|
||||
continue;
|
||||
}
|
||||
$matches = array_map(fn (array $condition): bool => $this->matches($properties, $condition, (bool) ($rule['case_sensitive'] ?? false)), array_values($rule['conditions']));
|
||||
if (($rule['match'] ?? 'all') === 'any' ? ! in_array(true, $matches, true) : in_array(false, $matches, true)) {
|
||||
continue;
|
||||
}
|
||||
$fields = [];
|
||||
foreach ($rule['extractions'] ?? [] as $extraction) {
|
||||
$value = $this->extract($this->values($properties, $extraction['field'] ?? '')[0] ?? '', $extraction);
|
||||
if (isset(self::TARGETS[$extraction['target'] ?? '']) && filled($value)) {
|
||||
$fields[$extraction['target']] = $value;
|
||||
}
|
||||
}
|
||||
$origin = $rule['origin'] ?? 'unknown';
|
||||
|
||||
return ['matched' => true, 'rule' => $rule['name'] ?? 'Unbenannte Regel', 'rule_index' => $rule['_index'],
|
||||
'event_type' => $rule['event_type'] ?? 'unknown', 'representation' => $rule['representation'] ?? 'unspecified',
|
||||
'priority' => (int) ($rule['priority'] ?? 100),
|
||||
'origin_channel_id' => $origin === 'current' ? $channel->id : (str_starts_with($origin, 'channel:') ? (int) substr($origin, 8) : null), 'fields' => $fields];
|
||||
}
|
||||
|
||||
return ['matched' => false, 'rule' => null, 'event_type' => 'unknown', 'representation' => 'unspecified', 'origin_channel_id' => null, 'priority' => 0, 'fields' => []];
|
||||
}
|
||||
|
||||
private function matches(array $properties, array $condition, bool $caseSensitive): bool
|
||||
{
|
||||
$field = $condition['field'] ?? '';
|
||||
if ($field === '') {
|
||||
return false;
|
||||
}
|
||||
$values = $this->values($properties, $field);
|
||||
$operator = $condition['operator'] ?? 'equals';
|
||||
if ($operator === 'exists') {
|
||||
return array_key_exists($field, $properties);
|
||||
}
|
||||
if ($operator === 'empty') {
|
||||
return $values === [] || collect($values)->every(fn (string $value): bool => trim($value) === '');
|
||||
}
|
||||
$expected = (string) ($condition['value'] ?? '');
|
||||
if (! $caseSensitive) {
|
||||
$expected = mb_strtolower($expected);
|
||||
$values = array_map(mb_strtolower(...), $values);
|
||||
}
|
||||
if ($operator === 'not_equals') {
|
||||
return $values !== [] && ! in_array($expected, $values, true);
|
||||
}
|
||||
|
||||
return collect($values)->contains(fn (string $value): bool => match ($operator) {
|
||||
'equals' => $value === $expected,
|
||||
'starts_with' => str_starts_with($value, $expected),
|
||||
'ends_with' => str_ends_with($value, $expected),
|
||||
'contains' => str_contains($value, $expected),
|
||||
default => false,
|
||||
});
|
||||
}
|
||||
|
||||
private function extract(string $text, array $extraction): ?string
|
||||
{
|
||||
$method = $extraction['method'] ?? 'whole';
|
||||
if (in_array($method, ['after', 'between'], true)) {
|
||||
$start = (string) ($extraction['start'] ?? '');
|
||||
$position = $start === '' ? false : mb_strpos($text, $start);
|
||||
if ($position === false) {
|
||||
return null;
|
||||
}
|
||||
$text = mb_substr($text, $position + mb_strlen($start));
|
||||
}
|
||||
if (in_array($method, ['before', 'between'], true)) {
|
||||
$end = (string) ($extraction['end'] ?? '');
|
||||
$position = $end === '' ? false : mb_strpos($text, $end);
|
||||
if ($position === false) {
|
||||
return null;
|
||||
}
|
||||
$text = mb_substr($text, 0, $position);
|
||||
}
|
||||
|
||||
return trim($text);
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
public function validate(Channel $channel, array $rules): array
|
||||
{
|
||||
$fields = array_keys($channel->ical_analysis['fields'] ?? []);
|
||||
$origins = ['unknown', 'current', ...$channel->property->channels()->pluck('id')->map(fn ($id): string => 'channel:'.$id)->all()];
|
||||
Validator::make(['rules' => $rules], [
|
||||
'rules' => ['array'], 'rules.*.name' => ['required', 'string', 'max:120'],
|
||||
'rules.*.enabled' => ['boolean'], 'rules.*.priority' => ['required', 'integer', 'min:0', 'max:10000'],
|
||||
'rules.*.match' => ['required', Rule::in(['all', 'any'])], 'rules.*.case_sensitive' => ['boolean'],
|
||||
'rules.*.conditions' => ['required', 'array', 'min:1', 'max:30'],
|
||||
'rules.*.conditions.*.field' => ['required', Rule::in($fields)],
|
||||
'rules.*.conditions.*.operator' => ['required', Rule::in(array_keys(self::OPERATORS))],
|
||||
'rules.*.conditions.*.value' => ['nullable', 'string', 'max:2000'],
|
||||
'rules.*.event_type' => ['required', Rule::in(array_keys(self::TYPES))],
|
||||
'rules.*.origin' => ['required', Rule::in($origins)],
|
||||
'rules.*.representation' => ['required', Rule::in(array_keys(self::REPRESENTATIONS))],
|
||||
'rules.*.extractions' => ['array', 'max:20'],
|
||||
'rules.*.extractions.*.field' => ['required', Rule::in($fields)],
|
||||
'rules.*.extractions.*.target' => ['required', Rule::in(array_keys(self::TARGETS))],
|
||||
'rules.*.extractions.*.method' => ['required', Rule::in(array_keys(self::EXTRACTIONS))],
|
||||
'rules.*.extractions.*.start' => ['nullable', 'string', 'max:500'],
|
||||
'rules.*.extractions.*.end' => ['nullable', 'string', 'max:500'],
|
||||
])->validate();
|
||||
foreach ($rules as $index => $rule) {
|
||||
foreach ($rule['extractions'] ?? [] as $extraction) {
|
||||
if ((in_array($extraction['method'], ['after', 'between'], true) && blank($extraction['start'] ?? null))
|
||||
|| (in_array($extraction['method'], ['before', 'between'], true) && blank($extraction['end'] ?? null))) {
|
||||
throw ValidationException::withMessages(['rules.'.$index.'.extractions' => 'Für die Textextraktion die benötigten Anfangs- und Endtexte angeben.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($rules);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\BlockedPeriods;
|
||||
|
||||
use App\Actions\ResolveChannelOccupation;
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
|
||||
use App\Models\BlockedPeriod;
|
||||
@@ -16,6 +17,7 @@
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
@@ -93,6 +95,8 @@ public static function table(Table $table): Table
|
||||
TextColumn::make('originChannel.name')->label('Ursprungskanal')->placeholder('Unbekannt')->toggleable(),
|
||||
TextColumn::make('id')->label('Interne Sperr-ID')->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('external_uid')->label('Externe UID')->limit(30)->toggleable(),
|
||||
TextColumn::make('ical_event_type')->label('Erkannt als')->formatStateUsing(fn (?string $state): string => ICalRuleEngine::TYPES[$state] ?? 'Nicht erkannt')->badge(),
|
||||
TextColumn::make('guest_fragment')->label('Verfügbare Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->ical_interpretation['fields']['guest_full_name'] ?? $record->ical_interpretation['fields']['guest_first_name'] ?? null)->placeholder('Unbekannt')->toggleable(),
|
||||
TextColumn::make('occupation_state')->label('Belegungsführung')->state(fn (BlockedPeriod $record): string => $record->is_representation
|
||||
? ($record->linked_booking_id ? 'Darstellung von Buchung #'.$record->linked_booking_id : 'Darstellung von Sperre #'.$record->canonical_block_id)
|
||||
: ($record->export_approved ? 'Führende Belegung' : 'Intern gesperrt – Export erst klären'))->badge(),
|
||||
@@ -107,6 +111,12 @@ public static function table(Table $table): Table
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('icalOriginal')->label('iCal-Original & Erkennung')->visible(fn (BlockedPeriod $record): bool => $record->ical_raw !== null)
|
||||
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->schema([
|
||||
TextEntry::make('recognized_rule')->label('Treffende Regel')->state(fn (BlockedPeriod $record): string => $record->ical_interpretation['rule'] ?? 'Keine'),
|
||||
TextEntry::make('recognized_representation')->label('Fachliche Einordnung')->state(fn (BlockedPeriod $record): string => ICalRuleEngine::REPRESENTATIONS[$record->ical_interpretation['representation'] ?? 'unspecified']),
|
||||
TextEntry::make('original')->label('Originalereignis (entfaltet)')->state(fn (BlockedPeriod $record): string => $record->ical_raw)->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']),
|
||||
]),
|
||||
Action::make('resolve')->label('Belegung zuordnen / klären')
|
||||
->visible(fn (BlockedPeriod $record): bool => in_array($record->source, ['channel', 'email'], true))
|
||||
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
|
||||
@@ -122,8 +132,8 @@ public static function table(Table $table): Table
|
||||
->mapWithKeys(fn (Booking $booking): array => [$booking->id => 'Buchung '.$booking->reference])->all();
|
||||
}
|
||||
|
||||
return BlockedPeriod::query()->where('property_id', $record->property_id)->occupying()->whereKeyNot($record->id)->whereDate('starts_on', $record->starts_on)->whereDate('ends_on', $record->ends_on)->get()
|
||||
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.($block->reason ?? 'Sperre')])->all();
|
||||
return BlockedPeriod::query()->where('property_id', $record->property_id)->occupying()->whereKeyNot($record->id)->whereDate('starts_on', $record->starts_on)->whereDate('ends_on', $record->ends_on)->orderByDesc('leading_priority')->orderBy('id')->get()
|
||||
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.($block->reason ?? 'Sperre').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all();
|
||||
}),
|
||||
Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt')
|
||||
->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Channels;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
||||
use App\Filament\Resources\Channels\Pages\CreateChannel;
|
||||
use App\Filament\Resources\Channels\Pages\EditChannel;
|
||||
use App\Filament\Resources\Channels\Pages\ListChannels;
|
||||
@@ -58,6 +59,7 @@ public static function getPages(): array
|
||||
'index' => ListChannels::route('/'),
|
||||
'create' => CreateChannel::route('/create'),
|
||||
'edit' => EditChannel::route('/{record}/edit'),
|
||||
'rules' => ChannelRules::route('/{record}/rules'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ApplyChannelRules;
|
||||
use App\Actions\ConfigureChannelExport;
|
||||
use App\Actions\SaveChannelRules;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalExportFields;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ChannelRules extends EditRecord
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected static ?string $title = 'Kalenderanalyse, Regeln & Exportfelder';
|
||||
|
||||
public function fieldOptions(): array
|
||||
{
|
||||
return collect(array_keys($this->record->ical_analysis['fields'] ?? []))->mapWithKeys(fn (string $field): array => [$field => $field])->all();
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return ['rules' => $this->record->ical_rules ?? [], 'export_names' => (bool) $this->record->ical_export_names, 'export_mapping' => $this->record->ical_export_mapping ?? []];
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Section::make('1. Gefundene Kalenderfelder und Originalereignisse')->description('„Kalender analysieren“ liest die hinterlegte Adresse. Die Analyse verändert keine Belegungen.')
|
||||
->schema([View::make('filament.resources.channels.rule-analysis')]),
|
||||
Section::make('2. Erkennungsregeln')->description('Kleinere Prioritätszahlen zuerst. Bei mehreren Treffern gilt die erste passende aktive Regel. Speichern legt einen Entwurf ab; erst „Auf Bestand anwenden“ aktiviert die Regeln für weitere Importe.')
|
||||
->schema([
|
||||
Repeater::make('rules')->label('Regeln')->defaultItems(0)->addActionLabel('Regel hinzufügen')->live(debounce: 600)
|
||||
->itemLabel(fn (array $state): string => $state['name'] ?? 'Neue Regel')
|
||||
->schema([
|
||||
TextInput::make('name')->label('Regelname')->required()->maxLength(120),
|
||||
TextInput::make('priority')->label('Priorität (kleinere Zahl zuerst)')->integer()->minValue(0)->maxValue(10000)->default(100)->required(),
|
||||
Toggle::make('enabled')->label('Regel aktiviert')->default(true),
|
||||
Toggle::make('case_sensitive')->label('Groß-/Kleinschreibung beachten')->default(false),
|
||||
Select::make('match')->label('Bedingungen verknüpfen')->options(['all' => 'UND – alle Bedingungen', 'any' => 'ODER – mindestens eine Bedingung'])->default('all')->required(),
|
||||
Repeater::make('conditions')->label('Wenn')->minItems(1)->defaultItems(1)->addActionLabel('Bedingung hinzufügen')->columns(3)->schema([
|
||||
Select::make('field')->label('Gefundenes Feld')->options(fn (): array => $this->fieldOptions())->required()->searchable(),
|
||||
Select::make('operator')->label('Vergleich')->options(ICalRuleEngine::OPERATORS)->default('equals')->required()->live(),
|
||||
TextInput::make('value')->label('Vergleichstext')->maxLength(2000)->visible(fn (Get $get): bool => ! in_array($get('operator'), ['exists', 'empty'], true))->live(debounce: 600),
|
||||
])->columnSpanFull(),
|
||||
Select::make('event_type')->label('Dann: Ereignistyp')->options(ICalRuleEngine::TYPES)->default('unknown')->required(),
|
||||
Select::make('origin')->label('Ursprünglicher Buchungskanal')->options(fn (): array => ['unknown' => 'Unbekannt', 'current' => 'Dieser Portalkanal', ...$this->record->property->channels()->get()->mapWithKeys(fn (Channel $channel): array => ['channel:'.$channel->id => $channel->name])->all()])->default('unknown')->required(),
|
||||
Select::make('representation')->label('Fachliche Einordnung')->options(ICalRuleEngine::REPRESENTATIONS)->default('unspecified')->required()->columnSpanFull(),
|
||||
Repeater::make('extractions')->label('Informationen aus Text übernehmen')->defaultItems(0)->addActionLabel('Textextraktion hinzufügen')->columns(2)->schema([
|
||||
Select::make('field')->label('Aus Kalenderfeld')->options(fn (): array => $this->fieldOptions())->required(),
|
||||
Select::make('target')->label('Übernehmen als')->options(ICalRuleEngine::TARGETS)->required(),
|
||||
Select::make('method')->label('Textauswahl')->options(ICalRuleEngine::EXTRACTIONS)->default('whole')->required()->live(),
|
||||
TextInput::make('start')->label('Text nach / Anfangstext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['after', 'between'], true))->live(debounce: 600),
|
||||
TextInput::make('end')->label('Text vor / Endtext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['before', 'between'], true))->live(debounce: 600),
|
||||
])->columnSpanFull(),
|
||||
])->columns(2),
|
||||
]),
|
||||
Section::make('3. Live-Vorschau')->description('Auswertung des gespeicherten echten Kalenderstands mit dem aktuellen Regelentwurf. Identische Termine sind lediglich Zuordnungskandidaten.')
|
||||
->schema([View::make('filament.resources.channels.rule-preview')]),
|
||||
Section::make('4. Informationen im Export an diesen Zielkanal')->description('Diese Exportkonfiguration wird beim Speichern wirksam. Die Vorschau zeigt den aktuell berechneten Inhalt; ein pausierter Export bleibt eingefroren. Nicht vorhandene Informationen werden ausgelassen.')
|
||||
->schema([
|
||||
Toggle::make('export_names')->label('Gastnamen ausdrücklich an diesen Zielkanal weitergeben')->default(false)->live(),
|
||||
Repeater::make('export_mapping')->label('iCal-Felder befüllen')->maxItems(3)->defaultItems(0)->live(debounce: 600)->addActionLabel('Exportfeld hinzufügen')->schema([
|
||||
Select::make('field')->label('iCal-Zielfeld')->options(ICalExportFields::ICAL_FIELDS)->required(),
|
||||
Select::make('items')->label('Enthaltene Informationen (in dieser Reihenfolge)')->options(ICalExportFields::FIELDS)->multiple()->required(),
|
||||
TextInput::make('separator')->label('Trennzeichen')->default(' – ')->maxLength(30),
|
||||
]),
|
||||
View::make('filament.resources.channels.export-preview'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function preview(): array
|
||||
{
|
||||
$engine = app(ICalRuleEngine::class);
|
||||
$rules = array_values($this->data['rules'] ?? []);
|
||||
$counts = array_fill(0, count($rules), 0);
|
||||
$unmatched = 0;
|
||||
$rows = [];
|
||||
$blocks = $this->record->property->blockedPeriods()->occupying()->get();
|
||||
foreach ($this->record->ical_analysis['events'] ?? [] as $event) {
|
||||
$result = $engine->evaluate($this->record, $event['properties'], $rules);
|
||||
if ($result['matched']) {
|
||||
$counts[$result['rule_index']]++;
|
||||
} else {
|
||||
$unmatched++;
|
||||
}
|
||||
$candidates = $blocks->filter(fn (BlockedPeriod $block): bool => $block->starts_on->toDateString() === $event['starts_on'] && $block->ends_on->toDateString() === $event['ends_on'] && ! ($block->channel_id === $this->record->id && $block->external_uid === $event['uid']))->sortByDesc('leading_priority');
|
||||
$rows[] = [...$event, 'summary' => $engine->values($event['properties'], 'SUMMARY')[0] ?? '(ohne SUMMARY)', 'result' => $result, 'candidates' => $candidates->map(fn (BlockedPeriod $block): array => ['id' => $block->id, 'reason' => $block->reason, 'priority' => $block->leading_priority])->all()];
|
||||
}
|
||||
|
||||
return ['rows' => $rows, 'counts' => $counts, 'rules' => $rules, 'unmatched' => $unmatched];
|
||||
}
|
||||
|
||||
public function exportPreview(): array
|
||||
{
|
||||
$channel = clone $this->record;
|
||||
$channel->forceFill(['ical_export_names' => (bool) ($this->data['export_names'] ?? false), 'ical_export_mapping' => array_values($this->data['export_mapping'] ?? [])]);
|
||||
|
||||
return app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($channel))['events'];
|
||||
}
|
||||
|
||||
protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
DB::transaction(function () use ($record, $data): Model {
|
||||
$channel = app(SaveChannelRules::class)->handle($record, array_values($data['rules'] ?? []));
|
||||
|
||||
return app(ConfigureChannelExport::class)->handle($channel, array_values($data['export_mapping'] ?? []), (bool) ($data['export_names'] ?? false));
|
||||
});
|
||||
|
||||
return $record->refresh();
|
||||
}
|
||||
|
||||
protected function getSavedNotificationTitle(): ?string
|
||||
{
|
||||
return 'Regelentwurf und Exportkonfiguration gespeichert';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
|
||||
try {
|
||||
$this->record = $analyze->handle($this->record);
|
||||
Notification::make()->title($this->record->ical_analysis['count'].' Originalereignisse analysiert')->success()->send();
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
Action::make('applyRules')->label('Auf Bestand anwenden')->requiresConfirmation()
|
||||
->modalDescription('Der Regelentwurf wird aktiviert und der vorhandene Kalenderbestand neu klassifiziert. IDs, Termine und persönliche Zuordnungen bleiben erhalten. Bekannte Herkunft beeinflusst den kanalspezifischen Export. Bei Namensfreigabe werden die gewählten Exportinformationen ebenfalls gespeichert.')
|
||||
->action(function (ApplyChannelRules $apply): void {
|
||||
$counts = DB::transaction(function () use ($apply): array {
|
||||
$this->record = $this->handleRecordUpdate($this->record, $this->form->getState());
|
||||
|
||||
return $apply->handle($this->record);
|
||||
});
|
||||
$this->record->refresh();
|
||||
Notification::make()->title($counts['classified'].' Einträge neu klassifiziert')->body($counts['missing_raw'].' Einträge ohne Originaldaten unverändert.')->success()->send();
|
||||
}),
|
||||
Action::make('configuration')->label('Kalenderverbindung')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ConfigureChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
@@ -11,6 +15,21 @@ class EditChannel extends EditRecord
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record])),
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
|
||||
try {
|
||||
$analyze->handle($this->record);
|
||||
$this->redirect(ChannelResource::getUrl('rules', ['record' => $this->record]));
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return [...$data, 'settings' => $this->record->settings];
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
namespace App\Filament\Resources\Channels\Tables;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ConfigureChannel;
|
||||
use App\Actions\RotateChannelToken;
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Models\Property;
|
||||
@@ -84,6 +87,15 @@ public static function configure(Table $table, ?Property $owner = null): Table
|
||||
...($owner ? [EditAction::make()->mutateRecordDataUsing(fn (array $data, Channel $record): array => [...$data, 'settings' => $record->settings])
|
||||
->using(fn (Channel $record, array $data): Channel => app(ConfigureChannel::class)->handle($owner, $data, $record))] : [EditAction::make()]),
|
||||
ActionGroup::make([
|
||||
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (Channel $record): string => ChannelResource::getUrl('rules', ['record' => $record])),
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (Channel $record, AnalyzeChannelCalendar $analyze, $livewire): void {
|
||||
try {
|
||||
$analyze->handle($record);
|
||||
$livewire->redirect(ChannelResource::getUrl('rules', ['record' => $record]));
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
Action::make('coverage')->label('Exportumfang prüfen')->modalSubmitAction(false)->modalCancelActionLabel('Schließen')
|
||||
->modalDescription('Aktuell berechneter Umfang der nächsten aktiven Ausgabe. Bei pausiertem Export bleibt der gespeicherte Stand maßgeblich.')
|
||||
->schema([
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BlockedPeriodFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -21,6 +22,7 @@
|
||||
* Like bookings, ends_on is the first free day again.
|
||||
*/
|
||||
#[ObservedBy(BlockedPeriodObserver::class)]
|
||||
#[Hidden(['ical_properties', 'ical_raw', 'ical_interpretation'])]
|
||||
#[Fillable(['property_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid', 'needs_review', 'review_note', 'missing_imports', 'is_representation', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'reviewed_at'])]
|
||||
class BlockedPeriod extends Model
|
||||
{
|
||||
@@ -44,6 +46,10 @@ protected function casts(): array
|
||||
'is_representation' => 'boolean',
|
||||
'export_approved' => 'boolean',
|
||||
'reviewed_at' => 'immutable_datetime',
|
||||
'ical_properties' => 'encrypted:array',
|
||||
'ical_raw' => 'encrypted',
|
||||
'ical_interpretation' => 'encrypted:array',
|
||||
'leading_priority' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
* 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', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at'])]
|
||||
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings'])]
|
||||
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])]
|
||||
class Channel extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelFactory> */
|
||||
@@ -62,6 +62,12 @@ protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'settings' => 'array',
|
||||
'ical_analysis' => 'encrypted:array',
|
||||
'ical_analyzed_at' => 'immutable_datetime',
|
||||
'ical_rules' => 'array',
|
||||
'ical_active_rules' => 'array',
|
||||
'ical_export_mapping' => 'array',
|
||||
'ical_export_names' => 'boolean',
|
||||
'status' => ChannelStatus::class,
|
||||
'booking_model' => ChannelBookingModel::class,
|
||||
'echo_behavior' => ChannelEchoBehavior::class,
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->trimStrings(except: [
|
||||
'components.*.updates.data.rules.*.conditions.*.value',
|
||||
'components.*.updates.data.rules.*.extractions.*.start',
|
||||
'components.*.updates.data.rules.*.extractions.*.end',
|
||||
'components.*.updates.data.export_mapping.*.separator',
|
||||
]);
|
||||
$middleware->web(append: [ResolveTheme::class]);
|
||||
$middleware->append(SecurityHeaders::class);
|
||||
})
|
||||
|
||||
@@ -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::table('channels', function (Blueprint $table): void {
|
||||
$table->longText('ical_analysis')->nullable();
|
||||
$table->dateTime('ical_analyzed_at')->nullable();
|
||||
$table->json('ical_rules')->nullable();
|
||||
$table->json('ical_active_rules')->nullable();
|
||||
$table->json('ical_export_mapping')->nullable();
|
||||
$table->boolean('ical_export_names')->default(false);
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table): void {
|
||||
$table->longText('ical_properties')->nullable();
|
||||
$table->longText('ical_raw')->nullable();
|
||||
$table->longText('ical_interpretation')->nullable();
|
||||
$table->string('ical_event_type')->default('unknown');
|
||||
$table->unsignedInteger('leading_priority')->default(0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('blocked_periods', fn (Blueprint $table) => $table->dropColumn(['ical_properties', 'ical_raw', 'ical_interpretation', 'ical_event_type', 'leading_priority']));
|
||||
Schema::table('channels', fn (Blueprint $table) => $table->dropColumn(['ical_analysis', 'ical_analyzed_at', 'ical_rules', 'ical_active_rules', 'ical_export_mapping', 'ical_export_names']));
|
||||
}
|
||||
};
|
||||
@@ -4,6 +4,8 @@ # Projektstand
|
||||
|
||||
> Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“).
|
||||
|
||||
**Visuelle iCal-Regelengine zur Bereitstellung vorbereitet (27.10.2026):** Echte Kalenderanalyse mit Originalfeldern, Beispielen, Häufigkeiten und Textpräfixen; Regeleditor mit UND/ODER, Literalvergleichen, Priorität und einfacher Textextraktion; Live-Vorschau, getrennte Entwurfs-/Aktivierungsstufen und Neuauswertung vorhandener Einträge ohne neue IDs oder Termine. Fachliche Führungskandidaten unterstützen die vorhandene persönliche Zuordnung, ohne automatische Datumszusammenführung. Exportzuordnung nach SUMMARY/DESCRIPTION/LOCATION und ausdrückliche Namensfreigabe je Zielkanal. Originale und Interpretation verschlüsselt gespeichert. **409 Feature-Tests / 1930 Assertions lokal erfolgreich, darunter 32 neue Fälle; Pint erfolgreich.** Additive Migration `2026_10_27_183425_add_ical_analysis_rules_and_event_metadata`. [Bedienung und Grenzen](architecture/ical-regelengine.md). Bereitstellung und reale FeWo-direkt-/Ostseeklar-Nachweise folgen; aktuell sind Quelle und Ziel vorhanden, aber noch keine echten Regelresultate behauptet.
|
||||
|
||||
**iCal-Bereich fachlich abgegrenzt und bereitgestellt (27.10.2026):** Menü und Wohnungsbereich heißen **„Kalenderabgleich (iCal)“**, Datensätze und Anlage **„iCal-Verbindung“**. Übersicht und Formular erklären den Umfang als Austausch von Belegungszeiträumen; weitere Funktionen eines Portals benötigen eigene Anbindungen. Route `/admin/channels`, Daten, Token und Synchronisationsverhalten bleiben erhalten. **66 relevante Tests / 336 Assertions erfolgreich, Pint erfolgreich.** Pipeline 4667 mit Build/Tests/Sicherung/Deployment erfolgreich; Server-REVISION `8927f2e` und Release bestätigt.
|
||||
|
||||
**Erstimport-Anzeige korrigiert und ausgeliefert (27.10.2026):** Ein neuer aktiver Kanal ohne erfolgreichen Import zeigt **„Erster Import ausstehend“**. „Import veraltet“ bleibt früher erfolgreichen, inzwischen nicht mehr aktuellen Importen vorbehalten; ein erster fehlgeschlagener Abruf zeigt weiterhin „Importfehler“. Erster Lauf über **Weitere Aktionen › Jetzt abgleichen**. Nur die Darstellung geändert, keine Import-/Belegungsregeln oder Portalverbindungen. Relevante Verwaltungs-/Abrufprüfungen: **18 Tests / 106 Assertions erfolgreich**, Pint erfolgreich; Pipeline 4666 mit Build/Tests/Sicherung/Deployment erfolgreich, Server-REVISION und Release bestätigt. Lesend geprüft: Der inzwischen vom Nutzer eingerichtete Importkanal 2 hat einen erfolgreichen Lauf vom 27.10. um 17:58; Aktualitätsgrenze 60 Minuten, `is_stale=false`. Kein weiterer Import durch diese Prüfung ausgelöst.
|
||||
|
||||
@@ -6,6 +6,8 @@ # Generische iCal-Integration und konfigurierbare Portalkanäle
|
||||
|
||||
## 1. Gültigkeit und Nachweisstand
|
||||
|
||||
Die [visuelle iCal-Regelengine](ical-regelengine.md) erweitert diesen Stand um Analyse der Originalfelder, benutzerdefinierte Klassifikation und individuelle Exportinformationen. Die frühere Standardaussage „keine Gastdaten im Export“ gilt weiterhin ohne ausdrückliche Feldzuordnung und Namensfreigabe; die neue Option wird je Zielkanal bewusst aktiviert. IDs, Zeiträume, Herkunftsschutz und bestätigte Zuordnungen bleiben bestehen.
|
||||
|
||||
Die vorhandene Kanalverwaltung, der Connector `ical`, Import, Export, Portal-Mails, Aufgaben und Protokolle wurden erweitert. Es gibt keine separate FeWo-direkt- oder Ostseeklar-Synchronisation. Ein weiterer Anbieter benötigt keine Codeänderung, wenn er das unten beschriebene Kalenderprofil unterstützt.
|
||||
|
||||
| Ebene | Stand |
|
||||
|
||||
@@ -8,6 +8,8 @@ # iCal-MVP: Bereitstellung und Benutzung
|
||||
|
||||
## Oberfläche und automatische Exportlinks
|
||||
|
||||
**Erweiterung um Kalenderanalyse und visuelle Regeln:** [Bedienung der iCal-Regelengine](ical-regelengine.md) beschreibt Feldentdeckung, Regelentwurf, Live-Vorschau, Neuauswertung, Führungskandidaten und individuell freigegebene Exportinformationen. Der konkrete Auslieferungs- und Realteststand wird dort getrennt nachgeführt.
|
||||
|
||||
Die eigenständige Verwaltungsseite **Vermietung → Kalenderabgleich (iCal)** (`/admin/channels`) zeigt die Kalenderverbindungen des angemeldeten Vermieters. Jeder Eintrag steht für den iCal-Belegungsabgleich einer Wohnung mit einem externen Kalender. Weitere Portalfunktionen wie Preise, Nachrichten oder vollständige Buchungsabläufe benötigen eigene Anbindungen und werden durch diesen Eintrag nicht aktiviert. Die Seite ist in der einfachen und der Expertenansicht erreichbar. Über **iCal-Verbindung anlegen** werden Wohnung, frei gewählter Name der Kalenderverbindung und Kalenderanbindung eingetragen. Es gibt keine vorausgewählten oder automatisch eingerichteten Anbieter. Auch auf ausdrücklichen Wunsch im Folgeauftrag wurde kein Ostseeklar-Kanal angelegt.
|
||||
|
||||
Jede iCal-Verbindung lässt sich individuell konfigurieren und bearbeiten. Die Übersicht bietet Suche nach Namen/Wohnung sowie die Aktionen für Exportlink, Exportumfang, Import und Protokoll. Die Einstellungen bleiben zusätzlich unter **Wohnungen → Wohnung bearbeiten → Kalenderabgleich (iCal)** erreichbar; beide Ansichten verwenden dieselben Formulare, Aktionen und Geschäftsregeln. Die interne Route `/admin/channels`, vorhandene Verbindungen und Exportadressen bleiben bei der begrifflichen Klarstellung erhalten.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Visuelle iCal-Regelengine
|
||||
|
||||
Stand: 27.10.2026 · Implementierung zur Bereitstellung vorbereitet; tatsächliche Auslieferung und echte Kalendernachweise werden nach der Abnahme ergänzt.
|
||||
|
||||
## Kalender analysieren
|
||||
|
||||
Unter **Vermietung → Kalenderabgleich (iCal)** am gewünschten Kanal **Weitere Aktionen → Kalender analysieren** wählen. Dieselbe Aktion steht auf seiner Konfigurationsseite. Die Importadresse muss vorher gespeichert sein. Über **Regeln & Exportfelder** wird die Auswertungsseite auch ohne neuen Abruf geöffnet, beispielsweise für einen reinen Exportkanal.
|
||||
|
||||
Die Analyse liest den echten Portalkalender und zeigt:
|
||||
|
||||
- Anzahl der Originalereignisse, einschließlich solcher ohne aktuell belegenden Zeitraum.
|
||||
- Tatsächlich vorhandene Ereignisfelder, auch unbekannte Zusatzfelder und wiederholte Angaben.
|
||||
- Häufige Werte, Beispielwerte und generisch erkannte Textpräfixe mit Ereigniszahlen.
|
||||
- Kalender-Kopfdaten sowie aufklappbare Originalereignisse mit ihren Parametern.
|
||||
|
||||
Die Analyse importiert und löscht keine Belegung. Ein fehlgeschlagener Abruf ersetzt den bisherigen Analysestand nicht. Originalfelder, Ereignistexte und Auswertung mit Namensbestandteilen werden verschlüsselt gespeichert und nur innerhalb der berechtigten Verwaltung angezeigt. Gefaltete iCal-Zeilen werden für die lesbare Originalansicht entfaltet.
|
||||
|
||||
## Regeln ohne Code erstellen
|
||||
|
||||
Jede Regel hat einen Namen, eine Priorität, einen Aktivierungsschalter und beliebig kombinierbare Bedingungen. Kleinere Prioritätszahlen werden zuerst ausgewertet; bei Gleichstand entscheidet die sichtbare Reihenfolge. Die **erste passende aktive Regel** bestimmt die Interpretation. Nachfolgende Regeln überschreiben das Ergebnis nicht.
|
||||
|
||||
Das Feld wird aus den gefundenen Kalenderfeldern gewählt. Vergleiche sind **gleich, ungleich, beginnt mit, endet mit, enthält, vorhanden, leer**. Bedingungen werden mit **UND** oder **ODER** verbunden. Standardmäßig sind Vergleiche unabhängig von der Groß-/Kleinschreibung. „Vorhanden“ prüft die Existenz eines Feldes; „leer“ umfasst auch fehlende Felder. „Ungleich“ benötigt ein vorhandenes Feld.
|
||||
|
||||
Aktionen bestimmen Ereignistyp, bekannten ursprünglichen Buchungskanal und die Einordnung als führenden Kandidaten oder zusätzliche Sperre. Ein unbekannter Ursprung bleibt unbekannt. Die Regeln sind Kanalkonfiguration und enthalten keine fest eingebauten Anbieternamen oder Interpretationen.
|
||||
|
||||
Texte werden über **Gesamter Text**, **Text nach**, **Text vor** oder **Text zwischen** übernommen. Verfügbare Zielfelder sind Gastvorname/Namensbestandteil, vollständiger Gastname, Buchungsreferenz, Belegungsbeschreibung und Zusatzinformation. Fehlt ein Trenntext, wird keine Information erfunden. Leerzeichen in Vergleichs- und Trenntexten bleiben erhalten. Ein Vorname wird nicht automatisch zu einem vollständigen Namen ergänzt. Diese Felder erweitern die importierte Kalenderbelegung; sie erzeugen keine vollständige Buchung oder einen Gästekartei-Eintrag.
|
||||
|
||||
## Vorschau, Entwurf und Aktivierung
|
||||
|
||||
Die Live-Vorschau zeigt Treffer je Regel, unerkannte Ereignisse, Klassifikation, erkannten Ursprung, extrahierte Informationen und die Originalereignisse. Sie verwendet den gespeicherten Analysestand und den aktuellen Entwurf. Für neue Kalenderdaten erneut analysieren.
|
||||
|
||||
**Speichern** speichert die Regeln zunächst als Entwurf. Bereits aktive Regeln bleiben für die automatischen Importe maßgeblich. **Auf Bestand anwenden** bestätigt und aktiviert den Entwurf und klassifiziert vorhandene Einträge neu. Danach verwenden auch folgende Importe diese Regeln.
|
||||
|
||||
Die Neuauswertung erhält lokale IDs, externe UIDs, Zeiträume und bestätigte persönliche Zuordnungen. Fehlende Originaldaten alter Einträge können anhand derselben UID aus der Analyse ergänzt werden; Löschen und Neuimport sind nicht erforderlich. Nicht zuordenbare alte Einträge bleiben unverändert. Hat ein neuerer Import seit der Analyse andere Originaldaten geliefert, verlangt die Anwendung eine neue Analyse. Abweichende Termine zwischen Analyse und gespeichertem Zeitraum werden als Prüffall markiert und durch die Klassifikation nicht verändert.
|
||||
|
||||
## Führende Repräsentation und Zuordnung
|
||||
|
||||
Eine erkannte Portalreservierung kann als führender Kandidat mit Vorrang gegenüber einer allgemeinen Sperre gekennzeichnet werden. Bei identischen Terminen zeigt die Vorschau mögliche Zusammenhänge mit vorhandenen Sperren und die Begründung **„exakt derselbe Zeitraum“**.
|
||||
|
||||
Dieser Hinweis ist kein Identitätsnachweis. Eine Regel erzeugt keine automatische Zusammenführung und hebt keine zusätzliche Sperre ungeprüft auf. Unter **Sperrzeiten → Belegung zuordnen / klären** wird die Identität persönlich bestätigt. Führende Kandidaten stehen dort bei den gleich terminierten Zielen zuerst. Bestätigte Verknüpfungen und persönlich bekannte Herkunft werden durch die Regelauswertung erhalten.
|
||||
|
||||
Die Sperrzeitenübersicht zeigt den erkannten Ereignistyp und verfügbare Namensinformationen. **iCal-Original & Erkennung** öffnet das Original und die treffende Regel.
|
||||
|
||||
## Exportinformationen je Zielkanal
|
||||
|
||||
Auf **Regeln & Exportfelder** werden die Zielfelder **SUMMARY**, **DESCRIPTION** und **LOCATION** mit ausgewählten Informationen befüllt. Möglich sind Belegungsbeschreibung, verfügbarer Vor- oder vollständiger Name, Buchungsreferenz, Zusatztext, Wohnung, bekannter Ursprung/Importkanal, Anreise, Abreise und Nächte. Reihenfolge und Trennzeichen sind konfigurierbar.
|
||||
|
||||
Ohne Zuordnung bleibt `SUMMARY:Belegt`. Nicht vorhandene Informationen werden ausgelassen. UID, Kalenderidentität und An-/Abreise können nicht durch eine Textzuordnung überschrieben werden. Die vorhandenen Herkunftsausschlüsse, Exportmodi, sicheren Pausen und Echo-Schutzregeln bleiben wirksam.
|
||||
|
||||
**Gastnamen ausdrücklich an diesen Zielkanal weitergeben** muss für die Namensfelder eingeschaltet werden. Diese Freigabe ist je Kanal getrennt und standardmäßig aus. Ohne sie werden Namensfelder auch bei einer bereits vorhandenen Zuordnung zur Laufzeit ausgeschlossen. Ein vollständiger Name ist nur verfügbar, wenn er tatsächlich aus der Quelle oder einer eigenen Buchung bekannt ist.
|
||||
|
||||
Die Exportvorschau zeigt die aktuell berechneten Ereignisse vor dem Speichern. Ein pausierter Export liefert weiterhin seinen eingefrorenen Stand. **Speichern aktiviert die Exportkonfiguration**; der Regelentwurf wird dadurch noch nicht für Import/Bestand aktiviert. Die tatsächliche Darstellung im Zielportal muss unabhängig geprüft werden. Ein Feedabruf oder eine bei uns vorhandene SUMMARY beweist keine Namensübernahme im Portal.
|
||||
|
||||
## Generischer erster Anwendungsfall
|
||||
|
||||
Die gewünschten Beispielregeln werden als normale Daten konfiguriert:
|
||||
|
||||
| Regel | Bedingung | Ergebnis |
|
||||
|---|---|---|
|
||||
| Portalreservierungen | SUMMARY beginnt mit `Reserved - ` | Portalreservierung; Ursprung aktueller Kanal; führender Kandidat; Text nach `Reserved - ` als Gastvorname/Namensbestandteil |
|
||||
| Allgemeine Sperren | SUMMARY ist gleich `Blocked` | Allgemeine Sperre; unbekannter Ursprung; zusätzliche Sperre; kein Gastname |
|
||||
|
||||
Dieselbe Oberfläche kann andere Felder, Werte und Trennzeichen eines dritten Anbieters verwenden. Die Muster sind keine Sonderfälle im Connector. Konkrete Anzahlen und Resultate des echten FeWo-direkt-Kalenders werden erst nach der tatsächlichen Analyse protokolliert.
|
||||
|
||||
## Nachweise und technische Orientierung
|
||||
|
||||
Die neuen Feature-Tests prüfen Feldentdeckung, Musterzahlen, alle visuellen Vergleiche, UND/ODER, Priorität, einfache Textextraktion, verschlüsselte Speicherung, Vorschau und Aktivierung, Bestandsidentität, persönliche Zuordnungen, unbekannte Drittanbieter, Rollen/Mandanten, HTML- und iCal-Escaping sowie individuelle Namensfreigabe und Exportzuordnung. Es werden ausschließlich synthetische Kalender in isolierter Testdatenbank verwendet.
|
||||
|
||||
Code: `ICalParser`, `ICalAnalysis`, `ICalRuleEngine`, `AnalyzeChannelCalendar`, `SaveChannelRules`, `ApplyChannelRules`, `ICalExportFields`, `ConfigureChannelExport` und die Ressourcenseite `ChannelRules`. Originaldaten und Interpretation erweitern die vorhandenen `Channel`-/`BlockedPeriod`-Modelle. Migration: `2026_10_27_183425_add_ical_analysis_rules_and_event_metadata`. Testdatei: `tests/Feature/ICalRuleEngineTest.php`.
|
||||
|
||||
Aktueller Auslieferungsstand: [Projektstand](../STATUS.md). Kalendergrundregeln und Herkunft: [iCal-Kanalkonfiguration](ical-kanalkonfiguration.md). Bisherige praktische Inbetriebnahme: [MVP-Bericht](ical-mvp-inbetriebnahme-2026-10-27.md).
|
||||
@@ -0,0 +1,18 @@
|
||||
@php($events = $this->exportPreview())
|
||||
<div class="space-y-3" style="min-width:0;overflow-wrap:anywhere">
|
||||
<p><strong>Exportvorschau: {{ count($events) }} Ereignisse</strong></p>
|
||||
<p class="text-sm">Ohne Feldzuordnung bleibt SUMMARY „Belegt“. Namen erscheinen nur bei ausdrücklicher Namensfreigabe und passender Zuordnung. Die tatsächliche Übernahme muss im Zielportal geprüft werden.</p>
|
||||
@foreach (array_slice($events, 0, 20) as $event)
|
||||
<details class="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<summary class="cursor-pointer">{{ \App\Channels\ICal\ICalParser::text($event['properties']['SUMMARY'][0]['value'] ?? 'Belegt') }}</summary>
|
||||
@foreach ($event['properties'] as $field => $values)
|
||||
@foreach ($values as $value)
|
||||
<p class="mt-2 text-sm"><strong>{{ $field }}:</strong> {{ \App\Channels\ICal\ICalParser::text($value['value']) }}</p>
|
||||
@endforeach
|
||||
@endforeach
|
||||
</details>
|
||||
@endforeach
|
||||
@if (count($events) > 20)
|
||||
<p class="text-sm">Die ersten 20 Ereignisse werden angezeigt.</p>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,30 @@
|
||||
@php($analysis = $this->record->ical_analysis)
|
||||
<div class="space-y-4" style="min-width:0;overflow-wrap:anywhere">
|
||||
@if (!$analysis)
|
||||
<p>Noch keine Analyse vorhanden. Importadresse zuerst an der Kalenderverbindung speichern, dann „Kalender analysieren“ wählen.</p>
|
||||
@else
|
||||
<p><strong>{{ $analysis['count'] }} Originalereignisse</strong> · analysiert am {{ $this->record->ical_analyzed_at?->format('d.m.Y H:i') }}.</p>
|
||||
<p class="text-sm">Die Feldnamen stammen aus diesem Kalender. Beispiele und Originalereignisse können personenbezogene Angaben enthalten.</p>
|
||||
@foreach ($analysis['fields'] as $name => $field)
|
||||
<details class="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<summary class="cursor-pointer font-medium">{{ $name }} · in {{ $field['count'] }} Ereignissen</summary>
|
||||
<div class="mt-3 space-y-3 text-sm">
|
||||
<p class="font-medium">Häufige Werte und Beispiele</p>
|
||||
@foreach ($field['values'] as $value => $count)
|
||||
<p>{{ $value === '' ? '(leer)' : $value }} <strong>· {{ $count }} Ereignisse</strong></p>
|
||||
@endforeach
|
||||
<p class="font-medium">Erkannte Textmuster</p>
|
||||
@foreach ($field['patterns'] as $pattern => $count)
|
||||
<p>{{ $pattern === '' ? '(leer)' : $pattern }} <strong>· {{ $count }} Ereignisse</strong></p>
|
||||
@endforeach
|
||||
</div>
|
||||
</details>
|
||||
@endforeach
|
||||
<details class="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<summary class="cursor-pointer font-medium">Kalender-Kopfdaten</summary>
|
||||
@foreach ($analysis['calendar'] as $field => $property)
|
||||
<p class="mt-2 text-sm"><strong>{{ $field }}:</strong> {{ $property['value'] }}</p>
|
||||
@endforeach
|
||||
</details>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,36 @@
|
||||
@php($preview = $this->preview())
|
||||
<div class="space-y-4" style="min-width:0;overflow-wrap:anywhere">
|
||||
<p><strong>{{ count($preview['rows']) }} Originalereignisse</strong> · {{ $preview['unmatched'] }} noch nicht erkannt.</p>
|
||||
@foreach ($preview['rules'] as $index => $rule)
|
||||
<p class="text-sm"><strong>{{ $rule['name'] ?? 'Neue Regel' }}:</strong> {{ $preview['counts'][$index] ?? 0 }} Treffer nach Priorität.</p>
|
||||
@endforeach
|
||||
@foreach ($preview['rows'] as $row)
|
||||
@php($result = $row['result'])
|
||||
<details wire:key="preview-{{ sha1($row['uid']) }}" class="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<summary class="cursor-pointer font-medium">{{ $row['summary'] }} · {{ \App\Channels\ICal\ICalRuleEngine::TYPES[$result['event_type']] ?? 'Nicht erkannt' }}</summary>
|
||||
<div class="mt-3 space-y-2 text-sm">
|
||||
<p><strong>Zeitraum:</strong> {{ $row['starts_on'] ?? 'kein belegender Zeitraum' }} @if ($row['ends_on']) bis {{ $row['ends_on'] }} (Abreise exklusiv) @endif</p>
|
||||
<p><strong>UID:</strong> {{ $row['uid'] }}</p>
|
||||
<p><strong>Treffende Regel:</strong> {{ $result['rule'] ?? 'Keine' }}</p>
|
||||
<p><strong>Einordnung:</strong> {{ \App\Channels\ICal\ICalRuleEngine::REPRESENTATIONS[$result['representation']] ?? 'Unbestimmt' }} · Priorität {{ $result['priority'] }}</p>
|
||||
<p><strong>Erkannter Ursprung:</strong> {{ $result['origin_channel_id'] ? ($this->record->property->channels->firstWhere('id', $result['origin_channel_id'])?->name ?? 'Unbekannt') : 'Unbekannt' }}</p>
|
||||
@foreach ($result['fields'] as $field => $value)
|
||||
<p><strong>{{ \App\Channels\ICal\ICalRuleEngine::TARGETS[$field] ?? $field }}:</strong> {{ $value }}</p>
|
||||
@endforeach
|
||||
@if ($row['candidates'])
|
||||
<div class="rounded-lg bg-gray-50 p-3 dark:bg-gray-900">
|
||||
<p class="font-medium">Mögliche Zusammenhänge: exakt derselbe Zeitraum</p>
|
||||
<p>Das ist ein Hinweis, kein Identitätsnachweis. Eine erkannte Reservierung kann die führende Darstellung sein. Unter „Sperrzeiten → Belegung zuordnen / klären“ persönlich zuordnen.</p>
|
||||
@foreach ($row['candidates'] as $candidate)
|
||||
<p>Sperre #{{ $candidate['id'] }} · {{ $candidate['reason'] }} · Führungsvorrang {{ $candidate['priority'] }}</p>
|
||||
@endforeach
|
||||
</div>
|
||||
@endif
|
||||
<details>
|
||||
<summary class="cursor-pointer font-medium">Originalereignis anzeigen</summary>
|
||||
<pre class="mt-2 text-xs" style="white-space:pre-wrap;overflow-wrap:anywhere">{{ $row['raw'] }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</details>
|
||||
@endforeach
|
||||
</div>
|
||||
@@ -0,0 +1,365 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ApplyChannelRules;
|
||||
use App\Actions\ConfigureChannelExport;
|
||||
use App\Actions\SaveChannelRules;
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalAnalysis;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Livewire\Livewire;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ICalRuleEngineTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_unknown_fields_parameters_originals_and_38_event_pattern_counts_are_preserved(): void
|
||||
{
|
||||
$events = '';
|
||||
for ($i = 0; $i < 38; $i++) {
|
||||
$events .= self::event('u'.$i, $i < 9 ? 'Reserved - Name'.$i : 'Blocked', extra: "X-UNKNOWN;LANGUAGE=de:Wert\\, eins\r\nX-UNKNOWN:Zweiter Wert\r\n");
|
||||
}
|
||||
$analysis = app(ICalAnalysis::class)->summarize(app(ICalParser::class)->parseDocument(self::feed($events)));
|
||||
$this->assertSame(38, $analysis['count']);
|
||||
$this->assertSame(9, $analysis['fields']['SUMMARY']['patterns']['Reserved - …']);
|
||||
$this->assertSame(29, $analysis['fields']['SUMMARY']['values']['Blocked']);
|
||||
$this->assertSame(['LANGUAGE=de'], $analysis['events'][0]['properties']['X-UNKNOWN'][0]['params']);
|
||||
$this->assertCount(2, $analysis['events'][0]['properties']['X-UNKNOWN']);
|
||||
$this->assertSame('Wert, eins', ICalParser::text($analysis['events'][0]['properties']['X-UNKNOWN'][0]['value']));
|
||||
$this->assertStringContainsString('SUMMARY:Reserved - Name0', $analysis['events'][0]['raw']);
|
||||
}
|
||||
|
||||
public static function comparisons(): array
|
||||
{
|
||||
return [['equals', 'paid', 'PAID', true], ['equals', 'paid', 'open', false], ['not_equals', 'paid', 'open', true], ['not_equals', 'paid', 'PAID', false], ['starts_with', 'paid', 'Paid - Guest', true], ['ends_with', 'paid', 'Booking paid', true], ['contains', 'paid', 'Booking paid successfully', true], ['contains', 'paid', 'open', false], ['exists', '', '', true], ['empty', '', '', true], ['empty', '', 'present', false]];
|
||||
}
|
||||
|
||||
#[DataProvider('comparisons')]
|
||||
public function test_literal_comparisons_need_no_regex(string $operator, string $value, string $actual, bool $expected): void
|
||||
{
|
||||
$rule = self::rule(['conditions' => [['field' => 'X-STATE', 'operator' => $operator, 'value' => $value]]]);
|
||||
$this->assertSame($expected, app(ICalRuleEngine::class)->evaluate(new Channel, ['X-STATE' => [['value' => $actual, 'params' => []]]], [$rule])['matched']);
|
||||
}
|
||||
|
||||
public function test_priority_and_or_and_case_sensitive_matching(): void
|
||||
{
|
||||
$engine = app(ICalRuleEngine::class);
|
||||
$properties = ['SUMMARY' => [['value' => 'Reserved - Lea', 'params' => []]]];
|
||||
$conditions = [['field' => 'X-MISSING', 'operator' => 'empty'], ['field' => 'SUMMARY', 'operator' => 'equals', 'value' => 'Other']];
|
||||
$this->assertFalse($engine->evaluate(new Channel, $properties, [self::rule(['conditions' => $conditions])])['matched']);
|
||||
$this->assertTrue($engine->evaluate(new Channel, $properties, [self::rule(['conditions' => $conditions, 'match' => 'any'])])['matched']);
|
||||
$this->assertSame('Vorrang', $engine->evaluate(new Channel, $properties, [self::rule(), self::rule(['name' => 'Vorrang', 'priority' => 1])])['rule']);
|
||||
$this->assertFalse($engine->evaluate(new Channel, $properties, [self::rule(['case_sensitive' => true, 'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'reserved']]])])['matched']);
|
||||
}
|
||||
|
||||
public static function extractions(): array
|
||||
{
|
||||
return [['after', 'Reserved - ', '', 'Lea | Ende'], ['before', '', ' |', 'Reserved - Lea'], ['between', 'Reserved - ', ' |', 'Lea'], ['after', 'Missing', '', null]];
|
||||
}
|
||||
|
||||
#[DataProvider('extractions')]
|
||||
public function test_marker_extraction_does_not_invent_missing_text(string $method, string $start, string $end, ?string $expected): void
|
||||
{
|
||||
$rule = self::rule(['extractions' => [['field' => 'SUMMARY', 'target' => 'guest_first_name', 'method' => $method, 'start' => $start, 'end' => $end]]]);
|
||||
$result = app(ICalRuleEngine::class)->evaluate(new Channel, ['SUMMARY' => [['value' => 'Reserved - Lea | Ende', 'params' => []]]], [$rule]);
|
||||
$this->assertSame($expected, $result['fields']['guest_first_name'] ?? null);
|
||||
}
|
||||
|
||||
public function test_analysis_reads_and_encrypts_original_data_without_importing_occupations(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
Http::preventStrayRequests();
|
||||
Http::fake(['https://portal.example/calendar.ics' => Http::response(self::calendar())]);
|
||||
$channel = app(AnalyzeChannelCalendar::class)->handle($channel);
|
||||
$this->assertSame(2, $channel->ical_analysis['count']);
|
||||
$this->assertSame(0, BlockedPeriod::count());
|
||||
$this->assertNull($channel->last_success_at);
|
||||
$this->assertStringNotContainsString('Reserved - Lea', DB::table('channels')->where('id', $channel->id)->value('ical_analysis'));
|
||||
$this->assertArrayNotHasKey('ical_analysis', $channel->toArray());
|
||||
Http::assertSentCount(1);
|
||||
}
|
||||
|
||||
public function test_draft_activation_and_reclassification_preserve_ids_uids_dates_and_stable_modified_time(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$this->import($channel);
|
||||
$identity = fn ($rows): array => $rows->map(fn ($b): array => [$b->id, $b->external_uid, $b->starts_on->toDateString(), $b->ends_on->toDateString()])->all();
|
||||
$before = $identity($channel->blockedPeriods()->orderBy('id')->get());
|
||||
app(SaveChannelRules::class)->handle($channel, self::rules());
|
||||
app(SyncChannel::class)->handle($channel->fresh());
|
||||
$this->assertSame('unknown', $channel->blockedPeriods()->first()->ical_event_type);
|
||||
$counts = app(ApplyChannelRules::class)->handle($channel->fresh());
|
||||
$rows = $channel->blockedPeriods()->orderBy('id')->get();
|
||||
$this->assertSame(['classified' => 2, 'missing_raw' => 0], $counts);
|
||||
$this->assertSame($before, $identity($rows));
|
||||
$this->assertSame('portal_reservation', $rows[0]->ical_event_type);
|
||||
$this->assertSame('Lea', $rows[0]->ical_interpretation['fields']['guest_first_name']);
|
||||
$this->assertSame($channel->id, $rows[0]->origin_channel_id);
|
||||
$this->assertGreaterThan(0, $rows[0]->leading_priority);
|
||||
$this->assertSame('block', $rows[1]->ical_event_type);
|
||||
$this->assertNull($rows[1]->origin_channel_id);
|
||||
$this->assertFalse($rows[1]->is_representation);
|
||||
$this->assertStringNotContainsString('Lea', DB::table('blocked_periods')->where('id', $rows[0]->id)->value('ical_raw'));
|
||||
$modified = $rows[0]->updated_at;
|
||||
$this->travel(3)->minutes();
|
||||
app(SyncChannel::class)->handle($channel->fresh());
|
||||
$this->assertTrue($modified->equalTo($rows[0]->fresh()->updated_at));
|
||||
}
|
||||
|
||||
public function test_old_inventory_gets_originals_without_reimport_and_preserves_confirmed_mapping(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$canonical = BlockedPeriod::factory()->for($channel->property)->create(['starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']);
|
||||
$copy = BlockedPeriod::factory()->for($channel->property)->create(['source' => 'channel', 'channel_id' => $channel->id, 'external_uid' => 'one', 'starts_on' => '2027-05-23', 'ends_on' => '2027-05-30', 'canonical_block_id' => $canonical->id, 'is_representation' => true, 'reviewed_at' => now()]);
|
||||
app(SaveChannelRules::class)->handle($channel, self::rules());
|
||||
Http::preventStrayRequests();
|
||||
Http::fake();
|
||||
app(ApplyChannelRules::class)->handle($channel->fresh());
|
||||
$copy->refresh();
|
||||
$this->assertSame($canonical->id, $copy->canonical_block_id);
|
||||
$this->assertTrue($copy->is_representation);
|
||||
$this->assertNull($copy->origin_channel_id);
|
||||
$this->assertSame('Lea', $copy->ical_interpretation['fields']['guest_first_name']);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_undiscovered_fields_regex_and_foreign_origins_cannot_be_saved(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
foreach ([self::rule(['conditions' => [['field' => 'SECRET', 'operator' => 'equals', 'value' => 'x']]]), self::rule(['conditions' => [['field' => 'SUMMARY', 'operator' => 'regex', 'value' => '.*']]]), self::rule(['origin' => 'channel:9999'])] as $rule) {
|
||||
try {
|
||||
app(SaveChannelRules::class)->handle($channel, [$rule]);
|
||||
$this->fail('Invalid rules must be rejected.');
|
||||
} catch (ValidationException) {
|
||||
$this->assertNull($channel->fresh()->ical_rules);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_unknown_portal_is_analysed_configured_and_activated_through_the_editor(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$channel->forceFill(['name' => 'Dritter unbekannter Anbieter', 'ical_analysis' => null])->save();
|
||||
$this->actingAs(User::factory()->create());
|
||||
Http::preventStrayRequests();
|
||||
Http::fake(['https://portal.example/calendar.ics' => Http::response(self::feed(self::event('third', 'Andere Bezeichnung', extra: "X-BOOKING-STATE:HOST\r\nX-PERSON:Guest=Noah|Confirmed\r\n")))]);
|
||||
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])->callAction('analyze')->assertNotified('1 Originalereignisse analysiert')->assertSee('X-BOOKING-STATE');
|
||||
$rule = self::rule(['conditions' => [['field' => 'X-BOOKING-STATE', 'operator' => 'equals', 'value' => 'HOST']], 'extractions' => [['field' => 'X-PERSON', 'target' => 'guest_first_name', 'method' => 'between', 'start' => 'Guest=', 'end' => '|']]]);
|
||||
$page->fillForm(['rules' => [$rule]])->assertSee('Noah')->call('save')->assertHasNoFormErrors();
|
||||
$this->assertSame('X-BOOKING-STATE', $channel->fresh()->ical_rules[0]['conditions'][0]['field']);
|
||||
$this->assertNull($channel->fresh()->ical_active_rules);
|
||||
$page->callAction('applyRules')->assertHasNoFormErrors();
|
||||
$this->assertCount(1, $channel->fresh()->ical_active_rules);
|
||||
Http::assertSentCount(1);
|
||||
}
|
||||
|
||||
public function test_editor_live_preview_does_not_mutate_inventory_before_explicit_application(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$this->import($channel);
|
||||
$this->actingAs(User::factory()->create());
|
||||
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])->fillForm(['rules' => self::rules()])->assertSee('Lea')->assertSee('Portalreservierung');
|
||||
$this->assertSame('unknown', $channel->blockedPeriods()->first()->ical_event_type);
|
||||
$page->callAction('applyRules')->assertHasNoFormErrors()->assertNotified('2 Einträge neu klassifiziert');
|
||||
$this->assertSame(0, Booking::count());
|
||||
$this->assertSame(2, $channel->blockedPeriods()->count());
|
||||
$this->assertSame('portal_reservation', $channel->blockedPeriods()->first()->ical_event_type);
|
||||
}
|
||||
|
||||
public function test_export_requires_names_permission_and_keeps_uid_dates_and_origin_exclusion(): void
|
||||
{
|
||||
$source = $this->channel();
|
||||
$this->import($source);
|
||||
app(SaveChannelRules::class)->handle($source, self::rules());
|
||||
app(ApplyChannelRules::class)->handle($source->fresh());
|
||||
$target = Channel::factory()->for($source->property)->create();
|
||||
$mapping = [['field' => 'SUMMARY', 'items' => ['occupation_label', 'guest_first_name'], 'separator' => ' – ']];
|
||||
$parser = app(ICalParser::class);
|
||||
$feed = app(ICalFeed::class);
|
||||
$before = $parser->parse($feed->build($target));
|
||||
try {
|
||||
app(ConfigureChannelExport::class)->handle($target, $mapping, false);
|
||||
$this->fail('Names need explicit permission.');
|
||||
} catch (ValidationException $e) {
|
||||
$this->assertArrayHasKey('export_names', $e->errors());
|
||||
}
|
||||
$this->assertStringNotContainsString('Lea', $feed->build($target));
|
||||
$target = app(ConfigureChannelExport::class)->handle($target, $mapping, true);
|
||||
$after = $parser->parse($feed->build($target));
|
||||
$this->assertSame('Portalreservierung – Lea', $after[0]->summary);
|
||||
$this->assertSame(array_map(fn ($p) => [$p->uid, $p->startsOn->toDateString(), $p->endsOn->toDateString()], $before), array_map(fn ($p) => [$p->uid, $p->startsOn->toDateString(), $p->endsOn->toDateString()], $after));
|
||||
$this->assertStringNotContainsString('BEGIN:VEVENT', $feed->build($source->fresh()));
|
||||
$target->forceFill(['ical_export_names' => false])->save();
|
||||
$this->assertStringNotContainsString('Lea', $feed->build($target));
|
||||
}
|
||||
|
||||
public function test_export_escapes_injected_lines_and_does_not_invent_full_guest_names(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$block = BlockedPeriod::factory()->for($channel->property)->create();
|
||||
$block->forceFill(['ical_interpretation' => ['fields' => ['guest_first_name' => "Lea, Test;\nUID:evil", 'note' => 'Hinweis']]])->save();
|
||||
$channel = app(ConfigureChannelExport::class)->handle($channel, [['field' => 'SUMMARY', 'items' => ['guest_first_name']], ['field' => 'DESCRIPTION', 'items' => ['guest_full_name', 'note']]], true);
|
||||
$document = app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($channel));
|
||||
$this->assertCount(1, $document['events']);
|
||||
$this->assertSame("Lea, Test;\nUID:evil", $document['events'][0]['period']->summary);
|
||||
$this->assertSame('Hinweis', $document['events'][0]['properties']['DESCRIPTION'][0]['value']);
|
||||
$this->assertSame('block-'.$block->id.'@fewo-stommer', $document['events'][0]['uid']);
|
||||
}
|
||||
|
||||
public function test_editor_enforces_role_and_tenant_isolation(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$this->actingAs(User::factory()->role(UserRole::Content)->create());
|
||||
Livewire::test(ChannelRules::class, ['record' => $channel->id])->assertForbidden();
|
||||
app(TenantContext::class)->set(Tenant::factory()->create());
|
||||
$this->actingAs(User::factory()->create());
|
||||
Livewire::test(ChannelRules::class, ['record' => $channel->id])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_literal_spaces_survive_the_actual_http_middleware_for_live_rule_updates(): void
|
||||
{
|
||||
Route::post('/_ical_literal_test', fn (Request $request) => response()->json($request->all()));
|
||||
$updates = ['data.rules.rule.conditions.condition.value' => 'Reserved - ', 'data.rules.rule.extractions.extraction.start' => 'Reserved - ', 'data.export_mapping.mapping.separator' => ' – '];
|
||||
$response = $this->postJson('/_ical_literal_test', ['components' => [['updates' => $updates]], 'other' => ' trimmed ']);
|
||||
$response->assertOk()->assertExactJson(['components' => [['updates' => $updates]], 'other' => 'trimmed']);
|
||||
}
|
||||
|
||||
public function test_export_mapping_can_be_previewed_and_saved_from_the_same_page(): void
|
||||
{
|
||||
$source = $this->channel();
|
||||
$this->import($source);
|
||||
app(SaveChannelRules::class)->handle($source, self::rules());
|
||||
app(ApplyChannelRules::class)->handle($source->fresh());
|
||||
$target = Channel::factory()->for($source->property)->create();
|
||||
$this->actingAs(User::factory()->create());
|
||||
$page = Livewire::test(ChannelRules::class, ['record' => $target->id])->fillForm(['export_names' => true, 'export_mapping' => [['field' => 'SUMMARY', 'items' => ['guest_first_name'], 'separator' => ' – ']]])->assertSee('Lea');
|
||||
$this->assertFalse((bool) $target->fresh()->ical_export_names);
|
||||
$this->assertStringNotContainsString('Lea', app(ICalFeed::class)->build($target));
|
||||
$page->call('save')->assertHasNoFormErrors();
|
||||
$this->assertTrue($target->fresh()->ical_export_names);
|
||||
$this->assertStringContainsString('SUMMARY:Lea', app(ICalFeed::class)->build($target->fresh()));
|
||||
}
|
||||
|
||||
public function test_own_bookings_supply_real_full_names_only_when_enabled_for_that_target(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$booking = Booking::factory()->for($channel->property)->create(['status' => 'confirmed', 'arrival' => '2027-05-23', 'departure' => '2027-05-30']);
|
||||
$booking->guest->update(['first_name' => 'Synthetisch', 'last_name' => 'Testgast']);
|
||||
$channel = app(ConfigureChannelExport::class)->handle($channel, [['field' => 'DESCRIPTION', 'items' => ['guest_full_name', 'booking_reference'], 'separator' => ' / ']], true);
|
||||
$event = app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($channel))['events'][0];
|
||||
$this->assertSame('Synthetisch Testgast / '.$booking->reference, $event['properties']['DESCRIPTION'][0]['value']);
|
||||
$this->assertSame('booking-'.$booking->id.'@fewo-stommer', $event['uid']);
|
||||
}
|
||||
|
||||
public function test_a_newer_import_cannot_be_overwritten_by_an_old_analysis_during_apply(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$this->import($channel);
|
||||
app(SaveChannelRules::class)->handle($channel, self::rules());
|
||||
$this->travel(2)->minutes();
|
||||
$block = $channel->blockedPeriods()->first();
|
||||
$block->forceFill(['ical_raw' => 'Newer original'])->saveQuietly();
|
||||
try {
|
||||
app(ApplyChannelRules::class)->handle($channel->fresh());
|
||||
$this->fail('Stale preview must not overwrite a newer import.');
|
||||
} catch (ValidationException $exception) {
|
||||
$this->assertArrayHasKey('rules', $exception->errors());
|
||||
}
|
||||
$this->assertSame('Newer original', $block->fresh()->ical_raw);
|
||||
$this->assertNull($channel->fresh()->ical_active_rules);
|
||||
}
|
||||
|
||||
public function test_ambiguous_duplicate_uids_with_different_original_fields_are_rejected(): void
|
||||
{
|
||||
$this->expectException(ChannelSyncException::class);
|
||||
app(ICalParser::class)->parseDocument(self::feed(self::event('one', 'Reserved - Lea').self::event('one', 'Blocked')));
|
||||
}
|
||||
|
||||
public function test_original_html_is_escaped_in_analysis_and_failed_analysis_keeps_the_previous_snapshot(): void
|
||||
{
|
||||
$channel = $this->channel();
|
||||
$payload = '<script>alert("ical-source")</script>';
|
||||
Http::preventStrayRequests();
|
||||
Http::fake(['https://portal.example/calendar.ics' => Http::sequence()->push(self::feed(self::event('html', $payload)))->push('<html>Login</html>')]);
|
||||
$channel = app(AnalyzeChannelCalendar::class)->handle($channel);
|
||||
$this->actingAs(User::factory()->create());
|
||||
Livewire::test(ChannelRules::class, ['record' => $channel->id])->assertSee($payload)->assertDontSee($payload, escape: false);
|
||||
$snapshot = $channel->ical_analysis;
|
||||
try {
|
||||
app(AnalyzeChannelCalendar::class)->handle($channel);
|
||||
$this->fail('An invalid feed must not replace an analysis.');
|
||||
} catch (ChannelSyncException) {
|
||||
$this->assertSame($snapshot, $channel->fresh()->ical_analysis);
|
||||
}
|
||||
}
|
||||
|
||||
private function channel(): Channel
|
||||
{
|
||||
$this->travelTo(CarbonImmutable::parse('2026-10-27 12:00'));
|
||||
$this->seed(PropertySeeder::class);
|
||||
$property = Property::sole();
|
||||
app(TenantContext::class)->set($property->tenant);
|
||||
$channel = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/calendar.ics']]);
|
||||
$channel->forceFill(['ical_analysis' => app(ICalAnalysis::class)->summarize(app(ICalParser::class)->parseDocument(self::calendar())), 'ical_analyzed_at' => now()])->save();
|
||||
|
||||
return $channel;
|
||||
}
|
||||
|
||||
private function import(Channel $channel): void
|
||||
{
|
||||
Http::preventStrayRequests();
|
||||
Http::fake(['https://portal.example/calendar.ics' => Http::response(self::calendar())]);
|
||||
Mail::fake();
|
||||
$this->assertTrue(app(SyncChannel::class)->handle($channel)->successful);
|
||||
}
|
||||
|
||||
public static function rules(): array
|
||||
{
|
||||
return [self::rule(), self::rule(['name' => 'Allgemeine Sperre', 'priority' => 20, 'conditions' => [['field' => 'SUMMARY', 'operator' => 'equals', 'value' => 'Blocked']], 'event_type' => 'block', 'origin' => 'unknown', 'representation' => 'additional_block', 'extractions' => []])];
|
||||
}
|
||||
|
||||
public static function rule(array $overrides = []): array
|
||||
{
|
||||
return [...['name' => 'Reservierungen erkennen', 'enabled' => true, 'priority' => 10, 'match' => 'all', 'case_sensitive' => false, 'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reserved - ']], 'event_type' => 'portal_reservation', 'origin' => 'current', 'representation' => 'leading_candidate', 'extractions' => [['field' => 'SUMMARY', 'target' => 'guest_first_name', 'method' => 'after', 'start' => 'Reserved - ', 'end' => '']]], ...$overrides];
|
||||
}
|
||||
|
||||
private static function event(string $uid, string $summary, string $start = '20270523', string $end = '20270530', string $extra = ''): string
|
||||
{
|
||||
return "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261027T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:{$summary}\r\n{$extra}END:VEVENT\r\n";
|
||||
}
|
||||
|
||||
private static function feed(string $events): string
|
||||
{
|
||||
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic//DE\r\n{$events}END:VCALENDAR\r\n";
|
||||
}
|
||||
|
||||
private static function calendar(): string
|
||||
{
|
||||
return self::feed(self::event('one', 'Reserved - Lea').self::event('two', 'Blocked', '20270601', '20270608'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user