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,
|
||||
|
||||
Reference in new issue
Block a user