Generische iCal-Kanäle mit Bestandsklärung und sicheren Exporten bereitstellen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m33s

This commit is contained in:
Lars committed 2026-10-27 17:14:45 +01:00
1 parent 6fe5bbc6e3
commit 783068501c
42 files changed
+2646 -248

No files matched your search

@@ -0,0 +1,280 @@
<?php
namespace Tests\Feature;
use App\Actions\ResolveChannelOccupation;
use App\Actions\SyncChannel;
use App\Availability\AvailabilityChecker;
use App\Channels\ICal\ICalFeed;
use App\Enums\BookingStatus;
use App\Enums\ChannelEchoBehavior;
use App\Enums\UserRole;
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\User;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Filament\Actions\CreateAction;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Tests\TestCase;
class ChannelOccupationResolutionTest extends TestCase
{
use RefreshDatabase;
public function test_equal_dates_with_different_channel_uids_are_not_automatically_merged_or_rebroadcast(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/a.ics']]);
$b = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/b.ics']]);
Http::preventStrayRequests();
Http::fake(['https://portal.example/a.ics' => Http::response(self::feed('uid-a')), 'https://portal.example/b.ics' => Http::response(self::feed('uid-b'))]);
Mail::fake();
app(SyncChannel::class)->handle($a);
app(SyncChannel::class)->handle($b);
app(SyncChannel::class)->handle($b);
$this->assertSame(2, $property->blockedPeriods()->count());
$this->assertSame([false, false, true], [$b->blockedPeriods()->sole()->is_representation, $b->blockedPeriods()->sole()->export_approved, $b->blockedPeriods()->sole()->needs_review]);
$this->assertStringNotContainsString('block-'.$b->blockedPeriods()->sole()->id.'@', app(ICalFeed::class)->build($a));
Http::assertSentCount(3);
}
public function test_reexporting_channel_holds_new_events_internally_until_individually_confirmed(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create(['echo_behavior' => ChannelEchoBehavior::Reexports, 'settings' => ['import_url' => 'https://portal.example/a.ics']]);
$b = Channel::factory()->for($property)->create();
Http::preventStrayRequests();
Http::fake(['https://portal.example/a.ics' => Http::response(self::feed('external'))]);
Mail::fake();
app(SyncChannel::class)->handle($a);
$block = $a->blockedPeriods()->sole();
$this->assertFalse($block->export_approved);
$this->assertFalse($this->available($property));
$this->assertStringNotContainsString('block-'.$block->id.'@', app(ICalFeed::class)->build($b));
app(ResolveChannelOccupation::class)->handle($block, 'independent', originId: $a->id);
$this->assertStringContainsString('block-'.$block->id.'@', app(ICalFeed::class)->build($b));
$this->assertStringNotContainsString('block-'.$block->id.'@', app(ICalFeed::class)->build($a));
$this->assertFalse($block->fresh()->needs_review);
Http::assertSentCount(1);
}
public function test_linked_calendar_representation_never_keeps_a_cancelled_primary_block_occupied(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create();
$b = Channel::factory()->for($property)->create();
$primary = $this->block($property, $a, 'primary');
$copy = $this->block($property, $b, 'copy');
app(ResolveChannelOccupation::class)->handle($copy, 'block', $primary->id, $a->id);
$this->assertFalse($this->available($property));
$primary->delete();
$this->assertTrue($this->available($property));
$this->assertTrue($copy->fresh()->is_representation);
$this->assertSame($primary->id, $copy->fresh()->canonical_block_id);
$this->assertSoftDeleted($primary);
$this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($a));
}
public function test_representation_of_local_booking_follows_its_cancellation(): void
{
$property = $this->property();
$channel = Channel::factory()->for($property)->create();
$booking = Booking::factory()->for($property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2027-05-23', 'departure' => '2027-05-30']);
$copy = $this->block($property, $channel, 'copy');
app(ResolveChannelOccupation::class)->handle($copy, 'booking', $booking->id);
$booking->update(['status' => BookingStatus::Cancelled]);
$this->assertTrue($this->available($property));
$this->assertSame($booking->id, $copy->fresh()->linked_booking_id);
$this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($channel));
}
public function test_primary_uid_reappearing_restores_same_local_identity_and_keeps_alias_assignment(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/a.ics']]);
$b = Channel::factory()->for($property)->create();
$primary = $this->block($property, $a, 'primary');
$copy = $this->block($property, $b, 'copy');
app(ResolveChannelOccupation::class)->handle($copy, 'block', $primary->id);
$primary->delete();
Http::preventStrayRequests();
Http::fake(['https://portal.example/a.ics' => Http::response(self::feed('primary'))]);
Mail::fake();
$result = app(SyncChannel::class)->handle($a);
$this->assertTrue($result->successful);
$this->assertSame($primary->id, $a->blockedPeriods()->sole()->id);
$this->assertSame($primary->id, $copy->fresh()->canonical_block_id);
$this->assertFalse($this->available($property));
Http::assertSentCount(1);
}
public function test_linked_representation_changed_by_portal_is_flagged_without_reopening_its_old_period(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create();
$b = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/b.ics']]);
$primary = $this->block($property, $a, 'primary');
$copy = $this->block($property, $b, 'copy');
app(ResolveChannelOccupation::class)->handle($copy, 'block', $primary->id);
$primary->update(['starts_on' => '2027-06-01', 'ends_on' => '2027-06-08']);
Http::preventStrayRequests();
Http::fake(['https://portal.example/b.ics' => Http::response(self::feed('copy'))]);
Mail::fake();
app(SyncChannel::class)->handle($b);
$this->assertTrue($copy->fresh()->needs_review);
$this->assertTrue($this->available($property));
$this->assertStringNotContainsString('20270523', app(ICalFeed::class)->build($a));
Http::assertSentCount(1);
}
public function test_mapping_rejects_different_dates_or_a_different_property_without_changing_inventory(): void
{
$property = $this->property();
$channel = Channel::factory()->for($property)->create();
$block = $this->block($property, $channel, 'copy');
$other = BlockedPeriod::factory()->create(['starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']);
$wrongDates = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2027-05-23', 'ends_on' => '2027-05-31']);
foreach ([$other, $wrongDates, $block] as $invalidTarget) {
try {
app(ResolveChannelOccupation::class)->handle($block, 'block', $invalidTarget->id);
$this->fail('An unverified target must not be accepted.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('target_id', $exception->errors());
}
}
$this->assertFalse($block->fresh()->is_representation);
$this->assertSame(3, BlockedPeriod::count());
}
public function test_alias_chains_are_rejected_and_an_assignment_can_be_explicitly_reversed(): void
{
$property = $this->property();
$channel = Channel::factory()->for($property)->create();
$a = $this->block($property, $channel, 'a');
$b = $this->block($property, $channel, 'b');
$c = $this->block($property, $channel, 'c');
app(ResolveChannelOccupation::class)->handle($b, 'block', $a->id);
try {
app(ResolveChannelOccupation::class)->handle($a, 'block', $c->id);
$this->fail('A primary with linked representations cannot become a representation itself.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('target_id', $exception->errors());
}
app(ResolveChannelOccupation::class)->handle($b, 'independent');
$this->assertNull($b->fresh()->canonical_block_id);
$this->assertFalse($b->fresh()->is_representation);
$this->assertTrue($b->fresh()->export_approved);
}
public function test_same_uid_in_different_channels_is_independently_identified(): void
{
$property = $this->property();
$a = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/a.ics']]);
$b = Channel::factory()->for($property)->create(['settings' => ['import_url' => 'https://portal.example/b.ics']]);
Http::preventStrayRequests();
Http::fake(['https://portal.example/a.ics' => Http::response(self::feed('same')), 'https://portal.example/b.ics' => Http::response(self::feed('same', '20270601', '20270608'))]);
Mail::fake();
app(SyncChannel::class)->handle($a);
app(SyncChannel::class)->handle($b);
$this->assertNotSame($a->blockedPeriods()->sole()->id, $b->blockedPeriods()->sole()->id);
$this->assertSame('2027-05-23', $a->blockedPeriods()->sole()->starts_on->toDateString());
$this->assertSame('2027-06-01', $b->blockedPeriods()->sole()->starts_on->toDateString());
Http::assertSentCount(2);
}
public function test_landlord_can_resolve_a_duplicate_through_the_existing_admin(): void
{
$property = $this->property();
$channel = Channel::factory()->for($property)->create();
$primary = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']);
$copy = $this->block($property, $channel, 'copy');
$this->actingAs(User::factory()->create());
Livewire::test(ManageBlockedPeriods::class)->callTableAction('resolve', $copy, ['resolution' => 'block', 'target_id' => $primary->id])->assertHasNoActionErrors();
$this->assertSame($primary->id, $copy->fresh()->canonical_block_id);
$this->assertTrue($copy->fresh()->is_representation);
}
public function test_content_role_cannot_open_the_occupation_resolution_screen(): void
{
$this->property();
$this->actingAs(User::factory()->role(UserRole::Content)->create());
Livewire::test(ManageBlockedPeriods::class)->assertForbidden();
}
public function test_any_portal_created_in_the_ui_automatically_gets_its_own_stable_export_link(): void
{
$property = $this->property();
$this->actingAs(User::factory()->create());
$ui = Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $property, 'pageClass' => EditProperty::class]);
foreach (['Portal Alpha', 'Portal Beta', 'Ein beliebiger weiterer Anbieter'] as $name) {
$ui->callAction(TestAction::make(CreateAction::class)->table(), ['name' => $name, 'connector' => 'ical'])->assertHasNoFormErrors();
}
$channels = $property->channels()->get();
$links = $channels->map(fn (Channel $channel): string => $channel->exportUrl());
$this->assertSame(3, $links->unique()->count());
foreach ($channels as $channel) {
$this->assertSame(48, strlen($channel->export_token));
$link = $channel->exportUrl();
$channel->update(['name' => $channel->name.' umbenannt']);
$this->assertSame($link, $channel->fresh()->exportUrl());
$this->get($link)->assertStatus(503);
}
}
private function property(): Property
{
$this->travelTo(CarbonImmutable::parse('2026-10-27 12:00'));
$this->seed(PropertySeeder::class);
$property = Property::sole();
app(TenantContext::class)->set($property->tenant);
return $property;
}
private function block(Property $property, Channel $channel, string $uid): BlockedPeriod
{
return BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => $uid, 'starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']);
}
private function available(Property $property): bool
{
return app(AvailabilityChecker::class)->isAvailable($property, CarbonImmutable::parse('2027-05-23'), CarbonImmutable::parse('2027-05-30'));
}
private static function feed(string $uid, string $start = '20270523', string $end = '20270530'): string
{
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic//DE\r\nBEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261027T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
}
}
+10 -3
View File
@@ -61,6 +61,7 @@ public function test_parser_reads_dates_datetimes_folded_lines_and_skips_cancell
{
$ics = implode("\r\n", [
'BEGIN:VCALENDAR',
'VERSION:2.0', 'PRODID:-//Synthetic Test//EN',
'BEGIN:VEVENT', 'UID:a1', 'DTSTART;VALUE=DATE:20261107', 'DTEND;VALUE=DATE:20261110', 'SUMMARY:Reserviert \, Familie', 'END:VEVENT',
'BEGIN:VEVENT', 'UID:a2', 'DTSTART;TZID=Europe/Berlin:20261201T160000', 'DTEND;TZID=Europe/Berlin:20261205T100000', 'END:VEVENT',
'BEGIN:VEVENT', 'UID:a3-very-long-uid-that-is-', ' folded', 'DTSTART:20261231T230000Z', 'DTEND:20270102T090000Z', 'END:VEVENT',
@@ -69,6 +70,7 @@ public function test_parser_reads_dates_datetimes_folded_lines_and_skips_cancell
'END:VCALENDAR',
]);
$ics = str_replace("BEGIN:VEVENT\r\n", "BEGIN:VEVENT\r\nDTSTAMP:20261022T080000Z\r\n", $ics);
$periods = (new ICalParser)->parse($ics);
$this->assertSame(
@@ -99,7 +101,9 @@ public function test_sync_adds_changes_and_removes_imported_occupations(): void
$this->fakeFeed([['x1', '20261107', '20261111']]);
$second = (new SyncChannel)->handle($channel);
$this->assertSame([0, 1, 1], [$second->added, $second->changed, $second->removed]);
$this->assertSame([0, 1, 0], [$second->added, $second->changed, $second->removed]);
$third = (new SyncChannel)->handle($channel);
$this->assertSame([0, 0, 1], [$third->added, $third->changed, $third->removed]);
$this->assertSame('2026-11-11', $channel->blockedPeriods()->sole()->ends_on->toDateString());
$this->assertNotNull($channel->fresh()->last_success_at);
}
@@ -251,6 +255,9 @@ public function test_channels_are_managed_and_tasks_completed_in_the_admin(): vo
->callAction(TestAction::make(CreateAction::class)->table(), [
'name' => 'FeWo-direkt',
'connector' => 'ical',
'status' => 'active',
'import_enabled' => true,
'export_enabled' => true,
'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/abc.ics'],
'requires_manual_blocking' => true,
'manage_url' => 'https://www.fewo-direkt.de/vermieter/kalender',
@@ -282,8 +289,8 @@ private function channel(string $name, bool $manual = false): Channel
*/
private function fakeFeed(array $events): void
{
$body = "BEGIN:VCALENDAR\r\n".collect($events)
->map(fn (array $event): string => "BEGIN:VEVENT\r\nUID:{$event[0]}\r\nDTSTART;VALUE=DATE:{$event[1]}\r\nDTEND;VALUE=DATE:{$event[2]}\r\nEND:VEVENT\r\n")
$body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic Test//EN\r\n".collect($events)
->map(fn (array $event): string => "BEGIN:VEVENT\r\nDTSTAMP:20261022T080000Z\r\nUID:{$event[0]}\r\nDTSTART;VALUE=DATE:{$event[1]}\r\nDTEND;VALUE=DATE:{$event[2]}\r\nEND:VEVENT\r\n")
->implode('')."END:VCALENDAR\r\n";
$this->httpResponse = Http::response($body, 200, ['Content-Type' => 'text/calendar']);
@@ -0,0 +1,593 @@
<?php
namespace Tests\Feature;
use App\Actions\ConfigureChannel;
use App\Actions\CreateChannelTasks;
use App\Actions\ProcessPortalMail;
use App\Actions\RotateChannelToken;
use App\Actions\SyncChannel;
use App\Availability\AvailabilityChecker;
use App\Channels\ICal\ICalParser;
use App\Channels\Mail\PortalMail;
use App\Enums\BookingStatus;
use App\Enums\ChannelExportMode;
use App\Enums\ChannelStatus;
use App\Enums\ChannelTaskAction;
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Property;
use App\Models\User;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Filament\Actions\CreateAction;
use Filament\Actions\EditAction;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class GenericChannelIntegrationTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-11-01 10:00'));
}
public function test_new_channel_has_safe_defaults_and_does_not_expose_an_empty_paused_calendar(): void
{
$property = $this->property();
$channel = app(ConfigureChannel::class)->handle($property, ['name' => 'Beliebiges Portal', 'connector' => 'ical']);
$this->assertSame([ChannelStatus::Setup, false, false, ChannelExportMode::Test], [$channel->status, $channel->import_enabled, $channel->export_enabled, $channel->export_mode]);
$this->get($channel->exportUrl())->assertStatus(503)->assertHeader('Retry-After', '300')->assertDontSee('BEGIN:VCALENDAR');
}
/** @return array<string, array{bool, bool}> */
public static function directionProvider(): array
{
return ['import' => [true, false], 'export' => [false, true], 'both' => [true, true], 'neither' => [false, false]];
}
#[DataProvider('directionProvider')]
public function test_directions_are_independent(bool $import, bool $export): void
{
$property = $this->property();
$channel = $this->channel($property, ['import_enabled' => $import, 'export_enabled' => $export]);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed())]);
$result = app(SyncChannel::class)->handle($channel);
$this->assertSame($import, $result->successful);
$this->get($channel->exportUrl())->assertStatus($export ? 200 : 503);
if (! $import) {
Http::assertNothingSent();
} else {
Http::assertSentCount(1);
}
}
public function test_test_mode_exports_only_own_occupations_but_foreign_ones_still_block_internally(): void
{
$property = $this->property();
$a = $this->channel($property, ['export_mode' => 'test']);
$b = $this->channel($property);
$own = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-02', 'ends_on' => '2026-11-03']);
$foreign = BlockedPeriod::factory()->for($property)->create(['channel_id' => $b->id, 'source' => 'channel', 'external_uid' => 'b1', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
$mail = BlockedPeriod::factory()->for($property)->create(['channel_id' => $b->id, 'source' => 'email', 'starts_on' => '2026-11-12', 'ends_on' => '2026-11-13']);
$booking = Booking::factory()->for($property)->create(['status' => BookingStatus::Confirmed, 'source' => 'manual']);
$portalBooking = Booking::factory()->for($property)->create(['status' => BookingStatus::Confirmed, 'source' => 'website', 'origin_channel_id' => $b->id]);
$importedBooking = Booking::factory()->for($property)->create(['status' => BookingStatus::Confirmed, 'source' => 'website', 'import_channel_id' => $b->id]);
$feed = $this->get($a->exportUrl())->assertOk()->getContent();
$this->assertStringContainsString("UID:block-{$own->id}@fewo-stommer", $feed);
$this->assertStringContainsString("UID:booking-{$booking->id}@fewo-stommer", $feed);
foreach ([$foreign, $mail] as $block) {
$this->assertStringNotContainsString("UID:block-{$block->id}@fewo-stommer", $feed);
}
foreach ([$portalBooking, $importedBooking] as $block) {
$this->assertStringNotContainsString("UID:booking-{$block->id}@fewo-stommer", $feed);
}
$this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')));
$this->assertNotNull($a->fresh()->last_export_requested_at);
}
public function test_regular_mode_excludes_both_the_import_channel_and_known_original_channel(): void
{
$property = $this->property();
$a = $this->channel($property);
$b = $this->channel($property);
$origin = BlockedPeriod::factory()->for($property)->create(['channel_id' => $b->id, 'origin_channel_id' => $a->id, 'source' => 'channel']);
$other = BlockedPeriod::factory()->for($property)->create(['channel_id' => $b->id, 'source' => 'channel']);
$portalBooking = Booking::factory()->for($property)->create(['status' => BookingStatus::Confirmed, 'import_channel_id' => $b->id, 'origin_channel_id' => $a->id]);
$feed = $this->get($a->exportUrl())->assertOk()->getContent();
$this->assertStringNotContainsString("UID:block-{$origin->id}@fewo-stommer", $feed);
$this->assertStringNotContainsString("UID:booking-{$portalBooking->id}@fewo-stommer", $feed);
$this->assertStringContainsString("UID:block-{$other->id}@fewo-stommer", $feed);
}
public function test_paused_export_freezes_the_last_response_and_resume_refreshes_it(): void
{
$property = $this->property();
$channel = $this->channel($property);
$block = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
$before = $this->get($channel->exportUrl())->assertOk()->getContent();
app(ConfigureChannel::class)->handle($property, ['export_enabled' => false], $channel);
$block->update(['ends_on' => '2026-11-11']);
$this->get($channel->exportUrl())->assertOk()->assertHeader('X-Fewo-Export-State', 'frozen')->assertContent($before);
$this->assertTrue($channel->fresh()->importsOccupations());
app(ConfigureChannel::class)->handle($property, ['export_enabled' => true], $channel);
$this->get($channel->exportUrl())->assertOk()->assertHeader('X-Fewo-Export-State', 'live')->assertSee('20261111');
}
public function test_pause_before_first_request_captures_the_existing_export_and_pauses_import(): void
{
$property = $this->property();
$channel = $this->channel($property);
BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
Http::preventStrayRequests();
app(ConfigureChannel::class)->handle($property, ['status' => 'paused'], $channel);
$this->get($channel->exportUrl())->assertOk()->assertHeader('X-Fewo-Export-State', 'frozen')->assertSee('20261107');
$this->assertFalse(app(SyncChannel::class)->handle($channel)->successful);
$this->assertSame(1, $property->blockedPeriods()->count());
Http::assertNothingSent();
}
public function test_repeated_import_and_identical_duplicate_uids_are_idempotent_and_echoes_are_ignored(): void
{
$property = $this->property();
$channel = $this->channel($property);
$event = self::event('external-1');
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed($event.$event.self::event('block-123@fewo-stommer')))]);
Mail::fake();
$first = app(SyncChannel::class)->handle($channel);
$id = $channel->blockedPeriods()->sole()->id;
$second = app(SyncChannel::class)->handle($channel);
$this->assertSame([1, 1, 0], [$first->events, $first->added, $second->added]);
$this->assertSame($id, $channel->blockedPeriods()->sole()->id);
}
/** @return array<string, array{string}> */
public static function invalidFeedProvider(): array
{
$valid = self::feed(self::event('external-1'));
return [
'not calendar' => ['<html>Login</html>'],
'only marker' => ["BEGIN:VCALENDAR\r\n"],
'truncated' => [str_replace('END:VCALENDAR', 'BEGIN:VEVENT', $valid)],
'bad event' => [str_replace('END:VEVENT', '', $valid)],
'invalid date' => [str_replace('20261107', '20261131', $valid)],
'missing UID' => [str_replace("UID:external-1\r\n", '', $valid)],
'missing stamp' => [str_replace("DTSTAMP:20261101T090000Z\r\n", '', $valid)],
'recurrence' => [str_replace('UID:external-1', "UID:external-1\r\nRRULE:FREQ=DAILY;COUNT=3", $valid)],
'different dates for same UID' => [self::feed(self::event('same').self::event('same', '20261114', '20261117'))],
'different value types' => [str_replace('DTEND;VALUE=DATE:20261110', 'DTEND:20261110T100000Z', $valid)],
'delta message' => [str_replace('VERSION:2.0', "VERSION:2.0\r\nMETHOD:CANCEL", $valid)],
];
}
#[DataProvider('invalidFeedProvider')]
public function test_invalid_snapshot_never_changes_existing_blocks(string $body): void
{
$property = $this->property();
$channel = $this->channel($property);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'existing', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response($body)]);
$result = app(SyncChannel::class)->handle($channel);
$this->assertFalse($result->successful);
$this->assertSame([$block->id, '2026-11-10', 0], [$channel->blockedPeriods()->sole()->id, $block->fresh()->ends_on->toDateString(), $block->fresh()->missing_imports]);
$this->assertNotNull($channel->fresh()->last_error_at);
$this->assertNull($channel->fresh()->last_success_at);
Http::assertSentCount(1);
}
public function test_missing_events_require_two_successful_snapshots_and_reappearance_resets_confirmation(): void
{
$property = $this->property();
$channel = $this->channel($property);
Mail::fake();
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::sequence()
->push(self::feed(self::event('one')))->push(self::feed())
->push(self::feed(self::event('one')))->push(self::feed())->push(self::feed())]);
app(SyncChannel::class)->handle($channel);
$first = app(SyncChannel::class)->handle($channel);
$this->assertSame(0, $first->removed);
$this->assertSame(1, $channel->blockedPeriods()->sole()->missing_imports);
$channel->update(['import_enabled' => false]);
$this->assertFalse(app(SyncChannel::class)->handle($channel)->successful);
$this->assertSame(1, $channel->blockedPeriods()->count());
$channel->update(['import_enabled' => true]);
app(SyncChannel::class)->handle($channel);
$this->assertSame(0, $channel->blockedPeriods()->sole()->missing_imports);
app(SyncChannel::class)->handle($channel);
$this->assertSame(1, app(SyncChannel::class)->handle($channel)->removed);
$this->assertSame(0, $channel->blockedPeriods()->count());
}
public function test_large_disappearance_is_held_for_review_instead_of_mass_removal(): void
{
$property = $this->property();
$channel = $this->channel($property);
BlockedPeriod::factory()->count(6)->for($property)->sequence(fn ($sequence) => ['channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'id-'.$sequence->index, 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10'])->create();
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed())]);
app(SyncChannel::class)->handle($channel);
$result = app(SyncChannel::class)->handle($channel);
$this->assertSame(0, $result->removed);
$this->assertSame(6, $channel->blockedPeriods()->where('needs_review', true)->count());
$this->assertNotEmpty($channel->fresh()->sync_warnings);
}
public function test_changed_dates_keep_identity_and_preserve_old_dates_for_after_commit_tasks(): void
{
$property = $this->property();
$channel = $this->channel($property);
$target = $this->channel($property, ['requires_manual_blocking' => true]);
Mail::fake();
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::sequence()->push(self::feed(self::event('one')))->push(self::feed(self::event('one', '20261114', '20261117')))]);
app(SyncChannel::class)->handle($channel);
$id = $channel->blockedPeriods()->sole()->id;
$cutoff = ChannelTask::max('id');
$result = app(SyncChannel::class)->handle($channel);
$this->assertSame([1, $id], [$result->changed, $channel->blockedPeriods()->sole()->id]);
$this->assertSame([['unblock', '2026-11-07', '2026-11-10'], ['block', '2026-11-14', '2026-11-17']], $target->tasks()->where('id', '>', $cutoff)->orderBy('id')->get()->map(fn ($task) => [$task->action->value, $task->starts_on->toDateString(), $task->ends_on->toDateString()])->all());
}
public function test_unblock_tasks_release_only_currently_free_nights(): void
{
$property = $this->property();
$target = $this->channel($property, ['requires_manual_blocking' => true]);
Mail::fake();
$outer = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-11']);
BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-08', 'ends_on' => '2026-11-10']);
$cutoff = ChannelTask::max('id');
$outer->delete();
$this->assertSame([['2026-11-07', '2026-11-08'], ['2026-11-10', '2026-11-11']], $target->tasks()->where('id', '>', $cutoff)->where('action', ChannelTaskAction::Unblock)->orderBy('id')->get()->map(fn ($task) => [$task->starts_on->toDateString(), $task->ends_on->toDateString()])->all());
}
public function test_mail_and_calendar_merge_only_with_a_shared_identifier(): void
{
$property = $this->property();
$channel = $this->channel($property, ['settings' => ['email_senders' => 'portal.example', 'import_url' => 'https://portal.example/feed.ics']]);
Mail::fake();
$mail = app(ProcessPortalMail::class)->handle(new PortalMail('message-1', 'mail@portal.example', 'Neue Buchung', "Anreise: 07.11.2026\nAbreise: 10.11.2026\nBuchungsnummer: HA-TEST01", now()->toImmutable()));
$id = $mail->blocked_period_id;
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed(self::event('HA-TEST01', '20261114', '20261117')))]);
app(SyncChannel::class)->handle($channel);
$this->assertSame([$id, 'channel', '2026-11-14'], [$channel->blockedPeriods()->sole()->id, $channel->blockedPeriods()->sole()->source, $channel->blockedPeriods()->sole()->starts_on->toDateString()]);
}
public function test_unidentified_nonoverlapping_mail_and_calendar_events_are_retained_separately(): void
{
$property = $this->property();
$channel = $this->channel($property);
BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'email', 'external_uid' => 'email:HA-TEST01', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed(self::event('different', '20261114', '20261117')))]);
Mail::fake();
app(SyncChannel::class)->handle($channel);
$this->assertSame(2, $channel->blockedPeriods()->where('needs_review', true)->count());
}
public function test_test_mode_does_not_dispatch_foreign_occupations_to_manual_portals(): void
{
$property = $this->property();
$a = $this->channel($property);
$b = $this->channel($property, ['export_mode' => 'test', 'requires_manual_blocking' => true]);
Mail::fake();
BlockedPeriod::factory()->for($property)->create(['channel_id' => $a->id, 'source' => 'channel']);
$this->assertSame(0, $b->tasks()->count());
Mail::assertNothingSent();
}
public function test_token_rotation_keeps_old_link_during_explicit_transition_and_hides_tokens_from_serialisation(): void
{
$property = $this->property();
$channel = $this->channel($property);
$oldUrl = $channel->exportUrl();
$rotated = app(RotateChannelToken::class)->handle($channel, 24);
$this->assertNotSame($oldUrl, $rotated->exportUrl());
$this->get($oldUrl)->assertOk();
$this->get($rotated->exportUrl())->assertOk();
$this->assertArrayNotHasKey('export_token', $rotated->toArray());
$this->assertArrayNotHasKey('previous_export_token', $rotated->toArray());
$this->travel(25)->hours();
$this->get($oldUrl)->assertNotFound();
$this->get($rotated->exportUrl())->assertOk();
}
public function test_second_rotation_cannot_silently_revoke_a_running_transition(): void
{
$property = $this->property();
$channel = $this->channel($property);
app(RotateChannelToken::class)->handle($channel);
$this->expectException(ValidationException::class);
app(RotateChannelToken::class)->handle($channel);
}
public function test_foreign_channel_provenance_cannot_be_assigned_to_another_property(): void
{
$property = $this->property();
$channel = $this->channel($property);
$other = Property::factory()->create();
$this->expectException(ValidationException::class);
BlockedPeriod::factory()->for($other)->create(['channel_id' => $channel->id]);
}
public function test_two_properties_and_their_channels_do_not_share_imports_or_exports(): void
{
$property = $this->property();
$other = Property::factory()->create();
$a = $this->channel($property);
$b = $this->channel($other);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response(self::feed(self::event('a1')))]);
Mail::fake();
app(SyncChannel::class)->handle($a);
$this->assertSame(0, $b->blockedPeriods()->count());
$this->assertTrue(app(AvailabilityChecker::class)->isAvailable($other, CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')));
$this->get($b->exportUrl())->assertOk()->assertDontSee('20261107');
}
public function test_admin_can_configure_directions_and_edit_confidential_import_address(): void
{
$property = $this->property();
$this->actingAs(User::factory()->create());
$component = Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $property, 'pageClass' => EditProperty::class]);
$component->callAction(TestAction::make(CreateAction::class)->table(), ['name' => 'Portal A', 'connector' => 'ical', 'status' => 'active', 'booking_model' => 'inquiry', 'import_enabled' => true, 'export_enabled' => false, 'export_mode' => 'test', 'settings' => ['import_url' => 'https://portal.example/secret.ics'], 'external_poll_minutes' => 1440])->assertHasNoFormErrors();
$channel = $property->channels()->sole();
$component->callAction(TestAction::make(EditAction::class)->table($channel), ['export_enabled' => true, 'external_poll_minutes' => 30])->assertHasNoFormErrors();
$this->assertSame([true, true, 30, 'https://portal.example/secret.ics'], [$channel->fresh()->import_enabled, $channel->fresh()->export_enabled, $channel->fresh()->external_poll_minutes, $channel->fresh()->setting('import_url')]);
}
public function test_failed_fetch_preserves_occupations_and_does_not_disclose_import_url(): void
{
$property = $this->property();
$channel = $this->channel($property, ['settings' => ['import_url' => 'https://portal.example/private-token.ics']]);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'one']);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::response('error', 403)]);
$result = app(SyncChannel::class)->handle($channel);
$this->assertFalse($result->successful);
$this->assertModelExists($block);
$this->assertStringNotContainsString('private-token', $channel->fresh()->last_error);
$this->assertSame(0, $block->fresh()->missing_imports);
}
public function test_source_address_cannot_silently_replace_an_existing_import_inventory(): void
{
$property = $this->property();
$channel = $this->channel($property);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'channel']);
try {
app(ConfigureChannel::class)->handle($property, ['settings' => ['import_url' => 'https://other.example/new.ics']], $channel);
$this->fail('Changing the inventory source must require a separate migration decision.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('settings.import_url', $exception->errors());
}
$this->assertModelExists($block);
$this->assertStringStartsWith('https://portal.example/', $channel->fresh()->setting('import_url'));
}
public function test_a_channel_lock_prevents_a_second_fetch(): void
{
$property = $this->property();
$channel = $this->channel($property);
Http::preventStrayRequests();
Http::fake();
$lock = Cache::lock("channel-sync:{$channel->tenant_id}:{$channel->id}", 120);
$this->assertTrue($lock->get());
try {
$result = app(SyncChannel::class)->handle($channel);
$this->assertFalse($result->successful);
Http::assertNothingSent();
} finally {
$lock->release();
}
}
public function test_ambiguous_mail_sender_never_selects_the_first_property(): void
{
$property = $this->property();
$other = Property::factory()->create();
$a = $this->channel($property, ['settings' => ['email_senders' => 'portal.example']]);
$b = $this->channel($other, ['settings' => ['email_senders' => 'portal.example']]);
Mail::fake();
$result = app(ProcessPortalMail::class)->handle(new PortalMail('ambiguous', 'mail@portal.example', 'Neue Buchung', 'Anreise: 07.11.2026 Abreise: 10.11.2026', now()->toImmutable()));
$this->assertNull($result);
$this->assertSame(0, BlockedPeriod::count());
$this->assertNotEmpty($a->fresh()->sync_warnings);
$this->assertNotEmpty($b->fresh()->sync_warnings);
Mail::assertNothingSent();
}
public function test_rolled_back_occupations_do_not_create_portal_tasks(): void
{
$property = $this->property();
$channel = $this->channel($property, ['requires_manual_blocking' => true]);
Mail::fake();
DB::beginTransaction();
BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
DB::rollBack();
$this->assertSame(0, $channel->tasks()->count());
Mail::assertNothingSent();
}
public function test_outdated_unblock_task_is_not_sent_to_external_automation(): void
{
$property = $this->property();
$channel = $this->channel($property);
$task = $channel->tasks()->create(['action' => 'unblock', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10', 'reason' => 'Synthetic release']);
BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-08', 'ends_on' => '2026-11-09']);
config(['fewo.automation.webhook_url' => 'https://bot.example/tasks', 'fewo.automation.secret' => 'synthetic-secret']);
Http::preventStrayRequests();
Http::fake();
app(CreateChannelTasks::class)->sendToAutomation($task);
$this->assertSame('dismissed', $task->fresh()->status->value);
Http::assertNothingSent();
}
public function test_export_folds_long_utf8_lines_and_round_trips_without_date_changes(): void
{
$property = $this->property();
$property->update(['name' => str_repeat('Kühlungsborn ', 12)]);
$channel = $this->channel($property);
BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
$body = $this->get($channel->exportUrl())->assertOk()->getContent();
foreach (explode("\r\n", $body) as $line) {
$this->assertLessThanOrEqual(75, strlen($line));
}
$period = app(ICalParser::class)->parse($body)[0];
$this->assertSame(['2026-11-07', '2026-11-10'], [$period->startsOn->toDateString(), $period->endsOn->toDateString()]);
}
public function test_outdated_block_task_is_not_sent_after_cancellation(): void
{
$property = $this->property();
$channel = $this->channel($property);
$task = $channel->tasks()->create(['action' => 'block', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10', 'reason' => 'Old synthetic occupation']);
config(['fewo.automation.webhook_url' => 'https://bot.example/tasks', 'fewo.automation.secret' => 'synthetic-secret']);
Http::preventStrayRequests();
Http::fake();
app(CreateChannelTasks::class)->sendToAutomation($task);
$this->assertSame('dismissed', $task->fresh()->status->value);
Http::assertNothingSent();
}
public function test_cancellation_without_shared_reference_retains_mail_block_for_review(): void
{
$property = $this->property();
$channel = $this->channel($property, ['settings' => ['email_senders' => 'portal.example']]);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'email', 'external_uid' => 'email:known', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
Mail::fake();
$record = app(ProcessPortalMail::class)->handle(new PortalMail('cancel-unknown', 'mail@portal.example', 'Buchung storniert', 'Die Buchung vom 07.11.2026 bis 10.11.2026 wurde storniert.', now()->toImmutable()));
$this->assertSame('needs_review', $record->status->value);
$this->assertModelExists($block);
}
public function test_upgrade_preserves_existing_directions_scope_token_and_inventory(): void
{
$property = $this->property();
$channel = $this->channel($property);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'old']);
$token = $channel->export_token;
$migration = require database_path('migrations/2026_10_27_154125_add_generic_ical_controls_and_provenance.php');
$migration->down();
$migration->up();
$this->assertSame([true, true, ChannelExportMode::Regular, $token], [$channel->fresh()->import_enabled, $channel->fresh()->export_enabled, $channel->fresh()->export_mode, $channel->fresh()->export_token]);
$this->assertModelExists($block);
$this->assertSame('old', $block->fresh()->external_uid);
}
public function test_admin_can_view_import_provenance_and_unresolved_block_review(): void
{
$property = $this->property();
$channel = $this->channel($property, ['name' => 'Synthetisches Portal']);
$block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'origin_channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'synthetic-uid', 'needs_review' => true, 'review_note' => 'Bestand persönlich prüfen', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']);
$this->actingAs(User::factory()->create());
Livewire::test(ManageBlockedPeriods::class)
->assertCanSeeTableRecords([$block])
->assertSee('Synthetisches Portal')
->assertSee('Bitte prüfen')
->assertSee('Bestand persönlich prüfen');
}
private function property(): Property
{
$this->seed(PropertySeeder::class);
$property = Property::sole();
app(TenantContext::class)->set($property->tenant);
return $property;
}
/** @param array<string, mixed> $attributes */
private function channel(Property $property, array $attributes = []): Channel
{
return Channel::factory()->for($property)->create($attributes);
}
private static function event(string $uid, string $start = '20261107', string $end = '20261110'): string
{
return "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261101T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:Belegt\r\nEND:VEVENT\r\n";
}
private static function feed(string $events = ''): string
{
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic Test//EN\r\n{$events}END:VCALENDAR\r\n";
}
}
+8 -6
View File
@@ -113,7 +113,7 @@ public function test_overlap_with_an_existing_booking_raises_a_conflict(): void
Mail::assertSent(ChannelConflict::class);
}
public function test_calendar_sync_confirms_the_mail_block_without_creating_new_tasks(): void
public function test_calendar_without_shared_identity_keeps_the_mail_block_for_review(): void
{
Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true]);
$this->process('Neue Buchung', self::BOOKING_MAIL);
@@ -122,19 +122,21 @@ public function test_calendar_sync_confirms_the_mail_block_without_creating_new_
$this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261110");
(new SyncChannel)->handle($this->fewo);
$block = $this->fewo->blockedPeriods()->sole();
$this->assertSame(['channel', 'vrbo-123'], [$block->source, $block->external_uid]);
$this->assertSame(2, $this->fewo->blockedPeriods()->count());
$this->assertSame(2, $this->fewo->blockedPeriods()->where('needs_review', true)->count());
$this->assertSame($tasksBefore, ChannelTask::count());
}
public function test_calendar_entry_with_other_dates_replaces_the_mail_block(): void
public function test_calendar_entry_with_overlapping_dates_does_not_replace_an_unidentified_mail_block(): void
{
$this->process('Neue Buchung', self::BOOKING_MAIL);
$this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261111");
(new SyncChannel)->handle($this->fewo);
$this->assertSame(['channel', '2026-11-11'], [$this->fewo->blockedPeriods()->sole()->source, $this->fewo->blockedPeriods()->sole()->ends_on->toDateString()]);
$this->assertSame(2, $this->fewo->blockedPeriods()->count());
$this->assertSame(1, $this->fewo->blockedPeriods()->where('source', 'email')->count());
$this->assertSame('2026-11-11', $this->fewo->blockedPeriods()->where('source', 'channel')->sole()->ends_on->toDateString());
}
public function test_mail_blocks_survive_a_calendar_sync_that_does_not_know_them_yet(): void
@@ -206,7 +208,7 @@ private function process(string $subject, string $text, string $messageId = 'msg
private function fakeFeed(string $event): void
{
$body = "BEGIN:VCALENDAR\r\n".($event !== '' ? "BEGIN:VEVENT\r\n{$event}\r\nEND:VEVENT\r\n" : '').'END:VCALENDAR';
$body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic Test//EN\r\n".($event !== '' ? "BEGIN:VEVENT\r\nDTSTAMP:20261022T080000Z\r\n{$event}\r\nEND:VEVENT\r\n" : '').'END:VCALENDAR';
Http::fake(['*' => Http::response($body)]);
}
}