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)); $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); } 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 = ''; Http::preventStrayRequests(); Http::fake(['https://portal.example/calendar.ics' => Http::sequence()->push(self::feed(self::event('html', $payload)))->push('Login')]); $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')); } }