Files
fewo-stommer/tests/Feature/EndToEndStayAcceptanceTest.php
T

628 lines
43 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\ExpireReservations;
use App\Actions\ProcessPortalMail;
use App\Actions\RecordPayment;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Channels\Mail\PortalMail;
use App\Documents\DocumentReleases;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CaseIntakeMode;
use App\Enums\CaseType;
use App\Enums\ChangeBasis;
use App\Enums\DocumentKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Enums\ProcessingMode;
use App\Filament\Pages\EffectiveSettings;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Mail\ArrivalInformation;
use App\Mail\BookingConfirmed;
use App\Mail\BookingWishAnswered;
use App\Mail\BookingWishNotice;
use App\Mail\InformationSent;
use App\Mail\OfferMade;
use App\Mail\ReviewRequest;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Extra;
use App\Models\InboxMessage;
use App\Models\Property;
use App\Models\Season;
use App\Models\User;
use App\Pricing\CaseMoney;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\CaseClosure;
use App\Process\WorkList;
use App\Support\Content;
use App\Support\Money;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;
use Tests\TestCase;
/**
* Business acceptance T16–T25 (docs/Prozessarchitektur/END_TO_END_ABNAHME.md): packages 7 and 9 played through the
* way the landlord and the guest work – the case page and its actions, the guest's links, the daily run – and checked
* by what they see: the case, its next step, the calendar, the tasks, the money and the mails. T23 (real SMTP) lives in
* {@see TestOperationSmtpAcceptanceTest}.
*/
class EndToEndStayAcceptanceTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private Channel $manualPortal;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
app(TenantContext::class)->set($this->property->tenant);
$this->manualPortal = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'booking_model' => 'inquiry', 'connector' => 'ical', 'import_enabled' => false, 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']);
Mail::fake();
Storage::fake('local');
Http::fake(fn () => Http::response('', 500));
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
/** T16 – hold 0: information "unter Vorbehalt", nothing reserved, the guest asks for the booking, the landlord confirms. */
public function test_t16_information_without_hold_and_booking_wish(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$booking = $this->request();
$this->assertNull($booking->hold_expires_at);
$this->assertSame(0, Booking::query()->occupying()->count(), 'the calendar stays free');
$this->assertSame('Unverbindliche Auskunft prüfen und senden', WorkList::items()[0]['title']);
$this->assertSame(DocumentKind::Information, DocumentKind::forCase($booking));
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])
->assertNotified('Auskunft gesendet');
$booking->refresh();
$this->assertSame([BookingStatus::Reserved, 1, 0, null], [$booking->status, $booking->information_version, $booking->offer_version, $booking->hold_expires_at]);
$this->assertSame(0, Booking::query()->occupying()->count(), 'still nothing reserved');
Mail::assertNotSent(OfferMade::class);
Mail::assertSent(InformationSent::class, fn (InformationSent $mail): bool => str_contains($mail->render(), 'keine Buchung und keine Reservierung') && ! str_contains($mail->render(), 'annehmen'));
$show = URL::temporarySignedRoute('information.show', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->get($show)->assertOk()->assertSee('Dies ist noch keine Buchung und keine Reservierung.')->assertSee('Buchung anfragen')->assertDontSee('Angebot annehmen');
$wish = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'noch nicht verbindlich'));
$this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'bereits vor'));
$booking->refresh();
$this->assertSame(BookingStatus::Reserved, $booking->status, 'a wish is no booking');
$this->assertSame(0, Booking::query()->occupying()->count());
$this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->count(), 'one task however often the guest clicks');
Mail::assertSent(BookingWishAnswered::class, 1);
$this->assertSame('Buchungswunsch bestätigen?', WorkList::items()[0]['title']);
$this->assertSame('decideWish', CaseActivities::next($booking)?->action);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('decideWish', ['decision' => 'confirm'])
->assertNotified('Buchung bestätigt');
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertSame('booking_wish', $booking->acceptance['via']);
$this->assertSame('Ingrid', $booking->acceptance['confirmed_by']);
$this->assertNotNull($booking->contract_path);
Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => str_contains($mail->render(), 'Buchungswunsch'));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->exists(), 'the manual portal is blocked now');
$this->assertStringContainsString('Buchungswunsch', $booking->events()->where('type', 'wish')->reorder()->orderByDesc('id')->value('summary'));
}
/** T16 (old link, expiry): a replaced information no longer works; an unanswered one ends without booking. */
public function test_t16_old_links_and_unanswered_information(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$booking = $this->request();
$this->sendInformation($booking);
$this->sendInformation($booking->fresh());
$booking->refresh();
$this->assertSame(2, $booking->information_version);
$old = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->post($old, ['terms' => '1'])->assertSessionHas('information.error', fn (string $text): bool => str_contains($text, 'nicht mehr aktuell'));
$this->assertNull($booking->fresh()->wish_at);
$this->travelTo($booking->information_valid_until->addMinute());
app(ExpireReservations::class)->handle();
$this->assertSame(BookingStatus::Expired, $booking->fresh()->status);
$this->flushSession();
$current = URL::temporarySignedRoute('information.show', now()->addDay(), ['booking' => $booking, 'v' => 2]);
$this->get($current)->assertOk()->assertSee('abgeschlossen');
}
/** T17 – the dates were given away between information and wish: no booking, a friendly answer, a note for the landlord. */
public function test_t17_booking_wish_after_the_dates_were_given_away(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$first = $this->request();
$this->sendInformation($first);
$second = $this->request('zweite@example.org');
$this->sendInformation($second);
// Meanwhile the first guest books and a portal reports an occupation that touches the second guest's stay.
$this->wish($first->fresh());
Livewire::test(ViewBooking::class, ['record' => $first->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']);
$this->assertSame(BookingStatus::Confirmed, $first->fresh()->status);
$this->post(URL::temporarySignedRoute('information.wish', $second->fresh()->information_valid_until, ['booking' => $second, 'v' => 1]), ['terms' => '1'])
->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'inzwischen vergeben'));
$second->refresh();
$this->assertSame(BookingStatus::Declined, $second->status);
$this->assertSame(1, Booking::query()->occupying()->count(), 'no double booking');
Mail::assertSent(BookingWishAnswered::class, fn (BookingWishAnswered $mail): bool => $mail->outcome === 'unavailable' && $mail->booking->is($second));
Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'unavailable');
$this->assertTrue(InboxMessage::query()->where('subject', 'like', '%Zeitraum inzwischen vergeben%')->exists());
// A portal occupation imported meanwhile has the same effect.
$third = $this->request('dritte@example.org', '2026-11-21', '2026-11-24');
$this->sendInformation($third);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'channel', 'channel_id' => $this->manualPortal->id, 'starts_on' => '2026-11-22', 'ends_on' => '2026-11-26']);
$this->wish($third->fresh());
$this->assertSame(BookingStatus::Declined, $third->fresh()->status);
}
/** T17 – price changed, calendar not current: even in automatic mode the wish waits for the landlord, with the reasons. */
public function test_t17_changed_price_and_stale_calendar_need_the_landlord(): void
{
$this->automaticWithoutHold();
$booking = $this->request();
$this->assertSame(1, $booking->fresh()->information_version, 'sent automatically');
Season::query()->whereDate('starts_on', '<=', '2026-11-07')->whereDate('ends_on', '>', '2026-11-07')->update(['nightly_rate' => 9900]);
Channel::factory()->for($this->property)->create(['name' => 'Kalenderportal', 'connector' => 'ical', 'import_enabled' => true, 'status' => 'active', 'settings' => ['import_url' => 'https://portal.example/cal.ics'], 'last_success_at' => now()->subDays(2)]);
$this->wish($booking->fresh());
$booking->refresh();
$this->assertSame(BookingStatus::Reserved, $booking->status);
$findings = implode(' ', $booking->wish['findings']);
$this->assertStringContainsString('Der Preis hat sich seit der Auskunft geändert', $findings);
$this->assertStringContainsString('Kalenderstand von Kalenderportal', $findings);
$task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->sole();
$this->assertStringContainsString('Preis', (string) $task->note);
// The landlord honours the price of the information (the guest was told it).
$told = $booking->total;
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']);
$this->assertSame([BookingStatus::Confirmed, $told], [$booking->fresh()->status, $booking->fresh()->total]);
}
/** T18 – automatic and manual handling of a wish; two guests for the same dates never both get the booking. */
public function test_t18_automatic_wish_is_confirmed_at_once_and_the_competitor_gets_a_refusal(): void
{
$this->automaticWithoutHold();
$first = $this->request();
$second = $this->request('zweite@example.org');
Mail::assertSent(InformationSent::class, 2);
$this->wish($first->fresh());
$first->refresh();
$this->assertSame(BookingStatus::Confirmed, $first->status, 'confirmed automatically after the new check');
$this->assertSame('automatisch nach erneuter Prüfung', $first->acceptance['confirmed_by']);
Mail::assertSent(BookingConfirmed::class, 1);
Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'confirmed');
$this->wish($second->fresh());
$this->assertSame(BookingStatus::Declined, $second->fresh()->status);
$this->assertSame(1, Booking::query()->occupying()->count());
Mail::assertSent(BookingConfirmed::class, 1);
}
/** T19 – A1 from the request to the closed stay: offer, payments, preparation, services, arrival, departure, closing. */
public function test_t19_complete_a1_process_until_the_stay_is_closed(): void
{
$this->property->update(['asks_arrival_time' => true, 'stay_tasks' => [
['title' => 'Schlüsselübergabe', 'when' => 'on_arrival', 'responsible' => 'Nachbarin Frau Kruse', 'applies_to' => ['rental']],
['title' => 'Endreinigung', 'when' => 'after_departure', 'responsible' => 'Reinigung Müller', 'applies_to' => ['rental', 'private']],
]]);
$booking = $this->request();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('sendOffer')->arguments([]), ['acknowledged' => true]);
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1']);
$booking->refresh();
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today());
app(RecordPayment::class)->handle($booking->fresh(), (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today());
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
// Five days before arrival: the arrival time is missing, the stay tasks are planned.
$this->travelTo(CarbonImmutable::parse('2026-11-02 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$tasks = BookingTask::query()->where('booking_id', $booking->id)->get();
$this->assertSame(1, $tasks->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'once, however often the run repeats');
$this->assertSame(['Endreinigung', 'Schlüsselübergabe'], $tasks->where('kind', BookingTaskKind::Service)->pluck('title')->sort()->values()->all());
$this->assertSame('Anreisedaten beim Gast erfragen', CaseActivities::next($booking->fresh())?->label);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('arrivalDetails', ['arrival_time' => 'gegen 16 Uhr', 'phone' => '0171 1234567', 'email' => 'gesa@example.org']);
$this->assertSame(BookingTaskStatus::Done, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->value('status'));
$this->travelTo(CarbonImmutable::parse('2026-11-04 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertSent(ArrivalInformation::class, 1);
// Arrival: the key handover is done.
$this->travelTo(CarbonImmutable::parse('2026-11-07 15:00'));
$handover = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Schlüsselübergabe')->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $handover->id, 'outcome' => 'done', 'note' => 'Schlüssel übergeben']);
// After the departure the cleaning is still open: the stay waits for it.
$this->travelTo(CarbonImmutable::parse('2026-11-11 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
$this->assertStringContainsString('Endreinigung', (string) collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'closure')?->detail);
$cleaning = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Endreinigung')->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $cleaning->id, 'outcome' => 'handed_over', 'handed_to' => 'Reinigung Müller', 'note' => 'erledigt laut Rückmeldung']);
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertNotNull($booking->settled_at, 'fully paid: nothing open commercially');
$this->travelTo(CarbonImmutable::parse('2026-11-14 08:00'));
app(RequestReviews::class)->handle();
$activities = collect(CaseActivities::for($booking));
$this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'closure')->state);
$this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'settlement')->state);
$this->assertStringContainsString('Übergeben an Reinigung Müller', (string) $activities->firstWhere('label', 'Endreinigung')?->detail);
Mail::assertSent(ReviewRequest::class, 1);
$this->assertSame([], collect(WorkList::items())->where('url', 'like', '%bookings/'.$booking->id.'%')->all());
}
/** T20 – A4: portal payment, stay, later payout; "paid according to the portal" never reads as money received. */
public function test_t20_complete_a4_process_with_portal_payment_and_later_payout(): void
{
$fewo = $this->fewo(['process_overrides' => ['booking' => ['payments' => 'portal', 'guest_messages' => 'portal']]]);
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-A4FLOW");
$booking = Booking::query()->sole();
$this->assertSame(CaseType::A4, $booking->case_type);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22',
'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69']],
'paid' => [['amount' => '979.51', 'paid_on' => '2026-10-21']]]);
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status, 'paid to the portal is not "Anzahlung erhalten" / "Bezahlt"');
$this->assertSame(0, CaseMoney::of($booking)->receivedOnAccount());
$history = $booking->events()->pluck('summary')->implode(' | ');
$this->assertStringContainsString('Laut FeWo-direkt hat der Gast '.Money::format(97951).' an das Portal gezahlt – noch kein Geld bei uns', $history);
$this->assertStringNotContainsString('Anzahlung eingegangen', $history);
$activities = collect(CaseActivities::for($booking));
$this->assertSame(ActivityState::External, $activities->firstWhere('key', 'arrival_info')->state);
$this->assertStringContainsString('(angekündigt)', $activities->firstWhere('key', 'arrival_info')->detail);
$this->assertSame(ActivityState::Waiting, $activities->firstWhere('key', 'payout')->state);
$this->travelTo(CarbonImmutable::parse('2026-12-04 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertNotSent(ArrivalInformation::class);
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])->count());
$this->travelTo(CarbonImmutable::parse('2026-12-15 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status, 'the outstanding payout does not hold the stay up');
$this->assertNull($booking->settled_at);
$payout = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PayoutCheck)->sole();
$this->assertSame('2026-12-28', $payout->due_on->toDateString());
$this->assertSame(ActivityState::Waiting, collect(CaseActivities::for($booking))->firstWhere('key', 'task_payout_check')->state, 'not due yet');
$this->assertContains('Die Auszahlung von FeWo-direkt ist noch nicht eingegangen.', CaseClosure::commercialPoints($booking));
$this->travelTo(CarbonImmutable::parse('2026-12-29 08:00'));
$this->assertSame('Auszahlung des Portals prüfen', collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id))['title'] ?? null);
app(RecordPayment::class)->handle($booking->fresh(), 89469, CarbonImmutable::today(), PaymentMethod::Transfer, kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$booking->refresh();
$this->assertSame(BookingTaskStatus::Done, $payout->fresh()->status);
$this->assertNotNull($booking->settled_at, 'commercially settled once the payout arrived');
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertSame($fewo->id, $booking->origin_channel_id);
}
/** T21 – A6 family stay: services prepared, no guest mails, closing without reminders; the agreed money settles it. */
public function test_t21_family_stay_with_preparation_and_closing(): void
{
$this->property->update(['tourist_tax_rate' => 250, 'stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental', 'private']]]]);
$linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 1800, 'pricing' => 'per_item', 'is_active' => true]);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::OWN_USE, 'internal_kind' => InternalKind::PrivateStay->value, 'occasion' => 'Besuch von Tochter Anna', 'property_id' => $this->property->id, 'guests' => 3, 'arrival' => '2026-11-14', 'departure' => '2026-11-19',
'stay_first_name' => 'Anna', 'stay_last_name' => 'Stommer', 'stay_email' => 'anna@example.org', 'rent' => '0', 'tourist_tax_persons' => 2,
'items' => [['extra_id' => $linen->id, 'quantity' => 3]]])
->call('create')->assertHasNoFormErrors();
$visit = Booking::query()->sole();
$this->travelTo(CarbonImmutable::parse('2026-11-10 08:00'));
app(SendBookingReminders::class)->handle();
$titles = BookingTask::query()->where('booking_id', $visit->id)->pluck('title')->sort()->values()->all();
$this->assertSame(['Bereitstellen: 3 × Wäschepaket', 'Endreinigung'], $titles);
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'no arrival details for family');
$this->travelTo(CarbonImmutable::parse('2026-11-20 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertSame(BookingStatus::Confirmed, $visit->fresh()->status, 'the stay waits for its open tasks');
foreach (BookingTask::query()->where('booking_id', $visit->id)->get() as $task) {
Livewire::test(ViewBooking::class, ['record' => $visit->getRouteKey()])->callAction('completeTask', ['task' => $task->id, 'outcome' => 'done']);
}
app(SendBookingReminders::class)->handle();
app(RequestReviews::class)->handle();
$visit->refresh();
$this->assertSame(BookingStatus::Completed, $visit->status);
$this->assertNull($visit->settled_at);
$this->assertSame(['Vereinbarte Zahlung noch offen: '.Money::format(7900).' (ohne Erinnerungen).'], CaseClosure::commercialPoints($visit));
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('status', BookingTaskStatus::Open)->count(), 'no reminders of any kind');
app(RecordPayment::class)->handle($visit, 7900, CarbonImmutable::today(), PaymentMethod::Cash);
$this->assertNotNull($visit->fresh()->settled_at);
Mail::assertNotSent(ArrivalInformation::class);
Mail::assertNotSent(ReviewRequest::class);
}
/** T22 – the stay is closed while money is still open; the claim stays visible and the commercial closing waits. */
public function test_t22_stay_closed_while_commercial_points_are_open(): void
{
$booking = $this->confirmedOwnBooking();
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today());
$this->travelTo(CarbonImmutable::parse('2026-11-12 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status, 'open money does not hold the stay up');
$this->assertNull($booking->settled_at);
$this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->whereIn('kind', [BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim])->count(), 'exactly one follow-up for the open amount');
$this->assertNotNull(collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id)), 'the follow-up stays in the work list');
$this->assertStringContainsString('Noch offen vom Gast', implode(' ', CaseClosure::commercialPoints($booking)));
$this->assertSame('Aufenthalt abgeschlossen, kaufmännisch noch offen', explode(' · ', CaseActivities::situation($booking))[1]);
app(RecordPayment::class)->handle($booking, (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today());
$booking->refresh();
$this->assertNotNull($booking->settled_at);
$this->assertSame(BookingStatus::Completed, $booking->status, 'a late payment does not reopen the stay');
// A contradicting payout statement is settled by the landlord with a reason.
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-DIFF01");
$portal = Booking::query()->where('portal_reference', 'HA-DIFF01')->sole();
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22',
'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69'], ['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Erwartet', 'amount' => '900.20']]]);
$this->travelTo(CarbonImmutable::parse('2026-12-15 08:00'));
app(SendBookingReminders::class)->handle();
app(RecordPayment::class)->handle($portal->fresh(), 89469, CarbonImmutable::today(), kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$portal->refresh();
$this->assertSame(BookingStatus::Completed, $portal->status);
$this->assertNull($portal->settled_at, 'the 5,51 € difference is not settled by the system');
// Decision O5 (Architektur V2): a reason alone is not enough with portal collection – the kind of clarification is required.
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'])->assertHasActionErrors(['clarification']);
$this->assertNull($portal->fresh()->settled_at);
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['clarification' => 'difference_booked', 'note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert']);
$portal->refresh();
$this->assertSame(['Ingrid', 'Differenz geklärt und verbucht: Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'], [$portal->settled_by, $portal->settled_note]);
}
/** T24 – landlord, property, portal and case settings decide the whole run. */
public function test_t24_settings_of_every_level_are_effective_in_the_whole_run(): void
{
$this->releaseTexts();
DocumentReleases::set(DocumentKind::Information, true, 'Test');
// Landlord: automatic, requests reserve. Portal Ostseeklar (requests): no reservation, manual. Property: arrival information 5 days ahead.
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => true]]);
$this->manualPortal->update(['process_overrides' => ['inquiry' => ['pre_reservation' => false, 'processing' => 'manual']]]);
$this->property->update(['process_overrides' => ['arrival_info_days_before' => 5], 'asks_arrival_time' => true]);
$direct = $this->request();
$this->assertSame(BookingStatus::OfferSent, $direct->fresh()->status, 'landlord level: automatic offer with hold');
$this->assertNotNull($direct->fresh()->hold_expires_at);
$viaPortal = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-21'), CarbonImmutable::parse('2026-11-24'), 2), ['first_name' => 'Pia', 'last_name' => 'Portal', 'email' => 'pia@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], originChannel: $this->manualPortal->fresh());
$this->assertSame([0, 0, null], [$viaPortal->fresh()->information_version, $viaPortal->fresh()->offer_version, $viaPortal->fresh()->hold_expires_at], 'portal level: no hold, manual');
$this->assertSame('sendInformation', CaseActivities::next($viaPortal->fresh())?->action);
Livewire::test(ViewBooking::class, ['record' => $viaPortal->getRouteKey()])->callAction('automation', ['mode' => ProcessingMode::Automatic->value]);
$this->assertSame(1, $viaPortal->fresh()->information_version, 'case level: switched to automatic, the information goes out');
$this->wish($viaPortal->fresh());
$this->assertSame(BookingStatus::Confirmed, $viaPortal->fresh()->status, 'and the wish is confirmed automatically');
// Property level: arrival details are asked for 5 + 2 days ahead, the arrival information 5 days ahead.
$this->travelTo(CarbonImmutable::parse('2026-11-14 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertTrue(BookingTask::query()->where('booking_id', $viaPortal->id)->where('kind', BookingTaskKind::ArrivalDetails)->exists());
Mail::assertNotSent(ArrivalInformation::class);
$this->travelTo(CarbonImmutable::parse('2026-11-16 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertSent(ArrivalInformation::class, fn (ArrivalInformation $mail): bool => $mail->booking->is($viaPortal));
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(EffectiveSettings::class)->set('bookingId', $viaPortal->id)->assertSee('für diesen Vorgang umgestellt')->assertSee('Abweichung des Portals');
}
/** T25 – change of a binding portal booking: the portal's new price, the calendar and the portal tasks follow. */
public function test_t25_change_of_a_binding_portal_booking(): void
{
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-CHANGE");
$booking = Booking::query()->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22']);
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-14')->exists());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-12-07', 'departure' => '2026-12-16', 'guests' => 2, 'portal_total' => '1199.00', 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Portal->value, 'reason' => 'Verlängerung über FeWo-direkt'])
->assertNotified('Änderung gespeichert');
$booking->refresh();
$this->assertSame(['2026-12-16', 119900, 'portal'], [$booking->departure->toDateString(), $booking->total, $booking->quote['source'] ?? null], 'the portal price counts, nothing is recalculated');
$this->assertSame(CaseType::A4, $booking->case_type);
$this->assertSame(0, CaseMoney::of($booking)->openForUs(), 'the portal still collects');
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-16')->exists(), 'portal task for the new dates');
$this->assertSame(ChangeBasis::Portal, $booking->changes()->sole()->basis);
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::RefundCheck)->count());
}
/** Special cases: unknown guest contact of a portal booking, unknown portal price, a cancellation shortly before arrival. */
public function test_special_cases_of_preparation_and_closing(): void
{
$this->property->update(['stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental']]]]);
$this->fewo();
$this->portalMail("Anreise: 30.10.2026\nAbreise: 02.11.2026\nBuchungsnummer: HA-NOMAIL");
$portal = Booking::query()->sole();
$this->travelTo(CarbonImmutable::parse('2026-10-26 08:00'));
app(SendBookingReminders::class)->handle();
$details = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::ArrivalDetails)->sole();
$this->assertStringContainsString('im Portal FeWo-direkt nachsehen', (string) $details->note, 'contact of a portal guest may have to come from the portal');
$this->travelTo(CarbonImmutable::parse('2026-11-03 08:00'));
$cleaning = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::Service)->sole();
$cleaning->complete('Ingrid');
app(SendBookingReminders::class)->handle();
$portal->refresh();
$this->assertSame(BookingStatus::Completed, $portal->status);
$this->assertSame(BookingTaskStatus::Dismissed, $details->fresh()->status, 'arrival details are moot after the departure');
$this->assertContains('Der Gesamtpreis laut FeWo-direkt fehlt.', CaseClosure::commercialPoints($portal), 'an unknown portal price is no invented 0');
// Cancellation two days before arrival: preparation is dropped, costs keep the case open commercially.
$own = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-05'), CarbonImmutable::parse('2026-11-08'), 2), ['first_name' => 'Kurt', 'last_name' => 'Kurzfristig', 'email' => 'kurt@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('confirm', ['notify' => false]);
app(SendBookingReminders::class)->handle();
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->exists());
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Krankheit', 'notify' => false, 'costs_task' => true]);
$own->refresh();
$this->assertSame(BookingStatus::Cancelled, $own->status);
$this->assertSame(BookingTaskStatus::Dismissed, BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->value('status'));
$this->assertNull($own->settled_at, 'the cancellation fee is still to be settled');
BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::CancellationFee)->sole()->complete('Ingrid', 'Keine Kosten berechnet (Kulanz).');
$this->assertNotNull($own->fresh()->settled_at);
}
/** Special case: an issue during the stay holds the closing up, a follow-up (damage) does not. */
public function test_issues_hold_the_stay_up_and_follow_ups_do_not(): void
{
$booking = $this->confirmedOwnBooking();
$this->travelTo(CarbonImmutable::parse('2026-11-08 10:00'));
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::Issue->value, 'title' => 'Kaffeemaschine defekt', 'responsible' => 'Ingrid']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::FollowUp->value, 'title' => 'Fleck im Teppich – Reinigung abrechnen']);
$this->assertSame(2, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::Issue, BookingTaskKind::FollowUp])->count());
$this->travelTo(CarbonImmutable::parse('2026-11-11 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertNotSame(BookingStatus::Completed, $booking->fresh()->status, 'the open issue holds the stay up');
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('closeStay', ['note' => 'Kaffeemaschine ersetzt']);
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertSame(BookingTaskStatus::Open, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::FollowUp)->value('status'), 'the follow-up stays on the closed case');
$this->assertSame('Kaffeemaschine ersetzt', BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::Issue)->value('note'));
}
/** Section 5: stored statuses are not silently reinterpreted; the command shows and corrects them on request. */
public function test_existing_payment_statuses_are_only_corrected_on_request(): void
{
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-OLDPAY");
$booking = Booking::query()->sole();
$booking->update(['total' => 97951, 'deposit' => 30000]);
// As the old rule left it: "paid according to the portal" had moved the status.
$booking->payments()->create(['amount' => 39061, 'paid_on' => '2026-10-20', 'method' => PaymentMethod::Transfer, 'kind' => PaymentKind::GuestViaPortal]);
$booking->update(['status' => BookingStatus::DepositPaid]);
$this->artisan('cases:recheck-payment-status')->expectsOutputToContain('Vorschau')->assertSuccessful();
$this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status, 'nothing changed by the preview');
$this->artisan('cases:recheck-payment-status', ['--apply' => true])->expectsOutputToContain('korrigiert')->assertSuccessful();
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
$this->assertStringContainsString('laut Portal bezahlt', (string) $booking->events()->where('type', 'status')->reorder()->orderByDesc('id')->value('reason'));
}
private function request(string $email = 'gesa@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
{
return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email, 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE']);
}
private function sendInformation(Booking $booking): void
{
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])
->assertNotified('Auskunft gesendet');
}
private function wish(Booking $booking): void
{
$this->post(URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => $booking->information_version]), ['terms' => '1'])->assertRedirect();
}
private function automaticWithoutHold(): void
{
$this->releaseTexts();
DocumentReleases::set(DocumentKind::Information, true, 'Test');
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]);
}
private function confirmedOwnBooking(): Booking
{
$booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('confirm', ['notify' => false]);
return $booking->fresh();
}
/**
* @param array<string, mixed> $attributes
*/
private function fewo(array $attributes = []): Channel
{
return Channel::query()->where('name', 'FeWo-direkt')->first() ?? Channel::factory()->for($this->property)->create([
'name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'case_intake' => CaseIntakeMode::Create,
'settings' => ['email_senders' => 'fewo-direkt.de'], 'process_overrides' => ['booking' => ['payments' => 'portal']], ...$attributes,
]);
}
private function portalMail(string $text): void
{
app(ProcessPortalMail::class)->handle(new PortalMail(uniqid('msg-'), 'noreply@fewo-direkt.de', 'Neue Buchung', $text, CarbonImmutable::now()));
}
private function releaseTexts(): void
{
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']);
DocumentReleases::set(DocumentKind::ExternalRecord, false, 'Test');
}
}