U-D/U-E/O5: Prozess-Tester im eigenen Prozess (standardmäßig gesperrt, 15 Negativtests, statischer Wächter), Szenarien und Bericht, Kanalereignisse (API-Eingang ohne Umbau von iCal/Mail), Abschluss nach finanzieller Klärung, Löschfrist 30 Tage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 15:34:40 +01:00
1 parent c255783cec
commit 0689c0a591
68 files changed
+3350 -35

No files matched your search

@@ -0,0 +1,181 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\ConfigureChannelProcess;
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelRegistry;
use App\Channels\Events\BookingCancelledByChannel;
use App\Channels\Events\BookingChangedByChannel;
use App\Channels\Events\ChannelEventHandler;
use App\Channels\Events\IncomingBooking;
use App\Channels\Events\PaymentReported;
use App\Channels\Events\PayoutReported;
use App\Channels\Events\Provenance;
use App\Channels\Intake\IntakeDecision;
use App\Channels\Mail\PortalMail;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\IntakeKind;
use App\Enums\IntakeOutcome;
use App\Enums\PaymentKind;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Process\OutwardSuspension;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\Group;
use Tests\Support\Process\FakeApiConnector;
use Tests\TestCase;
/**
* Package U-E (K4, K10, N7): normalised channel events of a future portal interface are mapped onto the existing intake.
* A report is never a business action: no cancellation, change, refund or payment on our account by itself; and one
* booking stays one case whether it arrives by API, mail or calendar.
*/
#[Group('channel-events')]
class ChannelEventContractTest extends TestCase
{
use RefreshDatabase;
private Channel $fewo;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed(PropertySeeder::class);
Mail::fake();
$this->fewo = Channel::factory()->for(Property::sole())->create(['name' => 'FeWo-direkt', 'booking_model' => 'mixed', 'case_intake' => 'create', 'import_enabled' => false,
'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/x.ics', 'email_senders' => 'fewo-direkt.de']]);
app(ConfigureChannelProcess::class)->handle($this->fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking']);
$this->fewo->refresh();
}
public function test_an_api_booking_becomes_one_case_whatever_the_transport_and_order(): void
{
$first = $this->handle(new IncomingBooking($this->provenance('HA-API1'), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')));
$this->assertSame(IntakeOutcome::Create, $first->outcome, implode(' ', $first->reasons));
$case = Booking::query()->sole();
$this->assertSame(['a4.portal_booking', BookingStatus::Confirmed, 'HA-API1'], [$case->profile['plan']['model'], $case->status, $case->portal_reference]);
// The same event again, then the booking mail of the same booking: still one case.
$this->assertSame(IntakeOutcome::Link, $this->handle(new IncomingBooking($this->provenance('HA-API1'), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')))->outcome);
app(ProcessPortalMail::class)->handle(new PortalMail('<m1@fewo-direkt.de>', 'noreply@fewo-direkt.de', 'Neue Buchung', "Anreise: 07.11.2026\nAbreise: 10.11.2026\nBuchungsnummer: HA-API1", CarbonImmutable::now()));
$this->assertSame(1, Booking::query()->count());
}
public function test_a_mail_first_and_the_api_event_afterwards_stay_one_case(): void
{
app(ProcessPortalMail::class)->handle(new PortalMail('<m2@fewo-direkt.de>', 'noreply@fewo-direkt.de', 'Neue Buchung', "Anreise: 14.11.2026\nAbreise: 18.11.2026\nBuchungsnummer: HA-API2", CarbonImmutable::now()));
$this->assertSame(1, Booking::query()->count());
$decision = $this->handle(new IncomingBooking($this->provenance('HA-API2'), CarbonImmutable::parse('2026-11-14'), CarbonImmutable::parse('2026-11-18')));
$this->assertSame(IntakeOutcome::Link, $decision->outcome);
$this->assertSame(1, Booking::query()->count());
}
public function test_an_api_booking_without_reference_or_with_another_reference_on_the_same_nights_is_clarified(): void
{
$this->assertSame(IntakeOutcome::Clarify, $this->handle(new IncomingBooking($this->provenance(null), CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05')))->outcome);
$this->assertSame(0, Booking::query()->count());
$this->handle(new IncomingBooking($this->provenance('HA-A'), CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14')));
$this->assertSame(IntakeOutcome::Clarify, $this->handle(new IncomingBooking($this->provenance('HA-B'), CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14')))->outcome);
$this->assertSame(1, Booking::query()->count());
}
public function test_a_cancellation_report_is_a_task_and_never_a_cancellation(): void
{
$case = $this->booking('HA-C');
$decision = $this->handle(new BookingCancelledByChannel($this->provenance('HA-C', 'evt-1'), 'vom Gast im Portal'));
$this->handle(new BookingCancelledByChannel($this->provenance('HA-C', 'evt-1'), 'vom Gast im Portal'));
$case->refresh();
$this->assertSame(IntakeOutcome::CancellationSignal, $decision->outcome);
$this->assertSame(BookingStatus::Confirmed, $case->status, 'the booking stays binding');
$this->assertNull($case->cancelled_at);
$this->assertSame(1, BookingTask::query()->where('booking_id', $case->id)->where('kind', BookingTaskKind::PortalCancellationReported)->count(), 'one task, also when repeated');
$this->assertFalse($case->payments()->where('kind', PaymentKind::Refund)->exists());
$this->assertNotNull(OutwardSuspension::reason($case), 'O4: automatic messages wait');
$this->assertTrue(Booking::query()->occupying()->whereKey($case->id)->exists(), 'the calendar stays blocked');
$this->assertSame(IntakeOutcome::Clarify, $this->handle(new BookingCancelledByChannel($this->provenance('UNBEKANNT', 'evt-2')))->outcome, 'an unassigned report stops nothing');
}
public function test_a_change_report_leaves_the_booking_as_it_is(): void
{
$case = $this->booking('HA-D');
$this->handle(new BookingChangedByChannel($this->provenance('HA-D', 'evt-3'), CarbonImmutable::parse('2026-11-08'), CarbonImmutable::parse('2026-11-12'), 3));
$case->refresh();
$this->assertSame(['2026-11-07', '2026-11-10'], [$case->arrival->toDateString(), $case->departure->toDateString()]);
$this->assertTrue(BookingTask::query()->where('booking_id', $case->id)->where('kind', BookingTaskKind::PortalChangeReported)->exists());
}
public function test_portal_payments_and_payouts_are_only_stated_by_the_portal(): void
{
$case = $this->booking('HA-E');
$this->handle(new PaymentReported($this->provenance('HA-E', 'p1'), 39061, CarbonImmutable::parse('2026-10-22')));
$this->handle(new PaymentReported($this->provenance('HA-E', 'p1'), 39061, CarbonImmutable::parse('2026-10-22')));
$this->handle(new PayoutReported($this->provenance('HA-E', 'p2'), 89469, CarbonImmutable::parse('2026-11-12'), executed: true));
$case->refresh();
$this->assertSame(1, $case->payments()->where('kind', PaymentKind::GuestViaPortal)->count(), 'recorded once, "laut Portal"');
$this->assertSame(0, $case->payments()->whereIn('kind', [PaymentKind::Guest, PaymentKind::PortalPayout])->count(), 'never money on our account by a report');
$this->assertTrue($case->events()->where('type', 'evidence')->exists(), 'the payout is evidence "laut Portal"');
}
public function test_only_portals_deliver_events(): void
{
$this->expectException(InvalidArgumentException::class);
$this->handle(new PaymentReported(new Provenance(Channel::websiteOf(Property::sole()), 'api', Provenance::AUTHENTICATED, 'X', 'e', CarbonImmutable::now()), 1, CarbonImmutable::now()));
}
/** N7: a new portal interface needs only its adapter and its registry entry. */
public function test_a_new_api_adapter_uses_the_same_intake(): void
{
config(['channels.connectors' => [...config('channels.connectors'), FakeApiConnector::class]]);
Http::fake(['api.portal.example/*' => Http::response(['bookings' => [['reference' => 'HA-N7', 'arrival' => '2026-11-21', 'departure' => '2026-11-24', 'guests' => 2, 'paid' => 10000, 'paid_on' => '2026-10-22']]])]);
$this->assertArrayHasKey('fake_api', app(ChannelRegistry::class)->connectors());
foreach (app(FakeApiConnector::class)->fetchEvents($this->fewo, null) as $event) {
$this->handle($event);
}
foreach (app(FakeApiConnector::class)->fetchEvents($this->fewo, null) as $event) {
$this->handle($event);
}
$case = Booking::query()->sole();
$this->assertSame(['HA-N7', 'a4.portal_booking'], [$case->portal_reference, $case->profile['plan']['model']]);
$this->assertSame(1, $case->payments()->where('kind', PaymentKind::GuestViaPortal)->count());
}
private function booking(string $reference): Booking
{
$this->handle(new IncomingBooking($this->provenance($reference), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')));
return Booking::query()->where('portal_reference', $reference)->sole();
}
private function provenance(?string $reference, string $evidence = 'evt'): Provenance
{
return new Provenance($this->fewo, 'api', Provenance::AUTHENTICATED, $reference, $evidence.'-'.($reference ?? 'none'), CarbonImmutable::now());
}
private function handle(object $event): ?IntakeDecision
{
return app(ChannelEventHandler::class)->handle($event);
}
}
@@ -0,0 +1,46 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\AnonymizeGuests;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Support\SystemSettings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Decision O3: reports of the process tester are deleted after 30 days by the existing retention job; the period is
* part of the retention settings (System › Löschfristen).
*/
#[Group('sandbox')]
class ProcessTestRunRetentionTest extends TestCase
{
use RefreshDatabase;
public function test_reports_older_than_the_retention_period_are_deleted(): void
{
$this->travelTo(CarbonImmutable::parse('2026-10-23 10:00'));
$this->seed(PropertySeeder::class);
$channel = Channel::websiteOf(Property::sole());
$user = User::factory()->create();
$run = fn (): ProcessTestRun => ProcessTestRun::query()->create(['tenant_id' => $channel->tenant_id, 'channel_id' => $channel->id, 'user_id' => $user->id, 'intake' => 'inquiry', 'scenario' => 'complete_request', 'configuration' => [], 'inputs' => [], 'steps' => 1, 'report' => [], 'outcome' => ProcessTestRun::COMPLETED]);
$old = $run();
$this->travel(29)->days();
$recent = $run();
$this->travel(2)->days();
$this->assertSame(30, config('fewo.retention.process_test_run_days'));
$this->assertArrayHasKey('fewo.retention.process_test_run_days', SystemSettings::EDITABLE);
app(AnonymizeGuests::class)->handle();
$this->assertModelMissing($old);
$this->assertModelExists($recent);
}
}
@@ -0,0 +1,192 @@
<?php
namespace Tests\Feature\Process;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Process\Tester\ProcessSandbox;
use App\Process\Tester\SandboxSnapshot;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use RuntimeException;
use Tests\Support\Process\HostileProbe;
use Tests\TestCase;
/**
* Safety proof of the process tester (requirement T2, docs/Prozessarchitektur/Architektur/04 §7): a probe inside the
* tester process deliberately tries forbidden accesses. A passing happy path is no proof; these tests are. The
* "operational database" is a SQLite file of its own here; its hash before and after is compared.
*/
#[Group('sandbox')]
class ProcessTesterSecurityTest extends TestCase
{
use RefreshDatabase;
private Channel $website;
private User $user;
private string $operational;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
Settings::tenant()->update(['test_recipient' => 'vermieter@example.org', 'mailbox_password' => 'geheim']);
$this->website = Channel::websiteOf(Property::sole());
$this->user = User::factory()->create();
ProcessTesterTest::template();
$this->operational = storage_path('framework/testing/operational-'.getmypid().'.sqlite');
File::ensureDirectoryExists(dirname($this->operational));
@unlink($this->operational);
$pdo = new PDO('sqlite:'.$this->operational);
$pdo->exec('create table probe (id integer primary key, value text)');
$pdo->exec("insert into probe (value) values ('real')");
$pdo = null;
}
protected function tearDown(): void
{
@unlink($this->operational);
@unlink(base_path('sandbox-probe.txt'));
parent::tearDown();
}
/**
* @return array<string, array{string, ?string}>
*/
public static function forbidden(): array
{
return [
'N-DB1 other connection' => ['db_other_connection', 'database'],
'N-DB3 new connection to the real file' => ['db_new_connection', 'database'],
'N-DB3 sandbox redirected to the real file' => ['db_redirected_sandbox', 'database'],
'N-NET1 network without scripted answer' => ['network', 'network'],
'N-NET2 automation webhook' => ['webhook', 'network'],
'N-IMAP mailbox' => ['imap', 'imap'],
'N-MAIL other mailer' => ['mail_other_mailer', 'mail'],
'N-FILE storage outside the run' => ['file_outside', 'file'],
'N-CACHE other store' => ['cache_other_store', 'cache'],
];
}
#[DataProvider('forbidden')]
public function test_a_forbidden_access_is_recorded_aborts_the_run_and_changes_nothing(string $case, string $kind): void
{
$before = hash_file('sha256', $this->operational);
$run = $this->probe($case);
$this->assertSame(ProcessTestRun::ABORTED, $run->outcome, json_encode($run->report));
$this->assertSame($kind, $run->report['violations'][0]['kind'] ?? null, json_encode($run->report['violations']));
$this->assertSame($before, hash_file('sha256', $this->operational), 'the operational database file is unchanged');
$this->assertFileDoesNotExist(base_path('sandbox-probe.txt'));
$this->assertSame(0, Booking::query()->count());
}
/** N-DB2: the run's own database has no access to the operational tables at all. */
public function test_the_runs_database_does_not_contain_the_operational_tables(): void
{
$before = hash_file('sha256', $this->operational);
$run = $this->probe('db_operational_table');
$probe = collect($run->report['timeline'][0]['effects'] ?? [])->firstWhere('type', 'probe');
$this->assertSame('QueryException', $probe['outcome'] ?? null);
$this->assertSame($before, hash_file('sha256', $this->operational));
}
/** No credentials, no real configuration, no real cases inside the run; its key is its own. */
public function test_the_run_has_no_credentials_no_real_data_and_its_own_key(): void
{
Booking::factory()->for(Property::sole())->create();
$run = $this->probe('environment');
$probe = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe');
$this->assertFalse($probe['db_password_env']);
$this->assertSame(['sandbox'], $probe['connections']);
$this->assertSame(['array'], $probe['mailers']);
$this->assertNull($probe['smtp_password']);
$this->assertTrue($probe['app_key_differs']);
$this->assertSame([0, 0], [$probe['bookings'], $probe['guests']], 'no real case or guest is copied');
$snapshot = SandboxSnapshot::build($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer']);
$this->assertArrayNotHasKey('bookings', $snapshot['tables']);
$this->assertNull($snapshot['tables']['tenants'][0]['mailbox_password']);
}
/** N-SIGN: a link signed inside a run is worthless in the real application. */
public function test_a_link_signed_in_a_run_is_invalid_outside(): void
{
$run = $this->probe('signed_link');
$url = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe')['url'];
$this->assertStringContainsString('signature=', $url);
$this->assertFalse(URL::hasValidSignature(Request::create($url)));
}
/** N-TOKEN: the run command refuses to work outside a run the tester started. */
public function test_the_run_command_refuses_outside_a_prepared_run(): void
{
$this->artisan('process:sandbox-run', ['run' => '00000000-0000-0000-0000-000000000000'])->assertFailed();
}
/** N-PAR: one run per landlord at a time. */
public function test_a_second_run_of_the_same_landlord_waits(): void
{
$directory = storage_path('app/sandbox/slots');
File::ensureDirectoryExists($directory);
$lock = fopen($directory.'/tenant-'.$this->website->tenant_id.'.lock', 'c');
flock($lock, LOCK_EX | LOCK_NB);
try {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('läuft bereits');
$this->probe('none');
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
/** N-ABORT: the directory of an aborted run is removed by the next run. */
public function test_leftovers_of_aborted_runs_are_removed(): void
{
$left = storage_path('app/sandbox/runs/11111111-1111-1111-1111-111111111111');
File::ensureDirectoryExists($left);
touch($left, time() - 7200);
$this->probe('none');
$this->assertDirectoryDoesNotExist($left);
}
private function probe(string $case): ProcessTestRun
{
config(['fewo.sandbox.test_environment' => [
'FEWO_SANDBOX_PROBE' => HostileProbe::class,
'FEWO_SANDBOX_PROBE_CASE' => $case,
'FEWO_SANDBOX_PROBE_FILE' => $this->operational,
'FEWO_SANDBOX_PROBE_PARENT_KEY' => (string) config('app.key'),
'APP_ENV' => 'testing',
]]);
return app(ProcessSandbox::class)->run($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', ['arrival' => '2026-11-07', 'nights' => 3], 1, $this->user);
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace Tests\Feature\Process;
use App\Enums\IntakeKind;
use App\Filament\Resources\Channels\Pages\ChannelProcess;
use App\Filament\Resources\Channels\Pages\ChannelProcessTest;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Process\Tester\ProcessSandbox;
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\Support\Facades\Mail;
use Illuminate\Support\Facades\Process;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Package U-D: the process tester plays scenarios in a process of its own with the same business logic (T01, T02,
* T05) and leaves the real data untouched (T03).
*/
#[Group('sandbox')]
class ProcessTesterTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private User $user;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'vermieter@example.org', 'process_defaults' => ['processing' => 'automatic', 'clarification_hold_auto_minutes' => 120, 'data_request_mode' => 'automatic']]);
$this->user = User::factory()->create();
self::template();
}
public static function template(): void
{
$template = storage_path('app/sandbox/template.sqlite');
$newest = max(array_map('filemtime', glob(database_path('migrations/*.php'))));
if (! is_file($template) || filemtime($template) < $newest) {
// A fresh process, as at deployment (the migrator binds the schema of the process that runs it).
Process::path(base_path())->timeout(120)->run([PHP_BINARY, 'artisan', 'process:sandbox-template'])->throw();
}
}
public function test_a_scenario_runs_isolated_with_the_real_business_logic_and_leaves_no_trace(): void
{
Mail::fake();
$website = Channel::websiteOf($this->property);
$run = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'missing_address', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 3, $this->user);
$report = $run->report;
$this->assertNull($report['aborted'] ?? null, json_encode($report));
$this->assertSame(ProcessTestRun::COMPLETED, $run->outcome);
$this->assertCount(3, $report['timeline']);
$this->assertSame(['a1.offer', 1, 'A1'], [$report['plan']['model'], $report['plan']['version'], $report['plan']['case_type']]);
// Same logic as the real case: data request and clarification hold, later the offer.
[$request, $expired, $answer] = $report['timeline'];
$this->assertStringContainsString('reserviert', $request['situation']);
$this->assertContains('tester@sandbox.invalid', array_column($request['mails'], 'to'), 'mails are simulated and go to the test address');
$this->assertSame('Angebot gesendet', $answer['status']);
$this->assertStringContainsString('Angebot', implode(' ', array_column($answer['mails'], 'subject')));
$this->assertSame([], $report['violations']);
// Nothing reached the real data: no case, no mail.
$this->assertSame(0, Booking::query()->count());
Mail::assertNothingSent();
$this->assertDirectoryDoesNotExist(storage_path('app/sandbox/runs/'.$run->id));
}
public function test_a_run_with_the_same_snapshot_gives_the_same_report(): void
{
$website = Channel::websiteOf($this->property);
$inputs = ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2];
$first = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', $inputs, 3, $this->user);
$second = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', $inputs, 3, $this->user);
$strip = fn (array $report): array => array_map(fn (array $event): array => array_diff_key($event, ['effects' => true]), $report['timeline']);
$this->assertSame($strip($first->report), $strip($second->report));
}
public function test_the_loyalty_variant_runs_in_the_tester_only(): void
{
$website = Channel::websiteOf($this->property);
$run = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'variant' => 'loyalty'], 'returning_guest', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 3, $this->user);
$this->assertNull($run->report['aborted'] ?? null, json_encode($run->report));
$this->assertSame('loyalty', $run->report['plan']['variant']);
$timeline = $run->report['timeline'];
$lines = array_column(end($timeline)['price']['lines'], 'label');
$this->assertNotEmpty(array_filter($lines, fn (string $label): bool => str_starts_with($label, 'Stammgastrabatt')), 'the discount enters the price before it is fixed');
$this->assertNull($website->fresh()->process_overrides['inquiry']['variant'] ?? null, 'nothing was saved');
}
/** S07/S08/S13: a portal booking by mail (twice), portal amounts and a cancellation report – A4 of FeWo-direkt */
public function test_a_portal_booking_scenario_with_cancellation_report(): void
{
$fewo = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'mixed', 'status' => 'setup', 'is_active' => false, 'import_enabled' => false, 'settings' => ['import_url' => 'https://www.fewo-direkt.de/x.ics']]);
$run = app(ProcessSandbox::class)->run($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'settings' => ['guest_messages' => 'portal']], 'portal_booking', ['arrival' => '2026-11-14', 'nights' => 4, 'guests' => 2, 'portal_total' => 980, 'cancellation' => true], 6, $this->user);
$report = $run->report;
$this->assertNull($report['aborted'] ?? null, json_encode($report));
$this->assertSame(['a4.portal_booking', 'A4'], [$report['plan']['model'], $report['plan']['case_type']]);
[$mail, $repeated, , $amounts, $cancellation] = $report['timeline'];
$this->assertSame('Bestätigt', $mail['status'] ?? null, json_encode($mail));
$this->assertSame($mail['situation'], $repeated['situation'], 'the same mail twice: one case');
$this->assertStringContainsString('laut Portal', implode(' ', array_column($amounts['activities'], 'detail')));
$this->assertContains('Das Portal meldet eine Stornierung – bitte prüfen', array_column($cancellation['activities'], 'label'));
$this->assertSame('Bestätigt', $cancellation['status'], 'the report never cancels');
$this->assertSame(0, Booking::query()->count());
$this->assertFalse((bool) $fewo->fresh()->is_active, 'the real channel is unchanged');
}
/** S12/T06: a failing mail server leaves the case in a defined state */
public function test_a_mail_failure_keeps_the_case(): void
{
$run = app(ProcessSandbox::class)->run(Channel::websiteOf($this->property), IntakeKind::Inquiry, ['model' => 'a1.offer'], 'mail_failure', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 2, $this->user);
$request = $run->report['timeline'][1];
$this->assertNull($run->report['aborted'] ?? null);
// v0.11 behaviour: the offer is saved even if its mail fails (SendOffer reports it); nothing went out.
$this->assertSame('Angebot gesendet', $request['status'], 'the case is kept');
$this->assertSame([], $request['mails'], 'no mail went out');
}
/** T01/T02: from the configurator with the unsaved draft, step by step, with a readable report */
public function test_the_landlord_tests_the_unsaved_draft_step_by_step(): void
{
$this->actingAs($this->user);
$website = Channel::websiteOf($this->property);
$configurator = Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()])
->call('toggleStep', 'review.request')
->call('test');
$configurator->assertRedirect();
$this->assertFalse(session('process-tester.draft.'.$website->id.'.inquiry')['steps']['review.request']['on']);
Livewire::test(ChannelProcessTest::class, ['record' => $website->getRouteKey()])
->assertSee('Vollständige Anfrage bis zur Buchung')
->set('inputs.arrival', '2026-11-07')
->call('start')
->assertSee('Bericht')
->assertSee('Gast fragt mit allen Angaben an')
->assertSee('simuliert')
->call('next')
->assertSee('Sie senden das Angebot');
$this->assertNull($website->fresh()->process_overrides['inquiry']['steps'] ?? null, 'the draft was never saved');
$this->assertSame(2, ProcessTestRun::query()->count());
}
public function test_without_the_isolation_the_tester_is_locked(): void
{
$this->actingAs($this->user);
$template = storage_path('app/sandbox/template.sqlite');
rename($template, $template.'.off');
try {
Livewire::test(ChannelProcessTest::class, ['record' => Channel::websiteOf($this->property)->getRouteKey()])
->assertSee('auf diesem Server gesperrt')
->assertDontSee('Test starten');
} finally {
rename($template.'.off', $template);
}
}
}
@@ -0,0 +1,78 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\RecordPayment;
use App\Actions\RecordPortalAmounts;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\PaymentKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Process\CaseClosure;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Decision O5 (intended change I-007): with portal collection the commercial closing needs the financial clarification
* of the payout – received, offset, booked difference or written-off claim; a portal's report of the payout is no proof,
* a reason alone is not enough, and an open claim stays traceable as a task of its own.
*/
#[Group('module:case.settlement')]
class SettlementClarificationTest extends TestCase
{
use RefreshDatabase;
private Booking $booking;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed(PropertySeeder::class);
Mail::fake();
$portal = Channel::factory()->for(Property::sole())->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'process_overrides' => ['booking' => ['payments' => 'portal']]]);
$this->booking = Booking::factory()->for(Property::sole())->create(['status' => BookingStatus::Completed, 'intake' => 'booking', 'import_channel_id' => $portal->id, 'origin_channel_id' => $portal->id,
'arrival' => '2026-10-10', 'departure' => '2026-10-17', 'total' => 97951, 'completed_at' => now()]);
app(RecordPortalAmounts::class)->handle($this->booking->fresh(), null, [['kind' => 'payout_announced', 'amount' => 89469]], [], 'FeWo-direkt');
}
public function test_a_reason_alone_does_not_settle_an_open_payout(): void
{
$this->expectException(ReservationException::class);
CaseClosure::settle($this->booking->fresh(), 'Portal hat ausgezahlt', 'Lars');
}
public function test_an_open_claim_stays_traceable_and_the_case_stays_commercially_open(): void
{
CaseClosure::settle($this->booking->fresh(), 'Auszahlung fehlt, beim Portal nachgefragt', 'Lars', CaseClosure::CLAIM_OPEN);
$this->assertNull($this->booking->fresh()->settled_at);
$this->assertTrue(BookingTask::query()->where('booking_id', $this->booking->id)->where('kind', BookingTaskKind::OpenClaim)->where('status', BookingTaskStatus::Open)->exists());
}
public function test_a_written_off_claim_settles_with_its_clarification_on_record(): void
{
CaseClosure::settle($this->booking->fresh(), 'Kulanz, Betrag ausgebucht', 'Lars', 'written_off');
$booking = $this->booking->fresh();
$this->assertNotNull($booking->settled_at);
$this->assertSame('Forderung ausgebucht: Kulanz, Betrag ausgebucht', $booking->settled_note);
}
public function test_the_received_payout_settles_by_itself(): void
{
app(RecordPayment::class)->handle($this->booking->fresh(), 89469, CarbonImmutable::today(), kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$this->assertNotNull($this->booking->fresh()->settled_at);
}
}
@@ -0,0 +1,63 @@
<?php
namespace Tests\Feature\Process;
use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\Finder\Finder;
use Tests\TestCase;
/**
* The limit of the process tester's isolation (docs/Prozessarchitektur/Architektur/04 §3.5, requirement T2): native PHP
* calls that bypass Laravel's managers – own database connections, sockets, curl, mail(), writing files by path,
* programs, reading the environment – cannot be stopped at run time on shared hosting. They are kept out of the
* application by this static check (like MailTestModeGateTest for mail): new ways out must use the framework's
* facades, which the tester controls. Every exception is named here with its reason.
*/
#[Group('sandbox')]
class SideEffectPathsTest extends TestCase
{
/** Forbidden native calls (regular expression => what it is). */
private const FORBIDDEN = [
'/new\s+\\\\?PDO\b/' => 'own database connection',
'/->getPdo\(/' => 'raw database handle',
'/\b(fsockopen|pfsockopen|stream_socket_client|socket_create)\s*\(/' => 'socket',
'/\bcurl_[a-z_]+\s*\(/' => 'curl',
'/(?<![\w>:$])(?<!function )mail\s*\(/' => 'mail()',
'/(?<![\w>:$])(?<!function )(file_put_contents|fopen|fwrite|unlink|rename|copy|touch|mkdir)\s*\(/' => 'file by path',
'/(?<![\w>:])(exec|shell_exec|passthru|system|popen|proc_open)\s*\(/' => 'program',
'/(?<![\w>:$])env\s*\(/' => 'environment outside config/',
'/\bgetenv\s*\(/' => 'environment outside config/',
];
/** Files allowed to use a forbidden call, with the reason. */
private const ALLOWED = [
'Console/Commands/BackupDatabase.php' => 'backup of the real database; console only, never reachable in a tester run (no scheduler there)',
'Console/Commands/ProcessCheck.php' => 'writes MODULMATRIX.md (developer command)',
'Console/Commands/ProcessSandboxRun.php' => 'writes the report into the run directory',
'Console/Commands/ProcessSandboxTemplate.php' => 'builds the template file',
'Filament/Resources/Guests/Pages/ListGuests.php' => 'CSV download to php://output',
'Process/Tester/EffectLedger.php' => 'appends to the run ledger',
'Process/Tester/ProcessSandbox.php' => 'slot locks and the check of proc_open',
'Process/Tester/SandboxBootstrapper.php' => 'reads FEWO_SANDBOX_RUN and copies the template before the application starts',
'Process/Tester/SandboxSnapshot.php' => 'none expected',
];
public function test_no_native_way_around_the_framework_in_the_application(): void
{
$violations = [];
foreach (Finder::create()->files()->in(app_path())->name('*.php') as $file) {
$relative = str_replace('\\', '/', $file->getRelativePathname());
if (array_key_exists($relative, self::ALLOWED)) {
continue;
}
$code = (string) preg_replace('~//[^\n]*|/\*.*?\*/~s', '', $file->getContents());
foreach (self::FORBIDDEN as $pattern => $what) {
if (preg_match($pattern, $code, $match) === 1) {
$violations[] = "{$relative}: {$what} ({$match[0]})";
}
}
}
$this->assertSame([], $violations, 'Native calls bypass the process tester\'s isolation – use Laravel facades (DB, Http, Mail, Storage, Process).');
}
}