Files
fewo-stommer/tests/Feature/ICalRuleEngineTest.php
T
Lars a0497fcccd
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s
iCal-Regelanwendung bei Zeitstempelupdates erlauben und Dialogfehler anzeigen
2026-10-29 16:25:29 +01:00

574 lines
34 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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\Availability\OccupancyOverview;
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\Pages\OccupancyCalendar;
use App\Filament\Resources\Channels\Pages\ChannelRules;
use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Filament\Notifications\Notification;
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_visible_header_action_saves_repeated_rule_changes_without_activating_the_draft(): void
{
$channel = $this->channel();
$this->actingAs(User::factory()->create());
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])
->assertActionVisible('saveDraft')->assertActionVisible('applyRules')
->assertSee('Es sind noch keine Erkennungsregeln aktiviert.')
->fillForm(['rules' => [self::rule()]])->callAction('saveDraft')->assertHasNoFormErrors()
->assertNoRedirect()
->assertNotified('Regelentwurf und Exportkonfiguration gespeichert')
->assertSee('Gespeicherte Regeln sind noch nicht aktiv.');
$updated = self::rule(['name' => 'Geänderte Erkennung', 'priority' => 15]);
$page->assertActionVisible('saveDraft')->fillForm(['rules' => [$updated]])
->callAction('saveDraft')->assertHasNoFormErrors()->assertNoRedirect();
$this->assertSame('Geänderte Erkennung', $channel->fresh()->ical_rules[0]['name']);
$this->assertSame(15, $channel->fresh()->ical_rules[0]['priority']);
$this->assertNull($channel->fresh()->ical_active_rules);
Livewire::test(ChannelRules::class, ['record' => $channel->id])->assertActionVisible('saveDraft')
->assertSee('Geänderte Erkennung')->assertSee('Gespeicherte Regeln sind noch nicht aktiv.');
}
public function test_applying_primary_source_rule_shows_full_guest_name_and_keeps_a_second_calendar_separate_until_confirmed(): void
{
$source = $this->channel();
$source->update(['name' => 'Buchungsdatenquelle', 'export_enabled' => false]);
$mirror = Channel::factory()->for($source->property)->create([
'name' => 'Zweiter Kalender', 'settings' => ['import_url' => 'https://portal.example/mirror.ics'],
]);
$calendar = self::feed(self::event('primary-stay', 'Reservation: Nora Beispiel'));
Http::preventStrayRequests();
Http::fake([
'https://portal.example/calendar.ics' => Http::response($calendar),
'https://portal.example/mirror.ics' => Http::response(self::feed(self::event('mirror-stay', 'Blocked'))),
]);
Mail::fake();
$this->assertTrue(app(SyncChannel::class)->handle($source)->successful);
$this->assertTrue(app(SyncChannel::class)->handle($mirror)->successful);
$source = app(AnalyzeChannelCalendar::class)->handle($source);
$primary = $source->blockedPeriods()->sole();
$secondary = $mirror->blockedPeriods()->sole();
$identity = $primary->only(['id', 'external_uid', 'starts_on', 'ends_on', 'channel_id']);
$rule = self::rule([
'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reservation: ']],
'extractions' => [['field' => 'SUMMARY', 'target' => 'guest_full_name', 'method' => 'after', 'start' => 'Reservation: ']],
]);
$this->actingAs(User::factory()->create());
$page = Livewire::test(ChannelRules::class, ['record' => $source->id])
->fillForm(['rules' => [$rule]])->callAction('saveDraft')->assertHasNoFormErrors();
$this->assertSame('unknown', $primary->fresh()->occupationKind()->value);
$this->assertNull($primary->fresh()->guestName());
$page->assertSee(PortalOccupationResource::getUrl('view', ['record' => $secondary->id]), escape: false)
->callAction('applyRules')->assertHasNoFormErrors()
->assertSee('Gespeicherter Entwurf und aktive Regeln stimmen überein.');
$primary->refresh();
$this->assertSame('reservation', $primary->occupationKind()->value);
$this->assertSame('Nora Beispiel', $primary->guestName());
$this->assertSame($source->id, $primary->origin_channel_id);
$this->assertGreaterThan(0, $primary->leading_priority);
$this->assertEquals($identity, $primary->only(array_keys($identity)));
$this->assertSame('unknown', $secondary->fresh()->occupationKind()->value);
$this->assertFalse($secondary->fresh()->is_representation);
$this->assertSame(0, Guest::count());
$this->assertCount(2, app(OccupancyOverview::class)->records(includeBlocks: true));
Livewire::test(ViewPortalOccupation::class, ['record' => $secondary->id])
->callAction('resolve', ['resolution' => 'block', 'target_id' => $primary->id, 'origin_channel_id' => $source->id])
->assertHasNoActionErrors();
$this->assertTrue($secondary->fresh()->is_representation);
$this->assertSame($primary->id, $secondary->fresh()->canonical_block_id);
$this->assertCount(1, app(OccupancyOverview::class)->records(includeBlocks: true));
Livewire::test(OccupancyCalendar::class, ['month' => '2027-05', 'propertyId' => $source->property_id])
->assertSee('Nora Beispiel')->assertSee('Portalreservierung')->assertDontSee('occupancy-event kind-unknown', escape: false);
Http::assertSentCount(3);
}
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));
$target = app(ConfigureChannelExport::class)->handle($target, $mapping, false);
$this->assertFalse($target->ical_export_names);
$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()));
$page->fillForm(['export_names' => false])->call('save')->assertHasNoFormErrors();
$this->assertFalse($target->fresh()->ical_export_names);
$this->assertStringNotContainsString('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);
}
#[DataProvider('timestampChanges')]
public function test_timestamp_only_sync_updates_do_not_block_applying_rules_or_replace_newer_originals(bool $changeStamp, bool $changeModified): void
{
$channel = $this->channel();
$initial = str_replace('DTSTAMP:20261027T090000Z', "DTSTAMP:20261027T090000Z\r\nLAST-MODIFIED:20261027T090000Z", self::calendar());
$calendar = str_replace(
['DTSTAMP:20261027T090000Z', 'LAST-MODIFIED:20261027T090000Z'],
[$changeStamp ? 'DTSTAMP:20261027T090500Z' : 'DTSTAMP:20261027T090000Z', $changeModified ? 'LAST-MODIFIED:20261027T090500Z' : 'LAST-MODIFIED:20261027T090000Z'],
$initial,
);
Http::preventStrayRequests();
Http::fake(['https://portal.example/calendar.ics' => Http::sequence()->push($initial)->push($calendar)]);
Mail::fake();
$this->assertTrue(app(SyncChannel::class)->handle($channel)->successful);
$this->travel(5)->minutes();
$this->assertTrue(app(SyncChannel::class)->handle($channel)->successful);
$block = $channel->blockedPeriods()->where('external_uid', 'one')->sole();
$this->assertStringContainsString(($changeStamp ? 'DTSTAMP' : 'LAST-MODIFIED').':20261027T090500Z', $block->ical_raw);
$original = $block->only(['id', 'external_uid', 'starts_on', 'ends_on', 'ical_raw', 'ical_properties']);
$this->actingAs(User::factory()->create());
Livewire::test(ChannelRules::class, ['record' => $channel->id])
->fillForm(['rules' => self::rules()])
->mountAction('applyRules')->assertActionMounted('applyRules')
->callMountedAction()->assertHasNoFormErrors()->assertActionNotMounted()
->assertNotified('2 Einträge neu klassifiziert')
->assertSee('Gespeicherter Entwurf und aktive Regeln stimmen überein.');
$this->assertEquals($original, $block->fresh()->only(array_keys($original)));
$this->assertSame('portal_reservation', $block->fresh()->ical_event_type);
$this->assertSame('Lea', $block->fresh()->guestName());
$this->assertSame($channel->fresh()->ical_rules, $channel->fresh()->ical_active_rules);
Http::assertSentCount(2);
}
public static function timestampChanges(): array
{
return ['DTSTAMP' => [true, false], 'LAST-MODIFIED' => [false, true], 'both' => [true, true]];
}
public function test_changed_import_closes_confirmation_and_shows_why_rules_were_not_activated(): void
{
$channel = $this->channel();
$this->import($channel);
$this->actingAs(User::factory()->create());
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])
->fillForm(['rules' => self::rules()])->mountAction('applyRules')->assertActionMounted('applyRules');
$this->travel(5)->minutes();
$block = $channel->blockedPeriods()->where('external_uid', 'one')->sole();
$newEvent = app(ICalParser::class)->parseDocument(self::feed(self::event('one', 'Reserved - Noah')))['events'][0];
$block->forceFill(['ical_raw' => $newEvent['raw'], 'ical_properties' => $newEvent['properties']])->saveQuietly();
$page->callMountedAction()->assertActionNotMounted()
->assertNotified(Notification::make()->title('Regeln wurden nicht angewendet')
->body('Der Importbestand hat sich seit der Vorschau geändert. Den Kalender erneut analysieren und die Vorschau prüfen.')
->danger()->persistent())
->assertSee('Es sind noch keine Erkennungsregeln aktiviert.');
$this->assertNull($channel->fresh()->ical_rules);
$this->assertNull($channel->fresh()->ical_active_rules);
$this->assertSame('unknown', $block->fresh()->ical_event_type);
$this->assertSame($newEvent['raw'], $block->fresh()->ical_raw);
$this->assertSame($newEvent['properties'], $block->fresh()->ical_properties);
$this->assertCount(2, $page->get('data.rules'));
}
public function test_invalid_extraction_is_visible_after_confirmation_and_can_be_corrected_without_losing_the_draft(): void
{
$channel = $this->channel();
$this->actingAs(User::factory()->create());
$rule = self::rule(['extractions' => [['field' => 'SUMMARY', 'target' => 'guest_full_name', 'method' => 'after', 'start' => '']]]);
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])
->fillForm(['rules' => [$rule]])->mountAction('applyRules')->callMountedAction()
->assertActionNotMounted()
->assertNotified(Notification::make()->title('Regeln wurden nicht angewendet')
->body('Für die Textextraktion die benötigten Anfangs- und Endtexte angeben.')->danger()->persistent());
$this->assertNull($channel->fresh()->ical_rules);
$this->assertNull($channel->fresh()->ical_active_rules);
$page->fillForm(['rules' => [self::rule()]])->mountAction('applyRules')->callMountedAction()
->assertHasNoFormErrors()->assertActionNotMounted()->assertNotified('0 Einträge neu klassifiziert');
$this->assertCount(1, $channel->fresh()->ical_active_rules);
}
public function test_a_rule_using_a_changed_timestamp_requires_a_new_preview(): void
{
$channel = $this->channel();
$this->import($channel);
$rule = self::rule(['conditions' => [['field' => 'DTSTAMP', 'operator' => 'equals', 'value' => '20261027T090000Z']]]);
app(SaveChannelRules::class)->handle($channel, [$rule]);
$this->travel(5)->minutes();
$block = $channel->blockedPeriods()->where('external_uid', 'one')->sole();
$newEvent = app(ICalParser::class)->parseDocument(self::feed(str_replace('DTSTAMP:20261027T090000Z', 'DTSTAMP:20261027T090500Z', self::event('one', 'Reserved - Lea'))))['events'][0];
$block->forceFill(['ical_raw' => $newEvent['raw'], 'ical_properties' => $newEvent['properties']])->saveQuietly();
try {
app(ApplyChannelRules::class)->handle($channel->fresh());
$this->fail('A changed rule result must require a new preview.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('rules', $exception->errors());
}
$this->assertNull($channel->fresh()->ical_active_rules);
$this->assertSame($newEvent['raw'], $block->fresh()->ical_raw);
$this->assertSame('unknown', $block->fresh()->ical_event_type);
}
public function test_main_form_validation_closes_confirmation_and_keeps_the_unsaved_fields(): void
{
$channel = $this->channel();
$this->actingAs(User::factory()->create());
$page = Livewire::test(ChannelRules::class, ['record' => $channel->id])
->fillForm(['rules' => [self::rule(['name' => ''])]])
->mountAction('applyRules')->callMountedAction()->assertActionNotMounted()
->assertHasErrors()->assertNotified('Regeln wurden nicht angewendet');
$this->assertCount(1, $page->get('data.rules'));
$this->assertNull($channel->fresh()->ical_rules);
$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'));
}
}