Files
fewo-stommer/tests/Feature/ChannelSyncTest.php

292 lines
13 KiB
PHP

<?php
namespace Tests\Feature;
use App\Actions\MonitorChannels;
use App\Actions\RemindChannelTasks;
use App\Actions\SyncChannel;
use App\Channels\ChannelSyncException;
use App\Channels\ICal\ICalParser;
use App\Enums\BookingStatus;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
use App\Livewire\BookingRequest;
use App\Mail\ChannelConflict;
use App\Mail\ChannelSyncAlert;
use App\Mail\ChannelTasksNotification;
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 Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Filament\Actions\CreateAction;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
use Tests\TestCase;
class ChannelSyncTest extends TestCase
{
use RefreshDatabase;
private Property $property;
/** Response of every faked HTTP request; replaced per test step. */
private mixed $httpResponse = null;
protected function setUp(): void
{
parent::setUp();
// These tests submit the form instantly; the bot time trap is tested in SpamProtectionTest.
config(['fewo.spam.min_seconds' => 0]);
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed(PropertySeeder::class);
$this->property = Property::sole();
Mail::fake();
Http::fake(fn () => $this->httpResponse);
}
public function test_parser_reads_dates_datetimes_folded_lines_and_skips_cancelled_events(): void
{
$ics = implode("\r\n", [
'BEGIN:VCALENDAR',
'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',
'BEGIN:VEVENT', 'UID:a4', 'STATUS:CANCELLED', 'DTSTART;VALUE=DATE:20261115', 'DTEND;VALUE=DATE:20261118', 'END:VEVENT',
'BEGIN:VEVENT', 'UID:a5', 'DTSTART;VALUE=DATE:20261120', 'END:VEVENT',
'END:VCALENDAR',
]);
$periods = (new ICalParser)->parse($ics);
$this->assertSame(
[['a1', '2026-11-07', '2026-11-10'], ['a2', '2026-12-01', '2026-12-05'], ['a3-very-long-uid-that-is-folded', '2027-01-01', '2027-01-02'], ['a5', '2026-11-20', '2026-11-21']],
array_map(fn ($period): array => [$period->uid, $period->startsOn->toDateString(), $period->endsOn->toDateString()], $periods),
);
$this->assertSame('Reserviert , Familie', $periods[0]->summary);
}
public function test_parser_rejects_non_calendar_responses(): void
{
$this->expectException(ChannelSyncException::class);
(new ICalParser)->parse('<html>Login</html>');
}
public function test_sync_adds_changes_and_removes_imported_occupations(): void
{
$channel = $this->channel('FeWo-direkt');
$this->fakeFeed([['x1', '20261107', '20261110'], ['x2', '20261201', '20261208'], ['booking-5@fewo-stommer', '20261215', '20261220'], ['old', '20261001', '20261005']]);
$first = (new SyncChannel)->handle($channel);
$this->assertTrue($first->successful);
$this->assertSame([2, 2, 0, 0], [$first->events, $first->added, $first->changed, $first->removed]);
$this->assertSame(['x1', 'x2'], $channel->blockedPeriods()->pluck('external_uid')->all());
$this->fakeFeed([['x1', '20261107', '20261111']]);
$second = (new SyncChannel)->handle($channel);
$this->assertSame([0, 1, 1], [$second->added, $second->changed, $second->removed]);
$this->assertSame('2026-11-11', $channel->blockedPeriods()->sole()->ends_on->toDateString());
$this->assertNotNull($channel->fresh()->last_success_at);
}
public function test_overlap_with_an_existing_booking_is_reported_as_possible_double_booking(): void
{
Booking::factory()->for($this->property)->create(['arrival' => '2026-11-08', 'departure' => '2026-11-12', 'status' => BookingStatus::Confirmed]);
$channel = $this->channel('FeWo-direkt');
$this->fakeFeed([['x1', '20261107', '20261110']]);
$log = (new SyncChannel)->handle($channel);
$this->assertSame(1, $log->conflicts);
Mail::assertSent(ChannelConflict::class);
}
public function test_failed_import_is_logged_and_alerted_once_until_it_works_again(): void
{
$channel = $this->channel('Ostseeklar');
$this->httpResponse = Http::response('Server Error', 500);
$log = (new SyncChannel)->handle($channel);
$this->assertFalse($log->successful);
$this->assertNotNull($channel->fresh()->last_error);
$this->assertSame(1, (new MonitorChannels)->handle());
$this->assertSame(0, (new MonitorChannels)->handle());
Mail::assertSent(ChannelSyncAlert::class, 1);
$this->fakeFeed([]);
(new SyncChannel)->handle($channel);
$this->assertNull($channel->fresh()->alerted_at);
}
public function test_export_feed_contains_all_occupations_except_the_channels_own(): void
{
$fewo = $this->channel('FeWo-direkt');
$ostseeklar = $this->channel('Ostseeklar');
$booking = Booking::factory()->for($this->property)->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10', 'status' => BookingStatus::Confirmed]);
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $fewo->id, 'source' => 'channel', 'starts_on' => '2026-12-01', 'ends_on' => '2026-12-05']);
BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $ostseeklar->id, 'source' => 'channel', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-12']);
$feed = $this->get($fewo->exportUrl())->assertOk()->assertHeader('Content-Type', 'text/calendar; charset=utf-8')->getContent();
$this->assertStringContainsString("UID:booking-{$booking->id}@fewo-stommer", $feed);
$this->assertStringContainsString('DTSTART;VALUE=DATE:20261120', $feed);
$this->assertStringContainsString('DTSTART;VALUE=DATE:20261210', $feed);
$this->assertStringNotContainsString('DTSTART;VALUE=DATE:20261201', $feed);
$this->assertStringNotContainsString($booking->guest->last_name, $feed);
$this->get('/kalender/falsch.ics')->assertNotFound();
}
public function test_manual_portals_get_tasks_when_occupations_change_elsewhere(): void
{
$fewo = $this->channel('FeWo-direkt', manual: true);
$ostseeklar = $this->channel('Ostseeklar');
$booking = Booking::factory()->for($this->property)->reserved()->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']);
$this->assertSame(0, ChannelTask::count(), 'holds do not create tasks');
$booking->update(['status' => BookingStatus::Confirmed]);
$booking->update(['status' => BookingStatus::Cancelled]);
$this->fakeFeed([['ok1', '20261201', '20261205']]);
(new SyncChannel)->handle($ostseeklar);
$this->fakeFeed([['fd1', '20261210', '20261212']]);
(new SyncChannel)->handle($fewo);
$this->assertSame(
[[ChannelTaskAction::Block, '2026-11-07'], [ChannelTaskAction::Unblock, '2026-11-07'], [ChannelTaskAction::Block, '2026-12-01']],
$fewo->tasks()->orderBy('id')->get()->map(fn (ChannelTask $task): array => [$task->action, $task->starts_on->toDateString()])->all(),
);
$this->assertSame(0, $ostseeklar->tasks()->count());
Mail::assertSent(ChannelTasksNotification::class, 3);
}
public function test_open_tasks_are_reminded_once(): void
{
$task = ChannelTask::factory()->for($this->channel('FeWo-direkt', manual: true))->create();
$this->assertSame(0, (new RemindChannelTasks)->handle());
$this->travel(3)->hours();
$this->assertSame(1, (new RemindChannelTasks)->handle());
$this->assertSame(0, (new RemindChannelTasks)->handle());
$this->assertNotNull($task->fresh()->reminded_at);
}
public function test_tasks_are_sent_to_the_automation_and_completed_by_signed_callback(): void
{
config(['fewo.automation.webhook_url' => 'https://bot.example/tasks', 'fewo.automation.secret' => 'geheim']);
$this->httpResponse = Http::response(['queued' => true]);
$this->channel('FeWo-direkt', manual: true);
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
$task = ChannelTask::sole();
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://bot.example/tasks'
&& hash_equals(hash_hmac('sha256', $request->body(), 'geheim'), $request->header('X-Signature')[0])
&& $request['action'] === 'block');
$this->assertNotNull($task->fresh()->automation_sent_at);
$body = json_encode(['done' => true]);
$this->call('POST', route('channel-tasks.complete', $task), [], [], [], ['HTTP_X-Signature' => 'falsch', 'CONTENT_TYPE' => 'application/json'], $body)->assertForbidden();
$this->call('POST', route('channel-tasks.complete', $task), [], [], [], ['HTTP_X-Signature' => hash_hmac('sha256', $body, 'geheim'), 'CONTENT_TYPE' => 'application/json'], $body)->assertOk();
$this->assertSame([ChannelTaskStatus::Done, 'Automatisierung'], [$task->fresh()->status, $task->fresh()->completed_by]);
}
public function test_health_endpoint_reports_sync_state_for_external_monitoring(): void
{
$this->get('/health/sync')->assertNotFound();
config(['fewo.channels.health_token' => 'abc']);
$channel = $this->channel('FeWo-direkt');
$this->getJson('/health/sync?token=abc')->assertStatus(503)->assertJsonPath('status', 'degraded');
$this->fakeFeed([]);
(new SyncChannel)->handle($channel);
$this->getJson('/health/sync?token=abc')->assertOk()->assertJsonPath('channels.0.ok', true);
}
public function test_referral_and_utm_parameters_are_stored_with_the_request(): void
{
Livewire::withQueryParams(['utm_source' => 'instagram', 'utm_campaign' => 'herbst'])
->test(BookingRequest::class)
->set('arrival', '2026-11-07')
->set('departure', '2026-11-10')
->set('firstName', 'Anna')
->set('lastName', 'Muster')
->set('email', 'anna@example.com')
->set('referralSource', 'social_media')
->set('privacyAccepted', true)
->call('submit')
->assertHasNoErrors();
$booking = Booking::sole();
$this->assertSame(['social_media', 'instagram', 'herbst'], [$booking->referral_source->value, $booking->utm_source, $booking->utm_campaign]);
}
public function test_channels_are_managed_and_tasks_completed_in_the_admin(): void
{
$this->actingAs(User::factory()->create());
$this->fakeFeed([['x1', '20261107', '20261110']]);
Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $this->property, 'pageClass' => EditProperty::class])
->callAction(TestAction::make(CreateAction::class)->table(), [
'name' => 'FeWo-direkt',
'connector' => 'ical',
'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/abc.ics'],
'requires_manual_blocking' => true,
'manage_url' => 'https://www.fewo-direkt.de/vermieter/kalender',
])
->assertHasNoFormErrors();
$channel = Channel::sole();
Livewire::test(ChannelsRelationManager::class, ['ownerRecord' => $this->property, 'pageClass' => EditProperty::class])
->callTableAction('sync', $channel)
->assertNotified('1 Belegungen eingelesen');
BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-11-20', 'ends_on' => '2026-11-22']);
$task = ChannelTask::sole();
Livewire::test(ListChannelTasks::class)
->assertCanSeeTableRecords([$task])
->callTableAction('done', $task);
$this->assertSame(ChannelTaskStatus::Done, $task->fresh()->status);
}
private function channel(string $name, bool $manual = false): Channel
{
return Channel::factory()->for($this->property)->create(['name' => $name, 'requires_manual_blocking' => $manual]);
}
/**
* @param list<array{string, string, string}> $events uid, start, end (Ymd)
*/
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")
->implode('')."END:VCALENDAR\r\n";
$this->httpResponse = Http::response($body, 200, ['Content-Type' => 'text/calendar']);
}
}