Files
fewo-stommer/tests/Feature/Process/BehaviourComparisonTest.php
T

405 lines
19 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\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.");
}
}