Files
fewo-stommer/tests/Feature/AutomaticChannelRepresentationTest.php
T
Lars add2367869
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s
Eindeutige iCal-Kalenderspiegelungen automatisch und widerrufbar zuordnen
2026-10-29 17:01:30 +01:00

323 lines
17 KiB
PHP

<?php
namespace Tests\Feature;
use App\Actions\ApplyChannelRules;
use App\Actions\ReconcileChannelRepresentations;
use App\Actions\ResolveChannelOccupation;
use App\Actions\SyncChannel;
use App\Availability\AvailabilityChecker;
use App\Availability\OccupancyOverview;
use App\Channels\ICal\ICalAnalysis;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Filament\Pages\OccupancyCalendar;
use App\Mail\ChannelConflict;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class AutomaticChannelRepresentationTest extends TestCase
{
use RefreshDatabase;
#[DataProvider('importOrders')]
public function test_recognized_mirror_is_linked_once_regardless_of_import_order(bool $primaryFirst): void
{
[$property, $source, $mirror] = $this->channels();
Http::preventStrayRequests();
Http::fake([
'https://portal.example/source.ics' => Http::response(self::feed('primary', 'Reservation: Nora Beispiel')),
'https://portal.example/mirror.ics' => Http::response(self::feed('mirror', 'Blocked')),
]);
Mail::fake();
foreach ($primaryFirst ? [$source, $mirror] : [$mirror, $source] as $channel) {
$this->assertTrue(app(SyncChannel::class)->handle($channel)->successful);
}
$primary = $source->blockedPeriods()->sole();
$copy = $mirror->blockedPeriods()->sole();
$this->assertTrue($copy->is_representation);
$this->assertTrue($copy->representation_automatic);
$this->assertSame($primary->id, $copy->canonical_block_id);
$this->assertNull($copy->reviewed_at);
$this->assertNull($copy->origin_channel_id);
$this->assertFalse($copy->needs_review);
$this->assertFalse($primary->needs_review);
$this->assertTrue($primary->export_approved);
$this->assertSame('mirror', $copy->external_uid);
$this->assertStringContainsString('SUMMARY:Blocked', $copy->ical_raw);
$this->assertSame(0, Guest::count());
$this->assertSame(0, BlockedPeriod::query()->unclear()->count());
$this->assertSame(2, $property->blockedPeriods()->count());
$this->actingAs(User::factory()->create());
$record = app(OccupancyOverview::class)->records($property->id, includeBlocks: true)->sole();
$this->assertSame(['Zweiter Kalender'], $record['mirrored_channels']);
$this->assertSame('Nora Beispiel', $record['guest']);
Livewire::test(OccupancyCalendar::class, ['propertyId' => $property->id, 'month' => '2027-05'])
->assertSee('Auch bei Zweiter Kalender gespiegelt')->assertDontSee('occupancy-event kind-unknown', escape: false);
$target = Channel::factory()->for($property)->create();
$this->assertStringContainsString('block-'.$primary->id.'@', app(ICalFeed::class)->build($mirror));
$this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($source));
$export = app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($target));
$this->assertCount(1, $export['events']);
$this->assertSame('block-'.$primary->id.'@fewo-stommer', $export['events'][0]['uid']);
$modified = $copy->updated_at;
$this->travel(5)->minutes();
app(SyncChannel::class)->handle($mirror);
$this->assertTrue($copy->fresh()->updated_at->equalTo($modified));
Mail::assertNotSent(ChannelConflict::class);
Http::assertSentCount(3);
}
public static function importOrders(): array
{
return ['primary first' => [true], 'mirror first' => [false]];
}
#[DataProvider('ambiguousCases')]
public function test_missing_evidence_contradictions_and_personal_decisions_prevent_automatic_linking(string $case): void
{
[$property, $source, $mirror] = $this->channels();
[$primary, $copy] = $this->occupations($source, $mirror);
match ($case) {
'unmatched' => $copy->forceFill(['ical_interpretation' => []])->saveQuietly(),
'source booking' => $copy->forceFill(['ical_event_type' => 'portal_reservation'])->saveQuietly(),
'reference' => $copy->forceFill(['ical_interpretation' => [...$copy->ical_interpretation, 'fields' => ['booking_reference' => 'EXTERNAL-123']]])->saveQuietly(),
'name' => $copy->forceFill(['ical_interpretation' => [...$copy->ical_interpretation, 'fields' => ['guest_full_name' => 'Anderer Gast']]])->saveQuietly(),
'origin' => $copy->forceFill(['origin_channel_id' => $mirror->id])->saveQuietly(),
'same channel' => $copy->forceFill(['channel_id' => $source->id])->saveQuietly(),
'different dates' => $copy->forceFill(['ends_on' => '2027-05-31'])->saveQuietly(),
'personal decision' => $copy->forceFill(['reviewed_at' => now()])->saveQuietly(),
'manual block' => $copy->forceFill(['occupation_kind' => 'block'])->saveQuietly(),
'private' => $copy->forceFill(['is_private' => true])->saveQuietly(),
'missing event' => $primary->forceFill(['missing_imports' => 1])->saveQuietly(),
'multiple primaries' => $primary->replicate()->forceFill(['external_uid' => 'second-primary'])->saveQuietly(),
'local booking' => Booking::factory()->for($property)->create(['arrival' => '2027-05-23', 'departure' => '2027-05-30', 'status' => 'confirmed']),
'unknown overlap' => BlockedPeriod::factory()->for($property)->create(['source' => 'channel', 'starts_on' => '2027-05-25', 'ends_on' => '2027-05-28']),
'custom review' => $copy->forceFill(['needs_review' => true, 'review_note' => 'Stornierung persönlich prüfen'])->saveQuietly(),
};
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertNull($copy->fresh()->canonical_block_id);
$this->assertFalse($primary->fresh()->is_representation);
}
public static function ambiguousCases(): array
{
$cases = ['unmatched', 'source booking', 'reference', 'name', 'origin', 'same channel', 'different dates', 'personal decision', 'manual block', 'private', 'missing event', 'multiple primaries', 'local booking', 'unknown overlap', 'custom review'];
return array_combine($cases, array_map(fn (string $case): array => [$case], $cases));
}
public function test_applying_rules_reconciles_existing_imports_without_fetching_or_recreating_them(): void
{
[$property, $source, $mirror] = $this->channels();
[$primary, $copy] = $this->occupations($source, $mirror);
$primary->forceFill(['ical_event_type' => 'unknown', 'leading_priority' => 0, 'ical_interpretation' => []])->saveQuietly();
$source->forceFill(['ical_rules' => [self::primaryRule()], 'ical_active_rules' => []])->save();
Http::preventStrayRequests();
app(ApplyChannelRules::class)->handle($source);
$this->assertTrue($copy->fresh()->is_representation);
$this->assertSame($primary->id, $copy->fresh()->canonical_block_id);
$this->assertSame(2, $property->blockedPeriods()->count());
Http::assertNothingSent();
}
public function test_changed_dates_detach_the_mirror_until_both_sources_agree_again(): void
{
[$property, $source, $mirror] = $this->channels();
Http::preventStrayRequests();
Http::fake([
'https://portal.example/source.ics' => Http::sequence()->push(self::feed('primary', 'Reservation: Nora Beispiel'))->push(self::feed('primary', 'Reservation: Nora Beispiel', '20270601', '20270608')),
'https://portal.example/mirror.ics' => Http::sequence()->push(self::feed('mirror', 'Blocked'))->push(self::feed('mirror', 'Blocked', '20270601', '20270608')),
]);
Mail::fake();
app(SyncChannel::class)->handle($source);
app(SyncChannel::class)->handle($mirror);
$primary = $source->blockedPeriods()->sole();
$copy = $mirror->blockedPeriods()->sole();
$this->assertTrue($copy->is_representation);
app(SyncChannel::class)->handle($source);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertTrue($copy->fresh()->needs_review);
$this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, CarbonImmutable::parse('2027-05-23'), CarbonImmutable::parse('2027-05-30')));
app(SyncChannel::class)->handle($mirror);
$this->assertTrue($copy->fresh()->is_representation);
$this->assertSame($primary->id, $copy->fresh()->canonical_block_id);
$this->assertFalse($copy->fresh()->needs_review);
$this->assertSame('2027-06-01', $copy->fresh()->starts_on->toDateString());
Http::assertSentCount(4);
}
public function test_missing_primary_reopens_a_still_reported_mirror_and_restoration_relinks_it(): void
{
[$property, $source, $mirror] = $this->channels();
Http::preventStrayRequests();
Http::fake([
'https://portal.example/source.ics' => Http::sequence()->push(self::feed('primary', 'Reservation: Nora Beispiel'))->push(self::feed())->push(self::feed())->push(self::feed('primary', 'Reservation: Nora Beispiel')),
'https://portal.example/mirror.ics' => Http::response(self::feed('mirror', 'Blocked')),
]);
Mail::fake();
app(SyncChannel::class)->handle($source);
app(SyncChannel::class)->handle($mirror);
$primary = $source->blockedPeriods()->sole();
$copy = $mirror->blockedPeriods()->sole();
app(SyncChannel::class)->handle($source);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertTrue($copy->fresh()->needs_review);
app(SyncChannel::class)->handle($source);
$this->assertSoftDeleted($primary);
$this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, $copy->starts_on, $copy->ends_on));
$this->assertFalse($copy->fresh()->export_approved);
$this->assertStringNotContainsString('BEGIN:VEVENT', app(ICalFeed::class)->build($source));
app(SyncChannel::class)->handle($source);
$this->assertSame($primary->id, $source->blockedPeriods()->sole()->id);
$this->assertTrue($copy->fresh()->is_representation);
Http::assertSentCount(5);
}
public function test_new_booking_evidence_in_a_mirror_breaks_the_automatic_link(): void
{
[$property, $source, $mirror] = $this->channels();
$mirror->forceFill(['ical_active_rules' => [self::primaryRule(), self::mirrorRule()]])->save();
Http::preventStrayRequests();
Http::fake([
'https://portal.example/source.ics' => Http::response(self::feed('primary', 'Reservation: Nora Beispiel')),
'https://portal.example/mirror.ics' => Http::sequence()->push(self::feed('mirror', 'Blocked'))->push(self::feed('mirror', 'Reservation: Anderer Gast')),
]);
Mail::fake();
app(SyncChannel::class)->handle($source);
app(SyncChannel::class)->handle($mirror);
$copy = $mirror->blockedPeriods()->sole();
$this->assertTrue($copy->is_representation);
app(SyncChannel::class)->handle($mirror);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertTrue($copy->fresh()->needs_review);
$this->assertSame('reservation', $copy->fresh()->occupationKind()->value);
$this->assertSame('Anderer Gast', $copy->fresh()->guestName());
Http::assertSentCount(3);
}
public function test_personal_independent_confirmation_prevents_relinking_and_manual_aliases_are_preserved(): void
{
[$property, $source, $mirror] = $this->channels();
[$primary, $copy] = $this->occupations($source, $mirror);
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertTrue($copy->fresh()->representation_automatic);
app(ResolveChannelOccupation::class)->handle($copy, 'independent');
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertFalse($copy->fresh()->representation_automatic);
app(ResolveChannelOccupation::class)->handle($copy, 'block', $primary->id);
$primary->delete();
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertTrue($copy->fresh()->is_representation);
$this->assertFalse($copy->fresh()->representation_automatic);
}
public function test_a_second_primary_breaks_an_existing_link_instead_of_using_priority_to_guess(): void
{
[$property, $source, $mirror] = $this->channels();
[$primary, $copy] = $this->occupations($source, $mirror);
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertTrue($copy->fresh()->is_representation);
$primary->replicate()->forceFill(['external_uid' => 'second-primary', 'leading_priority' => 1])->saveQuietly();
app(ReconcileChannelRepresentations::class)->handle($property);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertTrue($copy->fresh()->needs_review);
$this->assertNull($copy->fresh()->canonical_block_id);
}
public function test_reconciliation_does_not_cross_the_current_tenant_boundary(): void
{
[$property, $source, $mirror] = $this->channels();
[$primary, $copy] = $this->occupations($source, $mirror);
$other = Property::factory()->for(Tenant::factory())->create();
app(TenantContext::class)->set($other->tenant);
try {
app(ReconcileChannelRepresentations::class)->handle($property);
$this->fail('A foreign property must not be reconciled.');
} catch (ModelNotFoundException) {
app(TenantContext::class)->set($property->tenant);
$this->assertFalse($copy->fresh()->is_representation);
$this->assertFalse($primary->fresh()->is_representation);
}
}
private function channels(): array
{
$this->travelTo(CarbonImmutable::parse('2026-10-29 12:00'));
$this->seed(PropertySeeder::class);
$property = Property::sole();
app(TenantContext::class)->set($property->tenant);
$source = Channel::factory()->for($property)->create(['name' => 'Buchungsquelle', 'settings' => ['import_url' => 'https://portal.example/source.ics']]);
$analysis = app(ICalAnalysis::class)->summarize(app(ICalParser::class)->parseDocument(self::feed('primary', 'Reservation: Nora Beispiel')));
$source->forceFill(['ical_active_rules' => [self::primaryRule()], 'ical_analysis' => $analysis])->save();
$mirror = Channel::factory()->for($property)->create(['name' => 'Zweiter Kalender', 'settings' => ['import_url' => 'https://portal.example/mirror.ics']]);
$mirror->forceFill(['ical_active_rules' => [self::mirrorRule()]])->save();
return [$property, $source, $mirror];
}
private function occupations(Channel $source, Channel $mirror): array
{
$blocks = [];
foreach ([[$source, 'primary', 'Reservation: Nora Beispiel'], [$mirror, 'mirror', 'Blocked']] as [$channel, $uid, $summary]) {
$event = app(ICalParser::class)->parseDocument(self::feed($uid, $summary))['events'][0];
$block = BlockedPeriod::factory()->for($channel->property)->create(['source' => 'channel', 'channel_id' => $channel->id, 'external_uid' => $uid, 'starts_on' => '2027-05-23', 'ends_on' => '2027-05-30']);
$block->forceFill([...app(ApplyChannelRules::class)->attributes($channel, null, $event['properties']), 'ical_properties' => $event['properties'], 'ical_raw' => $event['raw']])->saveQuietly();
$blocks[] = $block;
}
return $blocks;
}
private static function primaryRule(): array
{
return ['name' => 'Buchung', 'priority' => 10, 'enabled' => true, 'case_sensitive' => false, 'match' => 'all', 'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reservation: ']], 'event_type' => 'portal_reservation', 'origin' => 'current', 'representation' => 'leading_candidate', 'extractions' => [['field' => 'SUMMARY', 'target' => 'guest_full_name', 'method' => 'after', 'start' => 'Reservation: ']]];
}
private static function mirrorRule(): array
{
return [...self::primaryRule(), 'name' => 'Belegtmeldung', 'conditions' => [['field' => 'SUMMARY', 'operator' => 'equals', 'value' => 'Blocked']], 'event_type' => 'block', 'origin' => 'unknown', 'representation' => 'additional_block', 'extractions' => []];
}
private static function feed(?string $uid = null, string $summary = '', string $start = '20270523', string $end = '20270530'): string
{
$event = $uid === null ? '' : "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261029T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:{$summary}\r\nEND:VEVENT\r\n";
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic//DE\r\n{$event}END:VCALENDAR\r\n";
}
}