Files
fewo-stommer/tests/Feature/EndToEndAcceptanceTest.php
LarsandClaude Opus 5.5 ccac78a6c9 v0.11 U2: Angebots-Gate, gemeinsamer Fakteneingang mit Herkunft
- CaseRequirements: Vor einem eigenen verbindlichen Angebot und vor der
  verbindlichen Bestätigung eines Buchungswunsches müssen Vor- und
  Nachname, E-Mail, vollständige Anschrift mit Land, Personenzahl und
  Zeitraum vorliegen – harter Blocker, auch von Hand (G2a, B3). Die
  Auskunft unter Vorbehalt bleibt ohne dieses Gate.
- ContributeCaseFacts (S5): jede Angabe mit Herkunft und Ergebnis in
  case_facts; fehlend → übernommen, gleich → bestätigt, abweichend vom
  Gast → Prüfaufgabe (Kartei bleibt), Vermieterin maßgeblich, Zeitraum und
  Personen → Änderungswunsch; idempotent; danach einmal CaseAutomation.
- ProvideGuestContact und Webformular nutzen den Fakteneingang.
- Land als ISO-Code mit „Deutschland“ als änderbarem Formularstandard;
  guests.country ohne stillen Standardwert (B4).
- Testdaten bestehender Tests um Anschriften ergänzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:07:18 +01:00

515 lines
35 KiB
PHP
Raw Permalink 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\ProcessPortalMail;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPayment;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Actions\SyncChannel;
use App\Channels\ICal\ICalFeed;
use App\Channels\Mail\PortalMail;
use App\Documents\DocumentReleases;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\CaseIntakeMode;
use App\Enums\CaseType;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
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\BookingCancelled;
use App\Mail\BookingChanged;
use App\Mail\BookingConfirmed;
use App\Mail\ChangeProposed;
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\Property;
use App\Models\User;
use App\Pricing\CaseMoney;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ProcessSettings;
use App\Process\WorkList;
use App\Support\Content;
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\Mail\Events\MessageSent;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Event;
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;
/**
* The business acceptance catalogue (docs/Prozessarchitektur/END_TO_END_ABNAHME.md, T01–T14): every case is played
* through the way the landlord works – the "Neu" dialog, the case page and its actions, the guest's links – and checked
* by what she would see: the case, its next step, the calendar and portal tasks, the money and the mails.
*/
class EndToEndAcceptanceTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private Channel $manualPortal;
/** What the portal calendars deliver (null: the portal cannot be reached). */
private ?string $feed = null;
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);
// A portal that has to be blocked by hand: every change of the calendar becomes a portal task.
$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 () => $this->feed === null ? Http::response('', 500) : Http::response($this->feed));
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
/** T01 – own request, automatic: the offer goes out by itself and the case waits for the guest. */
public function test_t01_own_request_handled_automatically(): void
{
$this->releaseTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
$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']);
$this->assertSame([BookingStatus::OfferSent, CaseType::A1], [$booking->status, $booking->case_type]);
Mail::assertSent(OfferMade::class, 1);
$this->assertSame('acceptance', collect(CaseActivities::for($booking))->firstWhere('state.value', 'waiting')?->key);
$this->assertSame([], WorkList::items(), 'nothing for the landlord to do');
}
/** T02 – own request, manual: prepared, released by the landlord, accepted by the guest, confirmed automatically. */
public function test_t02_own_request_released_by_hand_and_accepted_by_the_guest(): void
{
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::INQUIRY, 'property_id' => $this->property->id, 'guests' => 2, 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE', 'send_mails' => false])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame('Angebot prüfen und senden', WorkList::items()[0]['title']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendOffer')->arguments([]))
->assertNotified('Angebot gesendet');
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1'])->assertRedirect();
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertNotNull($booking->contract_path);
Mail::assertSent(BookingConfirmed::class, 1);
$this->assertSame(1, ChannelTask::query()->where('channel_id', $this->manualPortal->id)->count(), 'the manual portal is blocked');
}
/** T03 – missing guest data: one understandable task, then the case continues automatically. */
public function test_t03_missing_guest_data_becomes_a_task_and_the_case_continues(): void
{
$this->releaseTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::INQUIRY, 'property_id' => $this->property->id, 'guests' => 2, 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'first_name' => 'Paul', 'last_name' => 'Telefon', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE', 'send_mails' => true])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame('E-Mail-Adresse des Gastes eintragen', WorkList::items()[0]['title']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Paul', 'last_name' => 'Telefon', 'email' => 'paul@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], 'process' => ProvideGuestContact::AUTOMATIC, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert, Angebot gesendet');
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
}
/** T04 – FeWo-direkt direct booking: one case, the portal's price, payments with the portal, no reminders. */
public function test_t04_fewo_direkt_booking_is_one_case_with_the_portal_price_and_portal_payments(): void
{
$fewo = $this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-7X3K9Q");
$booking = Booking::query()->sole();
$this->assertSame([CaseType::A4, IntakeKind::Booking, BookingStatus::Confirmed, 0], [$booking->case_type, $booking->intake, $booking->status, $booking->offer_version]);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22'])
->assertNotified('Beträge gespeichert');
$booking->refresh();
$this->assertSame(97951, $booking->total);
$this->assertSame(Responsibility::Portal, CaseMoney::of($booking)->collector());
$this->assertSame(0, CaseMoney::of($booking)->openForUs());
$this->travelTo(CarbonImmutable::parse('2026-12-01'));
app(SendBookingReminders::class)->handle();
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->count(), 'no reminders of our own');
$this->assertSame($fewo->id, $booking->origin_channel_id);
}
/** T05 – Destination Solutions: binding on the portal, contract documents and payments by us. */
public function test_t05_destination_solutions_booking_with_our_documents_and_payments(): void
{
$ds = Channel::factory()->for($this->property)->create(['name' => 'Destination Solutions', 'booking_model' => 'portal_booking']);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::EXTERNAL, 'property_id' => $this->property->id, 'arrival' => '2027-02-01', 'departure' => '2027-02-08', 'guests' => 2, 'channel_id' => $ds->id, 'portal_reference' => 'DS-4711', 'portal_total' => '840.00', 'first_name' => 'Hans', 'last_name' => 'Gast', 'email' => 'hans@example.org'])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame([CaseType::A3, 84000, 'DS-4711'], [$booking->case_type, $booking->total, $booking->portal_reference]);
$this->assertTrue($booking->wantsPaymentTasks());
$this->assertSame('sendDocuments', collect(CaseActivities::for($booking))->firstWhere('key', 'documents')->action);
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today(), PaymentMethod::Transfer);
$this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status);
}
/** T06 – the same booking by mail and calendar stays one case. */
public function test_t06_duplicate_portal_reports_make_one_case(): void
{
$fewo = $this->fewo(['settings' => ['import_url' => 'https://portal.example/fewo.ics', 'email_senders' => 'fewo-direkt.de']]);
$fewo->forceFill(['ical_active_rules' => [['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' => 'DESCRIPTION', 'target' => 'booking_reference', 'method' => 'after', 'start' => 'Buchung ']]]]])->save();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-7X3K9Q");
$this->feed = ("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//DE\r\nBEGIN:VEVENT\r\nUID:evt-1\r\nDTSTAMP:20261022T090000Z\r\nDTSTART;VALUE=DATE:20261207\r\nDTEND;VALUE=DATE:20261214\r\nSUMMARY:Reservation\r\nDESCRIPTION:Buchung HA-7X3K9Q\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n");
app(SyncChannel::class)->handle($fewo->fresh());
app(SyncChannel::class)->handle($fewo->fresh());
$this->assertSame(1, Booking::query()->count());
$this->assertSame(Booking::query()->sole()->id, $fewo->blockedPeriods()->where('source', 'channel')->sole()->linked_booking_id);
}
/** T07 – change after booking: dates, price, payment plan, calendar and portal tasks follow; the history keeps it. */
public function test_t07_change_of_a_booking_updates_price_payment_calendar_and_portals(): void
{
$booking = $this->confirmedOwnBooking();
$before = $booking->total;
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-12', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Phone->value, 'reason' => 'Gast verlängert um 2 Nächte'])
->assertNotified('Änderung gespeichert');
$booking->refresh();
$this->assertSame('2026-11-12', $booking->departure->toDateString());
$this->assertGreaterThan($before, $booking->total);
$change = $booking->changes()->sole();
$this->assertSame([ChangeStatus::Applied, ChangeBasis::Phone, 'guest'], [$change->status, $change->basis, $change->requested_by]);
$this->assertStringContainsString('Neu belegt: 10.11.–12.11.2026', implode(' ', $change->consequences['calendar']));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-11-12')->exists(), 'portal task for the new dates');
$this->assertSame('Gast verlängert um 2 Nächte', $booking->events()->where('type', 'change')->value('reason'));
}
/** T08 – cancellation: the right way for own and for portal bookings, with costs, refund and portal task. */
public function test_t08_cancellation_takes_the_right_way(): void
{
$own = $this->confirmedOwnBooking();
app(RecordPayment::class)->handle($own, 10000, CarbonImmutable::today(), PaymentMethod::Transfer);
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Krankheit', 'notify' => false, 'costs_task' => true])
->assertNotified('Buchung storniert');
$own->refresh();
$this->assertSame(BookingStatus::Cancelled, $own->status);
$this->assertSame(['guest', 'Krankheit', 'Ingrid'], [$own->cancellation->initiated_by, $own->cancellation->reason, $own->cancellation->recorded_by]);
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::CancellationFee)->exists());
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::RefundCheck)->exists());
$this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-STORNO1");
$portal = Booking::query()->where('portal_reference', 'HA-STORNO1')->sole();
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Gast storniert über FeWo-direkt'])
->assertNotified('Stornierung im Portal veranlassen');
$this->assertSame(BookingStatus::Confirmed, $portal->fresh()->status, 'stays booked until the portal confirms');
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])
->callAction('confirmPortalCancellation', ['initiated_by' => 'guest', 'effective' => true])
->assertNotified('Buchung storniert');
$this->assertSame(BookingStatus::Cancelled, $portal->fresh()->status);
$request = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-28'), CarbonImmutable::parse('2026-12-01'), 2), ['first_name' => 'Ina', 'last_name' => 'Anfrage', 'email' => 'ina@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $request->getRouteKey()])
->callAction('end', ['reason' => 'Hund nicht erlaubt', 'notify' => false])
->assertNotified('Vorgang beendet');
$this->assertSame(BookingStatus::Declined, $request->fresh()->status);
$this->assertNull($request->fresh()->cancellation, 'a request without booking is no cancellation');
}
/** T09 – family visit: no rent, guests, services and tourist tax; no contract, no reminders, no review. */
public function test_t09_family_visit(): void
{
$this->property->update(['tourist_tax_rate' => 250]);
$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, 'tourist_tax_note' => 'Enkelkind unter 6 Jahren befreit',
'items' => [['extra_id' => $linen->id, 'quantity' => 3]]])
->call('create')->assertHasNoFormErrors();
$visit = Booking::query()->sole();
$this->assertSame([CaseType::A6, InternalKind::PrivateStay, BookingStatus::Confirmed], [$visit->case_type, $visit->internal_kind, $visit->status]);
$this->assertSame(3 * 1800 + 2 * 5 * 250, $visit->total);
$this->assertContains('tourist_tax', array_column($visit->quote['lines'], 'type'));
$this->assertSame(Responsibility::Nobody, $visit->process()->documents());
$this->assertFalse($visit->wantsPaymentTasks());
$this->assertNull($visit->contract_path);
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('starts_on', '2026-11-14')->exists(), 'portals are blocked');
$this->assertSame(DocumentKind::StayConfirmation, DocumentKind::forCase($visit));
$this->travelTo(CarbonImmutable::parse('2026-11-21'));
app(SendBookingReminders::class)->handle();
app(RequestReviews::class)->handle();
Mail::assertNotSent(ReviewRequest::class);
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->count());
}
/** T10 – maintenance block: no guest, contract or payment; extended and lifted with the portals following. */
public function test_t10_maintenance_block_extended_and_lifted(): void
{
$this->get(route('filament.admin.resources.bookings.create', ['kind' => 'block', 'von' => '2026-11-20', 'bis' => '2026-11-23']))->assertOk();
Livewire::withQueryParams(['kind' => 'block', 'von' => '2026-11-20', 'bis' => '2026-11-23'])->test(CreateBooking::class)
->assertSet('data.kind', 'block')->assertSet('data.arrival', '2026-11-20')
->fillForm(['kind' => BookingForm::BLOCK, 'occasion' => 'Malerarbeiten im Bad', 'property_id' => $this->property->id, 'arrival' => '2026-11-20', 'departure' => '2026-11-23'])
->call('create')->assertHasNoFormErrors();
$block = Booking::query()->sole();
$this->assertSame([InternalKind::Block, null, null, null], [$block->internal_kind, $block->guest_id, $block->total, $block->contract_path]);
Livewire::test(ViewBooking::class, ['record' => $block->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-20', 'departure' => '2026-11-25', 'reason' => 'Trocknung dauert länger'])
->assertNotified('Änderung gespeichert');
$this->assertSame('2026-11-25', $block->fresh()->departure->toDateString());
$this->assertSame(ChangeBasis::NotNeeded, $block->changes()->sole()->basis);
Livewire::test(ViewBooking::class, ['record' => $block->getRouteKey()])
->callAction('end', ['reason' => 'Arbeiten abgeschlossen'])
->assertNotified('Sperre aufgehoben');
$block->refresh();
$this->assertSame(BookingStatus::Cancelled, $block->status);
$this->assertNull($block->cancellation, 'lifting a block is no cancellation');
$this->assertSame('Sperre aufgehoben', $block->events()->where('type', 'status')->reorder()->orderByDesc('id')->value('summary'));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->where('action', 'unblock')->exists(), 'portals are released');
Mail::assertNotSent(BookingConfirmed::class);
Mail::assertNotSent(BookingCancelled::class);
}
/** T11 – external payments (R09): portal total, payouts, commission and open amounts kept apart. */
public function test_t11_external_payments_of_reference_case_r09(): void
{
$this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 10.07.2027\nAbreise: 17.07.2027\nBuchungsnummer: HA-R09XYZ");
$booking = Booking::query()->sole();
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::Accommodation->value, 'label' => '7 Nächte', 'amount' => '840.00'],
['kind' => AmountKind::Discount->value, 'label' => 'Rabatt', 'amount' => '-42.00'],
['kind' => AmountKind::Unexplained->value, 'label' => 'Gebühren und Steuern', 'amount' => '181.51'],
['kind' => AmountKind::Commission->value, 'label' => 'An FeWo-direkt gezahlt', 'amount' => '-84.82'],
['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69'],
['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Erwartete Auszahlung', 'amount' => '900.20', 'note' => 'zweite Ansicht'],
['kind' => AmountKind::InstallmentDue->value, 'label' => '2. Rate', 'amount' => '588.90', 'due_on' => '2027-06-10'],
],
'paid' => [['amount' => '390.61', 'paid_on' => '2026-10-20']]])
->assertNotified('Beträge gespeichert');
$money = CaseMoney::of($booking->fresh());
$this->assertSame(97951, $money->total());
$this->assertSame(0, $money->positions()['difference'], 'the positions add up to the total – nothing invented');
$this->assertSame([89469, 90020], $money->payout()['values']);
$this->assertSame(551, $money->payout()['difference']);
$this->assertNull($money->payout()['outstanding'], 'contradicting announcements are not settled by the system');
$this->assertSame(58890, $money->openAtPortal());
$this->assertSame(0, $money->openForUs());
$this->assertSame(0, $money->receivedOnAccount(), 'paid to the portal is not money on our account');
app(RecordPayment::class)->handle($booking->fresh(), 89469, CarbonImmutable::today(), PaymentMethod::Transfer, kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$money = CaseMoney::of($booking->fresh());
$this->assertSame(89469, $money->receivedOnAccount());
$this->assertSame(39061, $booking->fresh()->paidAmount(), 'the payout is not counted as a payment of the guest');
// Entering the same statements again does not double them.
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22', 'amounts' => [['kind' => AmountKind::Accommodation->value, 'label' => '7 Nächte', 'amount' => '840.00']], 'paid' => [['amount' => '390.61', 'paid_on' => '2026-10-20']]]);
$this->assertSame(7, $booking->amounts()->count());
$this->assertSame(39061, $booking->fresh()->paidAmount());
}
/** T12 – settings hierarchy: landlord, property, channel per intake and the single case. */
public function test_t12_settings_hierarchy_is_applied_and_visible(): void
{
$fewo = $this->fewo(['process_overrides' => ['inquiry' => ['processing' => 'manual'], 'booking' => ['payments' => 'portal']]]);
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'hold_hours' => 48]]);
$this->property->update(['process_overrides' => ['hold_hours' => 24]]);
$settings = app(ProcessSettings::class);
$direct = $settings->resolve($this->property->fresh(), null, IntakeKind::Inquiry);
$portalRequest = $settings->resolve($this->property->fresh(), $fewo, IntakeKind::Inquiry);
$portalBooking = $settings->resolve($this->property->fresh(), $fewo, IntakeKind::Booking);
$this->assertSame([ProcessingMode::Automatic, 'tenant'], [$direct->processing(), $direct->source(ProcessSetting::Processing)]);
$this->assertSame([24, 'property'], [$direct->holdHours(), $direct->source(ProcessSetting::HoldHours)]);
$this->assertSame([ProcessingMode::Manual, 'channel'], [$portalRequest->processing(), $portalRequest->source(ProcessSetting::Processing)]);
$this->assertSame([ProcessingMode::Automatic, 'tenant'], [$portalBooking->processing(), $portalBooking->source(ProcessSetting::Processing)], 'the booking intake inherits the default');
$this->assertSame(CaseType::A4, $portalBooking->caseType);
$case = app(CreateReservation::class)->handle($this->property->fresh(), 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, originChannel: $fewo);
$this->assertSame(ProcessingMode::Manual, $case->processingMode());
Livewire::test(ViewBooking::class, ['record' => $case->getRouteKey()])->callAction('automation', ['mode' => ProcessingMode::Automatic->value]);
$this->assertSame(ProcessingMode::Automatic, $case->fresh()->processingMode(), 'the case decision wins');
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(EffectiveSettings::class)
->assertSee('FeWo-direkt – Anfrage')->assertSee('FeWo-direkt – feste Buchung')->assertSee('Portal')->assertSee('Wohnung')
->set('bookingId', $case->id)->assertSee('für diesen Vorgang umgestellt');
}
/** T13 – test operation: every message of a whole run reaches only the test address. */
public function test_t13_test_operation_redirects_every_outgoing_message(): void
{
// A real mailer behind the gate instead of the fake of setUp().
$manager = new MailManager(app());
app()->instance('mail.manager', $manager);
Mail::swap($manager);
config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']);
// Every message that really leaves the system (after the test-operation gate), whichever mailer sent it.
$sent = [];
Event::listen(MessageSent::class, function (MessageSent $event) use (&$sent): void {
$sent[] = ['subject' => $event->message->getSubject(), 'to' => array_map(fn ($address) => $address->getAddress(), $event->sent->getEnvelope()->getRecipients())];
});
Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
app(TenantContext::class)->set(Settings::tenant()->fresh());
$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@gast.example', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('sendOffer')->arguments([]));
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Email->value, 'reason' => 'eine Nacht mehr', 'send_confirmation' => true]);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Absage', 'notify' => true, 'costs_task' => true]);
$this->assertGreaterThanOrEqual(6, count($sent), 'request, notification, offer, confirmation, change, cancellation');
foreach ($sent as $message) {
$this->assertSame(['test@example.com'], $message['to'], $message['subject']);
}
}
/** T14 – an agreed change and a change that needs the guest's consent are kept apart. */
public function test_t14_agreed_and_consent_requiring_changes_are_kept_apart(): void
{
$booking = $this->confirmedOwnBooking();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 3, 'way' => 'propose', 'requested_by' => 'landlord', 'reason' => 'Angebot: eine Nacht länger'])
->assertNotified('Vorschlag an den Gast gesendet');
$proposal = $booking->changes()->sole();
$this->assertSame(ChangeStatus::Proposed, $proposal->status);
$this->assertSame('2026-11-10', $booking->fresh()->departure->toDateString(), 'nothing changes before the guest agrees');
Mail::assertSent(ChangeProposed::class);
$this->assertSame('change_proposed', collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'change_proposed')?->key);
$this->get(URL::temporarySignedRoute('changes.show', $proposal->expires_at, ['change' => $proposal]))->assertOk()->assertSee('Änderung annehmen');
$this->post(URL::temporarySignedRoute('changes.accept', $proposal->expires_at, ['change' => $proposal]), ['agree' => '1'])->assertRedirect();
$proposal->refresh();
$this->assertSame([ChangeStatus::Applied, ChangeBasis::GuestLink], [$proposal->status, $proposal->basis]);
$this->assertNotNull($proposal->decided_at);
$this->assertSame('2026-11-11', $booking->fresh()->departure->toDateString());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Phone->value, 'reason' => 'Eine Person weniger', 'send_confirmation' => true])
->assertNotified('Änderung gespeichert');
$agreed = $booking->changes()->reorder()->orderByDesc('id')->first();
$this->assertSame(ChangeBasis::Phone, $agreed->basis);
$this->assertNull($agreed->decided_at, 'an updated confirmation is no consent of the guest');
$this->assertNotNull($agreed->confirmation_sent_at);
Mail::assertSent(BookingChanged::class, 1);
}
/** 6.3 – manual blocks become A6 cases; the calendar the portals read stays the same. */
public function test_existing_manual_blocks_become_cases_without_changing_the_portal_calendar(): void
{
$target = Channel::factory()->for($this->property)->create(['name' => 'Ziel', 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'manual', 'starts_on' => '2026-11-20', 'ends_on' => '2026-11-25', 'block_purpose' => 'maintenance', 'block_note' => 'Bad']);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'manual', 'starts_on' => '2026-12-01', 'ends_on' => '2026-12-04', 'block_purpose' => 'own_use', 'block_note' => 'Wir selbst']);
$tasksBefore = ChannelTask::query()->count();
Mail::fake(); // the two blocks above informed the landlord about their portal tasks; from here on nothing may be sent
$feed = fn (): string => preg_replace('/^DTSTAMP:.*$/m', '', app(ICalFeed::class)->build($target->fresh()));
$exportBefore = $feed();
$this->artisan('cases:adopt-blocks')->expectsOutputToContain('Vorschau – nichts geändert')->assertSuccessful();
$this->assertSame(0, Booking::query()->count());
$this->artisan('cases:adopt-blocks', ['--apply' => true])->expectsOutputToContain('übernommen 2')->assertSuccessful();
$this->artisan('cases:adopt-blocks', ['--apply' => true])->assertSuccessful();
$this->assertSame(2, Booking::query()->count(), 'a repeated run adopts nothing twice');
$this->assertSame([InternalKind::Block, InternalKind::OwnUse], Booking::query()->orderBy('arrival')->get()->pluck('internal_kind')->all());
$this->assertSame($exportBefore, $feed(), 'the portals see exactly the same calendar');
$this->assertSame($tasksBefore, ChannelTask::query()->count(), 'no portal tasks');
Mail::assertNothingSent();
}
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 $subject, string $text): void
{
app(ProcessPortalMail::class)->handle(new PortalMail(uniqid('msg-'), 'noreply@fewo-direkt.de', $subject, $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');
}
}