U-0: Bestandsaufnahme, Verhaltensreferenz v0.11 (11 Abläufe, 198 Konstellationen), Bestandsfälle, Fehlerregister

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 14:28:35 +01:00
1 parent 750c1ed1d9
commit 98df5e9e3b
19 files changed
+28855

No files matched your search

@@ -0,0 +1,404 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\AcceptOffer;
use App\Actions\ContributeCaseFacts;
use App\Actions\CreateInternalCase;
use App\Actions\CreateReservation;
use App\Actions\PrepareStays;
use App\Actions\ProcessPortalMail;
use App\Actions\RecordPayment;
use App\Actions\RecordPortalAmounts;
use App\Actions\RejectOffer;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Actions\SendOffer;
use App\Actions\SubmitBookingWish;
use App\Actions\TakeOverExternalBooking;
use App\Actions\TakeOverPortalInquiry;
use App\Channels\Mail\PortalMail;
use App\Documents\DocumentReleases;
use App\Enums\DocumentKind;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\StayRequest;
use App\Process\CaseAutomation;
use App\Process\ProcessSettings;
use App\Support\Content;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\Group;
use Tests\Support\Process\BehaviourSnapshot;
use Tests\TestCase;
/**
* Behaviour comparison old/new (docs/Prozessarchitektur/Architektur/05 §4): real case flows through the real actions
* and schedulers with a fixed clock; after every event the case is captured in the eight dimensions of
* {@see BehaviourSnapshot}. The reference was recorded on the v0.11 code (`PROCESS_BEHAVIOUR_RECORD=1`) before the
* process core was rebuilt; deviations need an entry in tests/Fixtures/process/intended.md or defects.md.
*/
#[Group('golden')]
class BehaviourComparisonTest extends TestCase
{
use RefreshDatabase;
private Property $property;
/** @var array<string, array<string, mixed>> */
private array $steps = [];
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 18:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Storage::fake('local');
Storage::fake('public');
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
config(['mail.default' => 'array', 'fewo.spam.min_seconds' => 0]);
Mail::swap(new MailManager($this->app));
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org']);
Http::preventStrayRequests();
BehaviourSnapshot::reset();
}
public function test_a1_complete_request_automatic_offer_acceptance_and_payment(): void
{
$this->automatic();
$booking = $this->request(['street' => 'Lindenallee 12', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']);
$this->capture('request', $booking);
app(AcceptOffer::class)->handle($booking->fresh(), $booking->fresh()->offer_version);
$this->capture('accepted', $booking);
app(RecordPayment::class)->handle($booking->fresh(), (int) $booking->fresh()->deposit, now());
$this->capture('deposit', $booking);
$this->travelTo($booking->fresh()->arrival->subDays(2)->setTime(9, 0));
$this->schedulers();
$this->capture('before_arrival', $booking);
$this->travelTo($booking->fresh()->departure->addDays(3)->setTime(9, 0));
$this->schedulers();
$this->capture('after_departure', $booking);
$this->assertBehaviour('a1_complete');
}
public function test_a1_missing_address_clarification_hold_data_request_and_late_answer(): void
{
$this->automatic(['clarification_hold_auto_minutes' => 120, 'data_request_mode' => 'automatic']);
$booking = $this->request([]);
$this->capture('request', $booking);
$this->travelTo(now()->addHours(2)->addMinutes(5));
$this->schedulers();
$this->capture('clarification_expired', $booking);
$this->travelTo(now()->addHours(23));
$this->schedulers();
$this->capture('first_reminder', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.street' => 'Lindenallee 12', 'guest.postal_code' => '10115', 'guest.city' => 'Berlin', 'guest.country' => 'DE'], FactSource::GuestLink);
$this->capture('answer', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.street' => 'Lindenallee 12'], FactSource::GuestLink);
$this->capture('answer_repeated', $booking);
$this->travelTo(now()->addHours(49));
$this->schedulers();
$this->capture('offer_expired', $booking);
$this->assertBehaviour('a1_missing_address');
}
public function test_a1_late_answer_when_the_dates_are_taken_meanwhile(): void
{
$this->automatic(['clarification_hold_auto_minutes' => 30, 'data_request_mode' => 'automatic']);
$booking = $this->request([]);
$this->travelTo(now()->addHour());
$this->schedulers();
$this->capture('clarification_expired', $booking);
$other = $this->request(['street' => 'Weg 1', 'postal_code' => '20095', 'city' => 'Hamburg', 'country' => 'DE'], 'zweiter@example.org');
$this->capture('other_offer', $other);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.street' => 'Lindenallee 12', 'guest.postal_code' => '10115', 'guest.city' => 'Berlin', 'guest.country' => 'DE'], FactSource::GuestLink);
$this->capture('answer_dates_taken', $booking);
$this->assertBehaviour('a1_dates_taken');
}
public function test_a1_manual_offer_and_rejection(): void
{
$booking = $this->request(['street' => 'Lindenallee 12', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']);
$this->capture('request', $booking);
app(SendOffer::class)->handle($booking->fresh());
$this->capture('offer', $booking);
app(SendOffer::class)->handle($booking->fresh());
$this->capture('offer_version_2', $booking);
app(RejectOffer::class)->handle($booking->fresh(), $booking->fresh()->offer_version);
$this->capture('rejected', $booking);
$this->assertBehaviour('a1_manual_reject');
}
public function test_a1_information_wish_and_binding_confirmation(): void
{
$this->automatic(['pre_reservation' => false]);
DocumentReleases::set(DocumentKind::Information, true, 'Test');
$booking = $this->request(['street' => 'Lindenallee 12', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']);
$this->capture('information', $booking);
app(SubmitBookingWish::class)->handle($booking->fresh(), $booking->fresh()->information_version);
$this->capture('wish', $booking);
$this->travelTo(now()->addMinutes(10));
$this->schedulers();
$this->capture('after_schedulers', $booking);
$this->assertBehaviour('a1_information');
}
public function test_a2_portal_inquiry_without_details(): void
{
$this->automatic(['clarification_hold_auto_minutes' => 60, 'data_request_mode' => 'automatic']);
$channel = $this->channel('FeWo-direkt', 'mixed');
$booking = app(TakeOverPortalInquiry::class)->handle($channel, CarbonImmutable::parse('2026-11-14'), CarbonImmutable::parse('2026-11-18'), 'HA-ANF1');
$this->capture('inquiry', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.first_name' => 'Gesa', 'guest.last_name' => 'Gast', 'guest.email' => 'gesa@example.org', 'booking.guests' => '2'], FactSource::PortalMail);
$this->capture('contact', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.street' => 'Lindenallee 12', 'guest.postal_code' => '10115', 'guest.city' => 'Berlin', 'guest.country' => 'DE'], FactSource::Email);
$this->capture('address', $booking);
$this->assertBehaviour('a2_inquiry');
}
public function test_a3_portal_booking_with_own_documents_and_payments(): void
{
$this->automatic();
$channel = $this->channel('Destination Solutions', 'portal_booking');
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $channel, CarbonImmutable::parse('2026-12-05'), CarbonImmutable::parse('2026-12-12'), ['portal_reference' => 'DS-1']);
$this->capture('booking', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.first_name' => 'Dora', 'guest.last_name' => 'Gast', 'guest.email' => 'dora@example.org', 'booking.guests' => '2'], FactSource::PortalMail);
$this->capture('guest', $booking);
app(RecordPortalAmounts::class)->handle($booking->fresh(), 98000, [], [], 'Destination Solutions');
$this->capture('price', $booking);
app(RecordPortalAmounts::class)->handle($booking->fresh(), 98000, [], [], 'Destination Solutions');
$this->capture('price_repeated', $booking);
$this->assertBehaviour('a3_booking');
}
public function test_a4_portal_booking_with_portal_payments(): void
{
$this->automatic();
$channel = $this->channel('FeWo-direkt', 'mixed', ['booking' => ['payments' => 'portal']]);
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $channel, CarbonImmutable::parse('2027-07-10'), CarbonImmutable::parse('2027-07-17'), ['portal_reference' => 'HA-A4', 'portal_total' => 97951, 'guests' => 2]);
$this->capture('booking', $booking);
app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.first_name' => 'Fiete', 'guest.last_name' => 'Gast', 'guest.email' => 'fiete@example.org'], FactSource::PortalMail);
$this->capture('guest', $booking);
app(RecordPortalAmounts::class)->handle($booking->fresh(), null, [['kind' => 'payout_announced', 'amount' => 89469]], [['amount' => 39061, 'paid_on' => '2026-10-23']], 'FeWo-direkt');
$this->capture('portal_amounts', $booking);
app(RecordPortalAmounts::class)->handle($booking->fresh(), null, [['kind' => 'payout_announced', 'amount' => 89469]], [['amount' => 39061, 'paid_on' => '2026-10-23']], 'FeWo-direkt');
$this->capture('portal_amounts_repeated', $booking);
$this->assertBehaviour('a4_booking');
}
public function test_a5_portal_booking_with_portal_documents(): void
{
$this->automatic();
$channel = $this->channel('Portal A5', 'portal_booking', ['booking' => ['payments' => 'portal', 'documents' => 'portal', 'guest_messages' => 'portal']]);
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $channel, CarbonImmutable::parse('2026-12-19'), CarbonImmutable::parse('2026-12-23'), ['portal_reference' => 'P5-1', 'portal_total' => 60000]);
$this->capture('booking', $booking);
$this->assertBehaviour('a5_booking');
}
public function test_portal_mail_booking_and_cancellation_report(): void
{
$channel = $this->channel('FeWo-direkt', 'mixed', [], ['email_senders' => 'fewo-direkt.de']);
$channel->update(['case_intake' => 'create']);
$text = "Gast: Max Mustermann\nAnreise: Sa., 7. Nov. 2026\nAbreise: Di., 10. Nov. 2026\nReisende: 2 Erwachsene\nBuchungsnummer: HA-7X3K9Q";
app(ProcessPortalMail::class)->handle(new PortalMail('<b1@fewo-direkt.de>', 'noreply@fewo-direkt.de', 'Neue Buchung: Ferienwohnung', $text, CarbonImmutable::now()));
$booking = Booking::query()->sole();
$this->capture('booking_mail', $booking);
app(ProcessPortalMail::class)->handle(new PortalMail('<b1@fewo-direkt.de>', 'noreply@fewo-direkt.de', 'Neue Buchung: Ferienwohnung', $text, CarbonImmutable::now()));
$this->capture('booking_mail_repeated', $booking);
app(ProcessPortalMail::class)->handle(new PortalMail('<c1@fewo-direkt.de>', 'noreply@fewo-direkt.de', 'Buchung storniert: HA-7X3K9Q', 'Die Buchung vom 07.11.2026 bis 10.11.2026 wurde storniert.', CarbonImmutable::now()));
$this->capture('cancellation_mail', $booking);
app(CaseAutomation::class)->advance($booking->fresh());
$this->capture('advance_after_cancellation', $booking);
$this->assertBehaviour('portal_mail_cancellation');
}
public function test_a6_own_use(): void
{
$booking = app(CreateInternalCase::class)->handle($this->property, InternalKind::PrivateStay, CarbonImmutable::parse('2026-11-20'), CarbonImmutable::parse('2026-11-23'), ['occasion' => 'Familie']);
$this->capture('internal', $booking);
$this->travelTo(CarbonImmutable::parse('2026-11-24 09:00'));
$this->schedulers();
$this->capture('after', $booking);
$this->assertBehaviour('a6_internal');
}
/**
* State matrix: intake × status × responsibilities × data × time, read only (activities, next step, situation and
* the automation's blockers) – the constellations the flows above do not reach.
*/
public function test_state_matrix(): void
{
$channels = [
'website' => null,
'a2' => $this->channel('Anfrageportal', 'inquiry'),
'a3' => $this->channel('Buchungsportal A3', 'portal_booking'),
'a4' => $this->channel('Buchungsportal A4', 'portal_booking', ['booking' => ['payments' => 'portal']]),
'a5' => $this->channel('Buchungsportal A5', 'portal_booking', ['booking' => ['payments' => 'portal', 'documents' => 'portal', 'guest_messages' => 'portal']]),
];
$statuses = ['reserved', 'offer_sent', 'confirmed', 'deposit_paid', 'paid', 'completed', 'cancelled', 'expired', 'declined'];
$guests = [
'complete' => ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE'],
'no_address' => ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'],
'none' => null,
];
$times = ['future' => ['2026-12-01', '2026-12-05'], 'past' => ['2026-10-10', '2026-10-14']];
$index = 0;
foreach ($channels as $channelKey => $channel) {
$intake = in_array($channelKey, ['website', 'a2'], true) ? 'inquiry' : 'booking';
foreach ($statuses as $status) {
if ($intake === 'booking' && in_array($status, ['reserved', 'offer_sent', 'expired', 'declined'], true)) {
continue;
}
foreach ($guests as $guestKey => $guestData) {
foreach ($times as $timeKey => [$arrival, $departure]) {
$shift = $index++ * 10;
$profile = app(ProcessSettings::class)->resolve($this->property, $channel, IntakeKind::from($intake));
$booking = Booking::factory()->for($this->property)->create([
'guest_id' => $guestData === null ? null : Guest::query()->create([...$guestData, 'email' => $guestData['email'] ? $index.$guestData['email'] : null, 'tenant_id' => $this->property->tenant_id])->id,
'status' => $status,
'intake' => $intake,
'case_type' => $profile->caseType,
'profile' => $profile->toArray(),
'import_channel_id' => $channel?->id,
'origin_channel_id' => $channel?->id,
'source' => $channel === null ? 'website' : 'channel',
'arrival' => CarbonImmutable::parse($arrival)->addDays($shift)->toDateString(),
'departure' => CarbonImmutable::parse($departure)->addDays($shift)->toDateString(),
'balance_due_on' => CarbonImmutable::parse($arrival)->addDays($shift - 28)->toDateString(),
'total' => 80000,
'deposit' => 20000,
'hold_expires_at' => in_array($status, ['reserved', 'offer_sent'], true) ? now()->addHours(24) : null,
'hold_purpose' => 'offer',
'offer_version' => in_array($status, ['offer_sent', 'confirmed', 'deposit_paid', 'paid', 'completed', 'cancelled', 'declined'], true) && $intake === 'inquiry' ? 1 : 0,
'confirmed_at' => in_array($status, ['confirmed', 'deposit_paid', 'paid', 'completed'], true) ? now() : null,
]);
$snapshot = BehaviourSnapshot::of($booking);
$this->steps["{$channelKey}.{$status}.{$guestKey}.{$timeKey}"] = array_intersect_key($snapshot, array_flip(['activities', 'next', 'situation', 'automation', 'calendar']));
}
}
}
}
$this->assertBehaviour('state_matrix');
}
/**
* @param array<string, mixed> $defaults
*/
private function automatic(array $defaults = []): void
{
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', ...$defaults]]);
}
/**
* @param array<string, string> $address
*/
private function request(array $address, string $email = 'gesa@example.org'): Booking
{
return 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' => $email, ...$address],
);
}
/**
* @param array<string, array<string, mixed>> $overrides
* @param array<string, mixed> $settings
*/
private function channel(string $name, string $model, array $overrides = [], array $settings = []): Channel
{
return Channel::factory()->for($this->property)->create([
'name' => $name,
'booking_model' => $model,
'process_overrides' => $overrides,
'settings' => ['import_url' => 'https://portal.example/'.md5($name).'.ics', ...$settings],
'import_enabled' => false,
]);
}
/** The case-related schedulers in the order of routes/console.php. */
private function schedulers(): void
{
foreach (['bookings:expire-holds', 'bookings:auto-offers', 'cases:data-requests'] as $command) {
$this->artisan($command)->assertSuccessful();
}
app(SendBookingReminders::class)->handle();
app(PrepareStays::class)->handle();
app(RequestReviews::class)->handle();
}
private function capture(string $label, Booking $booking): void
{
$this->steps[$label] = BehaviourSnapshot::of($booking);
}
private function assertBehaviour(string $flow): void
{
$path = base_path("tests/Fixtures/process/behaviour/{$flow}.json");
$json = json_encode($this->steps, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
if (env('PROCESS_BEHAVIOUR_RECORD')) {
@mkdir(dirname($path), 0777, true);
file_put_contents($path, $json);
$this->markTestIncomplete("Reference recorded: {$flow}");
}
$this->assertFileExists($path, 'No reference recorded for '.$flow);
$this->assertSame(json_decode((string) file_get_contents($path), true), json_decode($json, true), "Behaviour of {$flow} differs from the v0.11 reference.");
}
}
@@ -0,0 +1,264 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\AcceptOffer;
use App\Actions\CancelBooking;
use App\Actions\CreateInternalCase;
use App\Actions\CreateReservation;
use App\Actions\RecordPayment;
use App\Actions\RecordPortalAmounts;
use App\Actions\TakeOverExternalBooking;
use App\Actions\TakeOverPortalInquiry;
use App\Documents\RentalContract;
use App\Enums\DocumentKind;
use App\Enums\InternalKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\StayRequest;
use App\Process\Activity;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Support\CancellationCost;
use App\Support\Content;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Regression for running and finished cases (docs/Prozessarchitektur/Architektur/02 §5.3–5.4, rules R1–R6): cases
* written by the v0.11 code are kept as frozen rows (tests/Fixtures/process/ongoing/cases.json). Every release reads
* them back unchanged and must derive the same contract values (cancellation costs, deposit, balance, due dates,
* contract text), the same activities and the same automation decision – and advancing them must not touch their
* contract data. The rows are synthetic; they were recorded once with `PROCESS_ONGOING_RECORD=1`.
*/
#[Group('ongoing')]
class OngoingCaseRegressionTest extends TestCase
{
use RefreshDatabase;
/** Tables that make up a case, in insert order (no encrypted columns: case_facts stay out on purpose). */
private const TABLES = ['guests', 'bookings', 'booking_tasks', 'data_requests', 'case_amounts', 'payments', 'cancellations', 'booking_changes'];
/** Contract columns that no release and no automatic run may change (level E-V). */
private const CONTRACT_COLUMNS = ['total', 'deposit', 'quote', 'offer_terms', 'acceptance', 'deposit_due_on', 'balance_due_on', 'arrival', 'departure', 'status', 'profile'];
private const NOW = '2026-11-02 09:00';
private Property $property;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 18:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Storage::fake('local');
Storage::fake('public');
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
config(['mail.default' => 'array', 'fewo.spam.min_seconds' => 0]);
Mail::swap(new MailManager($this->app));
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org']);
Http::preventStrayRequests();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'clarification_hold_auto_minutes' => 120, 'data_request_mode' => 'automatic']]);
}
public function test_frozen_cases_keep_their_contract_values_activities_and_automation_decision(): void
{
$path = base_path('tests/Fixtures/process/ongoing/cases.json');
if (env('PROCESS_ONGOING_RECORD')) {
$this->record($path);
$this->markTestIncomplete('Ongoing cases recorded.');
}
$this->assertFileExists($path);
$cases = json_decode((string) file_get_contents($path), true);
$this->restore($cases);
$this->travelTo(CarbonImmutable::parse(self::NOW));
foreach ($cases as $label => $case) {
$booking = Booking::query()->findOrFail($case['id']);
$this->assertSame($case['expected'], $this->derive($booking), "Derived values of {$label} changed.");
$before = $this->contract($booking);
app(CaseAutomation::class)->advance($booking->fresh());
$this->assertSame($before, $this->contract($booking->fresh()), "Advancing {$label} changed its contract data.");
}
}
private function record(string $path): void
{
$address = ['street' => 'Lindenallee 12', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE'];
$cases = [];
$cases['a1_clarification'] = $this->request('2026-11-07', '2026-11-10', 'klaer@example.org', []);
$cases['a1_offer_sent'] = $this->request('2026-11-14', '2026-11-17', 'angebot@example.org', $address);
$confirmed = $this->request('2026-12-01', '2026-12-08', 'fest@example.org', $address);
app(AcceptOffer::class)->handle($confirmed->fresh(), $confirmed->fresh()->offer_version);
$cases['a1_confirmed_deposit_open'] = $confirmed;
$paid = $this->request('2026-11-18', '2026-11-21', 'bezahlt@example.org', $address);
app(AcceptOffer::class)->handle($paid->fresh(), $paid->fresh()->offer_version);
app(RecordPayment::class)->handle($paid->fresh(), (int) $paid->fresh()->deposit, now());
$cases['a1_deposit_paid'] = $paid;
$cancelled = $this->request('2026-12-10', '2026-12-13', 'storno@example.org', $address);
app(AcceptOffer::class)->handle($cancelled->fresh(), $cancelled->fresh()->offer_version);
app(CancelBooking::class)->handle($cancelled->fresh(), reason: 'Gast verhindert');
$cases['a1_cancelled'] = $cancelled;
$past = $this->request('2026-10-26', '2026-10-30', 'vorbei@example.org', $address);
app(AcceptOffer::class)->handle($past->fresh(), $past->fresh()->offer_version);
$cases['a1_stay_over'] = $past;
$fewo = $this->channel('FeWo-direkt', 'mixed', ['booking' => ['payments' => 'portal']]);
$inquiry = app(TakeOverPortalInquiry::class)->handle($fewo, CarbonImmutable::parse('2027-03-01'), CarbonImmutable::parse('2027-03-05'), 'HA-ANF');
$cases['a2_inquiry'] = $inquiry;
$ds = $this->channel('Destination Solutions', 'portal_booking');
$a3 = app(TakeOverExternalBooking::class)->handle($this->property, $ds, CarbonImmutable::parse('2027-04-01'), CarbonImmutable::parse('2027-04-08'), ['portal_reference' => 'DS-1', 'portal_total' => 98000, 'guests' => 2]);
$cases['a3_booking'] = $a3;
$a4 = app(TakeOverExternalBooking::class)->handle($this->property, $fewo, CarbonImmutable::parse('2027-07-10'), CarbonImmutable::parse('2027-07-17'), ['portal_reference' => 'HA-A4', 'portal_total' => 97951, 'guests' => 2]);
app(RecordPortalAmounts::class)->handle($a4->fresh(), null, [['kind' => 'payout_announced', 'amount' => 89469]], [['amount' => 39061, 'paid_on' => '2026-10-23']], 'FeWo-direkt');
$cases['a4_portal_payments'] = $a4;
$a5channel = $this->channel('Portal A5', 'portal_booking', ['booking' => ['payments' => 'portal', 'documents' => 'portal', 'guest_messages' => 'portal']]);
$cases['a5_booking'] = app(TakeOverExternalBooking::class)->handle($this->property, $a5channel, CarbonImmutable::parse('2027-05-01'), CarbonImmutable::parse('2027-05-04'), ['portal_reference' => 'P5-1', 'portal_total' => 60000]);
$cases['a6_private'] = app(CreateInternalCase::class)->handle($this->property, InternalKind::PrivateStay, CarbonImmutable::parse('2027-06-01'), CarbonImmutable::parse('2027-06-04'), ['occasion' => 'Familie']);
$migrated = $this->request('2026-11-24', '2026-11-27', 'alt@example.org', $address);
$migrated->forceFill(['profile' => [...(array) $migrated->fresh()->profile, 'origin' => 'migration']])->saveQuietly();
$cases['legacy_migration_offer'] = $migrated;
$this->travelTo(CarbonImmutable::parse(self::NOW));
$out = [];
foreach ($cases as $label => $booking) {
$booking = $booking->fresh();
$out[$label] = ['id' => $booking->id, 'rows' => $this->rows($booking), 'expected' => $this->derive($booking)];
}
@mkdir(dirname($path), 0777, true);
file_put_contents($path, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n");
}
/**
* @return array<string, list<array<string, mixed>>>
*/
private function rows(Booking $booking): array
{
$rows = [];
foreach (self::TABLES as $table) {
$query = DB::table($table);
$query = $table === 'bookings' ? $query->where('id', $booking->id)
: ($table === 'guests' ? $query->where('id', $booking->guest_id) : $query->where('booking_id', $booking->id));
$rows[$table] = $query->orderBy('id')->get()->map(fn (object $row): array => (array) $row)->all();
}
return $rows;
}
/**
* @param array<string, array{id: int, rows: array<string, list<array<string, mixed>>>}> $cases
*/
private function restore(array $cases): void
{
// Channels the cases point to, as they were configured when the cases were written.
$this->channel('FeWo-direkt', 'mixed', ['booking' => ['payments' => 'portal']]);
$this->channel('Destination Solutions', 'portal_booking');
$this->channel('Portal A5', 'portal_booking', ['booking' => ['payments' => 'portal', 'documents' => 'portal', 'guest_messages' => 'portal']]);
foreach (self::TABLES as $table) {
foreach ($cases as $case) {
foreach ($case['rows'][$table] as $row) {
if ($table === 'guests' && DB::table('guests')->where('id', $row['id'])->exists()) {
continue;
}
DB::table($table)->insert($row);
}
}
}
}
/**
* Everything a release must derive identically from the frozen rows.
*
* @return array<string, mixed>
*/
private function derive(Booking $booking): array
{
// As in a request of the landlord: the case's landlord is the current one (TenantConfig lays its data over config).
return app(TenantContext::class)->run($booking->property->tenant, fn (): array => $this->deriveInContext($booking));
}
/**
* @return array<string, mixed>
*/
private function deriveInContext(Booking $booking): array
{
$booking = $booking->fresh(['guest', 'property', 'payments']);
$cost = fn (string $on): ?array => $booking->arrival === null ? null : CancellationCost::calculate($booking, CarbonImmutable::parse($on));
[$view, $data] = app(RentalContract::class)->view($booking, DocumentKind::Confirmation, draft: true);
return [
'cancellation' => [
'today' => $cost(self::NOW),
'arrival_minus_40' => $cost($booking->arrival->subDays(40)->toDateString()),
'arrival_minus_10' => $cost($booking->arrival->subDays(10)->toDateString()),
],
'rent' => CancellationCost::rent($booking),
'deposit' => $booking->deposit,
'balance' => $booking->total === null ? null : max(0, $booking->total - (int) $booking->deposit),
'open_amount' => $booking->openAmount(),
'due' => [$booking->deposit_due_on?->toDateString(), $booking->balance_due_on?->toDateString()],
'contract_sha' => $booking->intake?->value === 'internal' || $booking->total === null ? null : sha1(view($view, $data)->render()),
'case_type' => $booking->process()->caseType->value,
'activities' => array_map(fn (Activity $activity): array => [$activity->key, $activity->state->value, $activity->detail, $activity->action], CaseActivities::for($booking)),
'next' => CaseActivities::next($booking)?->key,
'document_blockers' => app(CaseAutomation::class)->documentBlockers($booking),
];
}
/**
* @return array<string, mixed>
*/
private function contract(Booking $booking): array
{
return array_intersect_key($booking->getAttributes(), array_flip(self::CONTRACT_COLUMNS));
}
/**
* @param array<string, string> $address
*/
private function request(string $arrival, string $departure, string $email, array $address): Booking
{
return app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email, ...$address]);
}
/**
* @param array<string, array<string, mixed>> $overrides
*/
private function channel(string $name, string $model, array $overrides = []): Channel
{
return Channel::query()->where('name', $name)->first() ?? Channel::factory()->for($this->property)->create([
'name' => $name, 'booking_model' => $model, 'process_overrides' => $overrides,
'settings' => ['import_url' => 'https://portal.example/'.md5($name).'.ics'], 'import_enabled' => false,
]);
}
}