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

265 lines
13 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\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,
]);
}
}