Files
fewo-stommer/tests/Feature/GenericChannelIntegrationTest.php
Lars 2ae48e77fa
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m3s
iCal-Ereignisse mit LAST-MODIFIED statt fehlendem DTSTAMP lesen
2026-10-29 15:53:55 +01:00

643 lines
34 KiB
PHP

<?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\PortalOccupations\Pages\ManagePortalOccupations;
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'));
$fallback = str_replace('DTSTAMP:20261101T090000Z', 'LAST-MODIFIED:20261101T090000Z', $valid);
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)],
'empty fallback stamp' => [str_replace('LAST-MODIFIED:20261101T090000Z', 'LAST-MODIFIED:', $fallback)],
'non UTC fallback stamp' => [str_replace('LAST-MODIFIED:20261101T090000Z', 'LAST-MODIFIED:20261101T090000', $fallback)],
'invalid fallback date' => [str_replace('LAST-MODIFIED:20261101T090000Z', 'LAST-MODIFIED:20260230T090000Z', $fallback)],
'invalid present stamp with valid fallback' => [str_replace('DTSTAMP:20261101T090000Z', "DTSTAMP:invalid\r\nLAST-MODIFIED:20261101T090000Z", $valid)],
'empty present stamp with valid fallback' => [str_replace('DTSTAMP:20261101T090000Z', "DTSTAMP:\r\nLAST-MODIFIED:20261101T090000Z", $valid)],
'duplicate fallback stamp' => [str_replace('LAST-MODIFIED:20261101T090000Z', "LAST-MODIFIED:20261101T090000Z\r\nLAST-MODIFIED:20261101T100000Z", $fallback)],
'duplicate primary stamp' => [str_replace('DTSTAMP:20261101T090000Z', "DTSTAMP:20261101T090000Z\r\nDTSTAMP:20261101T100000Z", $valid)],
'created is not a fallback' => [str_replace('DTSTAMP:20261101T090000Z', 'CREATED:20261101T090000Z', $valid)],
'calendar metadata is not an event fallback' => [str_replace("DTSTAMP:20261101T090000Z\r\n", '', str_replace('VERSION:2.0', "VERSION:2.0\r\nLAST-MODIFIED:20261101T090000Z", $valid))],
'fallback does not relax date validation' => [str_replace('20261107', '20261131', $fallback)],
'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)],
];
}
public function test_valid_last_modified_can_replace_missing_dtstamp_without_rewriting_originals_or_identity(): void
{
$property = $this->property();
$channel = $this->channel($property);
$body = self::feed(
"BEGIN:VEVENT\r\nUID:without-stamp\r\nSTATUS:1\r\nDTSTART:20261110T120000Z\r\nDTEND:20261124T115959Z\r\nLAST-MODIFIED:20261029T152031Z\r\nSUMMARY:Belegt\r\nEND:VEVENT\r\n".
"BEGIN:VEVENT\r\nUID:summer-time\r\nSTATUS:1\r\nDTSTART:20270328T130000Z\r\nDTEND:20270404T115959Z\r\nLAST-MODIFIED:20261029T152031Z\r\nSUMMARY:Belegt\r\nEND:VEVENT\r\n"
);
$document = app(ICalParser::class)->parseDocument($body);
$this->assertCount(2, $document['events']);
$this->assertArrayNotHasKey('DTSTAMP', $document['events'][0]['properties']);
$this->assertSame('20261029T152031Z', $document['events'][0]['properties']['LAST-MODIFIED'][0]['value']);
$this->assertStringNotContainsString('DTSTAMP:', $document['events'][0]['raw']);
Http::preventStrayRequests();
Http::fake(['https://portal.example/*' => Http::sequence()->push($body)->push($body)
->push(str_replace('20261124T115959Z', '20261125T115959Z', $body))]);
Mail::fake();
$first = app(SyncChannel::class)->handle($channel);
$ids = $channel->blockedPeriods()->orderBy('id')->pluck('id')->all();
$second = app(SyncChannel::class)->handle($channel);
$third = app(SyncChannel::class)->handle($channel);
$this->assertTrue($first->successful);
$this->assertTrue($second->successful);
$this->assertTrue($third->successful);
$this->assertSame([2, 0, 1], [$first->added, $second->added, $third->changed]);
$this->assertSame($ids, $channel->blockedPeriods()->orderBy('id')->pluck('id')->all());
$ordinary = $channel->blockedPeriods()->where('external_uid', 'without-stamp')->sole();
$summerTime = $channel->blockedPeriods()->where('external_uid', 'summer-time')->sole();
$this->assertSame(['2026-11-10', '2026-11-25'], [$ordinary->starts_on->toDateString(), $ordinary->ends_on->toDateString()]);
$this->assertSame(['2027-03-28', '2027-04-04'], [$summerTime->starts_on->toDateString(), $summerTime->ends_on->toDateString()]);
$this->assertSame('unknown', $ordinary->occupationKind()->value);
$this->assertArrayNotHasKey('DTSTAMP', $ordinary->ical_properties);
$this->assertSame('1', $ordinary->ical_properties['STATUS'][0]['value']);
Http::assertSentCount(3);
}
#[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(ManagePortalOccupations::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";
}
}