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

+31 -1
View File
@@ -3,8 +3,10 @@
namespace App\Process;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\CaseMoney;
@@ -21,6 +23,16 @@
*/
final class CaseClosure
{
/** Kinds of financial clarification that allow settling an open portal payout (decision O5). */
public const PAYOUT_CLARIFICATIONS = [
'offset' => 'Verrechnung dokumentiert',
'difference_booked' => 'Differenz geklärt und verbucht',
'written_off' => 'Forderung ausgebucht',
self::CLAIM_OPEN => 'Als offene Forderung weiterführen',
];
public const CLAIM_OPEN = 'open_claim';
public const AUTOMATIC = 'automatisch';
/**
@@ -92,8 +104,26 @@ public static function refresh(Booking $booking): void
* The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial
* tasks are closed with the same note. The reason is required and kept.
*/
public static function settle(Booking $booking, string $note, string $by): void
public static function settle(Booking $booking, string $note, string $by, ?string $clarification = null): void
{
// Decision O5: with portal collection, an open or deviating payout is settled only after its financial
// clarification – a reason alone is not enough, and a portal's report of a payout is no proof of the receipt.
$payoutPoints = $booking->status !== BookingStatus::Cancelled && CaseMoney::of($booking)->collector() === Responsibility::Portal
? self::portalMoney($booking, CaseMoney::of($booking)) : [];
if ($payoutPoints !== [] && ! array_key_exists((string) $clarification, self::PAYOUT_CLARIFICATIONS)) {
throw new ReservationException('Bei Inkasso durch das Portal ist der kaufmännische Abschluss erst nach finanzieller Klärung möglich: Auszahlung eingegangen, Verrechnung, verbuchte Differenz oder ausgebuchte Forderung. Offen: '.implode(' ', $payoutPoints));
}
if ($clarification === self::CLAIM_OPEN) {
// The claim stays traceable: an open task of its own, the case stays commercially open.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::OpenClaim, 'status' => BookingTaskStatus::Open], ['tenant_id' => $booking->tenant_id, 'due_on' => today()->addDays(14), 'note' => mb_substr($note, 0, 1000)]);
CaseLog::record($booking, 'settled', 'Als offene Forderung weitergeführt', reason: $note, data: ['open_points' => $payoutPoints, 'clarification' => $clarification], actor: $by);
return;
}
if ($clarification !== null && isset(self::PAYOUT_CLARIFICATIONS[$clarification])) {
$note = self::PAYOUT_CLARIFICATIONS[$clarification].': '.$note;
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
if ($task->kind->isCommercial()) {
$task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note);
+2
View File
@@ -69,6 +69,8 @@ public static function derive(ProcessProfile $profile): self
public static function freeze(ProcessProfile $profile, array $configuration, bool $sandbox = false): self
{
$catalogue = app(ProcessCatalogue::class);
// Inside a process tester run (its own process, SandboxBootstrapper) tester-only variants are allowed.
$sandbox = $sandbox || filled(config('sandbox.run'));
$chosen = (string) ($configuration['model'] ?? '');
if ($chosen === '') {
return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', (array) ($configuration['steps'] ?? []), self::DERIVED);
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Process\Tester;
/**
* The record of a tester run: every simulated effect and every violation, appended line by line to a file in the
* run's directory – it survives exceptions, and what an action swallowed is still there.
*/
final class EffectLedger
{
private static ?string $path = null;
public static function open(string $path): void
{
self::$path = $path;
}
public static function isOpen(): bool
{
return self::$path !== null;
}
/**
* @param array<string, mixed> $data
*/
public static function record(string $type, array $data = []): void
{
if (self::$path === null) {
return;
}
file_put_contents(self::$path, json_encode(['type' => $type, ...$data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n", FILE_APPEND | LOCK_EX);
}
/**
* @return list<array<string, mixed>>
*/
public static function entries(): array
{
if (self::$path === null || ! is_file(self::$path)) {
return [];
}
return array_values(array_map(fn (string $line): array => (array) json_decode($line, true), array_filter(explode("\n", (string) file_get_contents(self::$path)))));
}
public static function violations(): array
{
return array_values(array_filter(self::entries(), fn (array $entry): bool => ($entry['type'] ?? null) === 'violation'));
}
}
+199
View File
@@ -0,0 +1,199 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use RuntimeException;
/**
* The process tester seen from the landlord's request (docs/Prozessarchitektur/Architektur/04 §3.2): checks that the
* isolation can be established on this server, prepares a run (read-only snapshot, run directory), starts the run in a
* process of its own – which knows neither the real database nor any real service – waits for its report, stores the
* report and removes the run's directory. The landlord's request never switches into sandbox mode itself.
*/
final class ProcessSandbox
{
/** At most this many runs at the same time on the server (one per landlord). */
public const SLOTS = 3;
public const TIMEOUT_SECONDS = 30;
/**
* What keeps the tester from running safely here (empty = it may run). Checked in the request that would start it.
*
* @return list<string>
*/
public static function requirements(): array
{
$missing = [];
if (! extension_loaded('pdo_sqlite')) {
$missing[] = 'Die PHP-Erweiterung pdo_sqlite fehlt (eigene Testdatenbank je Lauf).';
}
if (! is_file(storage_path('app/sandbox/template.sqlite'))) {
$missing[] = 'Die Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).';
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
if (! function_exists('proc_open') || in_array('proc_open', $disabled, true)) {
$missing[] = 'Eigene Prozesse lassen sich nicht starten (proc_open gesperrt) – ohne eigenen Prozess ist keine sichere Trennung möglich.';
}
if (str_contains(str_replace(DIRECTORY_SEPARATOR, '/', self::php()), '/') && ! is_file(self::php())) {
$missing[] = 'Das PHP-Programm für den Testlauf wurde nicht gefunden.';
}
return $missing;
}
/**
* Plays a scenario with the (possibly unsaved) draft of a channel's process and returns the stored report.
*
* @param array<string, mixed> $draft
* @param array<string, mixed> $inputs
*/
public function run(Channel $channel, IntakeKind $intake, array $draft, string $scenario, array $inputs, int $steps, User $user): ProcessTestRun
{
if (($missing = self::requirements()) !== []) {
throw new RuntimeException('Der Prozess-Tester ist auf diesem Server gesperrt: '.implode(' ', $missing));
}
if (ScenarioCatalogue::find($scenario) === null) {
throw new RuntimeException('Unbekanntes Szenario.');
}
if (($problems = app(ChannelProcessConfiguration::class)->problems($channel, $intake, $draft, sandbox: true)) !== []) {
throw new RuntimeException('Die Konfiguration ist nicht zulässig: '.implode(' ', $problems));
}
self::prune();
$locks = $this->slot($channel->tenant_id);
$run = (string) Str::uuid();
$directory = SandboxBootstrapper::directory($run);
try {
File::ensureDirectoryExists($directory.'/files', 0700);
$input = [
'snapshot' => SandboxSnapshot::build($channel, $intake, $draft),
'scenario' => $scenario,
'inputs' => $inputs,
'steps' => $steps,
'start' => now()->startOfMinute()->toIso8601String(),
];
File::put($directory.'/input.json', (string) json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$result = Process::path(base_path())
->timeout(self::TIMEOUT_SECONDS)
->env([SandboxBootstrapper::ENV => $run, ...self::childEnvironment(), ...(app()->environment('testing') ? (array) config('fewo.sandbox.test_environment', []) : [])])
->run([self::php(), 'artisan', 'process:sandbox-run', $run, '--no-interaction']);
$report = is_file($directory.'/report.json') ? (array) json_decode((string) File::get($directory.'/report.json'), true) : [];
if ($report === []) {
$report = ['aborted' => 'Der Testlauf hat keinen Bericht geliefert'.($result->successful() ? '.' : ': '.mb_substr(trim($result->errorOutput() ?: $result->output()), 0, 300)), 'timeline' => [], 'violations' => []];
}
return ProcessTestRun::query()->create([
'tenant_id' => $channel->tenant_id,
'channel_id' => $channel->id,
'user_id' => $user->id,
'intake' => $intake->value,
'scenario' => $scenario,
'configuration' => $draft,
'inputs' => $inputs,
'steps' => $steps,
'report' => $report,
'outcome' => filled($report['aborted'] ?? null) ? ProcessTestRun::ABORTED : ProcessTestRun::COMPLETED,
'release' => self::release(),
]);
} finally {
File::deleteDirectory($directory);
foreach ($locks as $lock) {
flock($lock, LOCK_UN);
fclose($lock);
}
}
}
/**
* Removes directories of runs that ended abnormally (older than an hour).
*/
public static function prune(): void
{
foreach (glob(storage_path('app/sandbox/runs/*'), GLOB_ONLYDIR) ?: [] as $directory) {
if (filemtime($directory) < time() - 3600) {
File::deleteDirectory($directory);
}
}
}
/**
* The release the report belongs to.
*/
public static function release(): ?string
{
// Releases on Strato live in releases/<timestamp>-<commit> (pipeline-manager, scripts/deploy.sh).
$release = basename(base_path());
return preg_match('/^\d{14}-[0-9a-f]{7,40}$/', $release) === 1 ? $release : null;
}
/**
* The PHP command line program for the run (Strato: php-cli next to the web PHP).
*/
public static function php(): string
{
$configured = (string) config('fewo.sandbox.php', '');
if ($configured !== '') {
return $configured;
}
return PHP_SAPI === 'cli' ? PHP_BINARY : (is_file('/opt/RZphp84/bin/php-cli') ? '/opt/RZphp84/bin/php-cli' : 'php');
}
/**
* Environment of the run's process: what Laravel needs to boot – never database, mail or service credentials (the
* run's configuration replaces them anyway, this keeps them out of its environment, too).
*
* @return array<string, string|false>
*/
private static function childEnvironment(): array
{
$blank = [];
foreach (array_keys(getenv()) as $key) {
if (preg_match('/^(DB_|MAIL_|REDIS_|AWS_|MAILBOX_|FEWO_MAILBOX|OPENAI|ANTHROPIC|OPENROUTER|N8N_|PIPELINE_)/', (string) $key) === 1) {
$blank[$key] = false;
}
}
return $blank;
}
/**
* One run per landlord and at most SLOTS on the server, as file locks (they end with the process).
*
* @return list<resource> the held locks (landlord, slot)
*/
private function slot(int $tenant): array
{
$directory = storage_path('app/sandbox/slots');
File::ensureDirectoryExists($directory, 0700);
$tenantLock = fopen($directory.'/tenant-'.$tenant.'.lock', 'c');
if ($tenantLock === false || ! flock($tenantLock, LOCK_EX | LOCK_NB)) {
throw new RuntimeException('Für diesen Vermieter läuft bereits ein Test. Bitte einen Moment warten.');
}
for ($index = 1; $index <= self::SLOTS; $index++) {
$slot = fopen($directory.'/slot-'.$index.'.lock', 'c');
if ($slot !== false && flock($slot, LOCK_EX | LOCK_NB)) {
return [$tenantLock, $slot];
}
if ($slot !== false) {
fclose($slot);
}
}
fclose($tenantLock);
throw new RuntimeException('Der Prozess-Tester ist gerade belegt. Bitte gleich noch einmal versuchen.');
}
}
+207
View File
@@ -0,0 +1,207 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Process\CaseActivities;
use App\Process\CaseContext;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use App\Process\ProcessProfile;
use App\Process\Tester\Scenarios\Scenario;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Event;
use Symfony\Component\Mime\Email;
use Throwable;
/**
* Plays a scenario inside the tester process (docs/Prozessarchitektur/Architektur/04 §2): seeds the run's own database
* from the snapshot, then triggers the scenario's events through the real entry points and reads the case's course
* after each one with the same method the case page uses. Contains no business rules of its own.
*/
final class ProcessSandboxDriver
{
public const MAX_EVENTS = 60;
public const MAX_SECONDS = 20;
private int $mailsSeen = 0;
private int $ledgerSeen = 0;
/** @var list<Email> every mail of the run (simulated: the only mailer is `array`) */
private array $sent = [];
/**
* @param array<string, mixed> $input input.json of the run
* @return array<string, mixed> the report
*/
public function run(array $input): array
{
$this->assertSandbox();
$started = microtime(true);
// Mails are collected when they are sent: the transport is rebuilt whenever the landlord context changes.
Event::listen(MessageSent::class, function (MessageSent $event): void {
$this->sent[] = $event->message;
EffectLedger::record('mail', ['subject' => (string) $event->message->getSubject()]);
});
SandboxSnapshot::seed($input['snapshot']);
Date::setTestNow(CarbonImmutable::parse((string) $input['start']));
$tenant = Tenant::query()->findOrFail($input['snapshot']['tenant_id']);
$channel = Channel::withoutGlobalScopes()->findOrFail($input['snapshot']['channel_id']);
$intake = IntakeKind::from((string) $input['snapshot']['intake']);
$class = ScenarioCatalogue::find((string) $input['scenario']) ?? throw new \RuntimeException('Unbekanntes Szenario.');
/** @var Scenario $scenario */
$scenario = new $class;
return app(TenantContext::class)->run($tenant, function () use ($input, $channel, $intake, $scenario, $started): array {
$property = Property::query()->findOrFail($channel->property_id);
$context = new SandboxContext($channel, $intake, $property, (array) $input['inputs']);
$events = array_slice($scenario->events($context->inputs), 0, min(self::MAX_EVENTS, max(1, (int) $input['steps'])));
$timeline = [];
$aborted = null;
if (filled(config('sandbox.probe'))) {
// Negative tests only: a probe tries forbidden accesses before the scenario.
rescue(fn () => app((string) config('sandbox.probe'))->handle($context), report: false);
}
foreach ($events as $event) {
$error = null;
try {
($event->run)($context);
} catch (Throwable $exception) {
$error = class_basename($exception).': '.$exception->getMessage();
}
$timeline[] = ['label' => $event->label, 'at' => now()->format('d.m.Y H:i'), 'error' => $error, ...$this->capture($context)];
if (EffectLedger::violations() !== []) {
$aborted = 'Unzulässiger Zugriff – Lauf abgebrochen.';
break;
}
if (microtime(true) - $started > self::MAX_SECONDS) {
$aborted = 'Laufzeitgrenze erreicht – Lauf abgebrochen.';
break;
}
}
$booking = $context->booking?->fresh();
return [
'scenario' => ['key' => $scenario::key(), 'label' => $scenario::label(), 'inputs' => $context->inputs, 'available_events' => count($scenario->events($context->inputs))],
'plan' => $booking === null ? null : $this->plan($booking),
'timeline' => $timeline,
'result' => $booking === null ? null : ['status' => $booking->status->getLabel(), 'situation' => CaseActivities::situation($booking), 'next' => CaseActivities::next($booking)?->label],
'violations' => EffectLedger::violations(),
'aborted' => $aborted ?? (EffectLedger::violations() !== [] ? 'Unzulässiger Zugriff – Lauf abgebrochen.' : null),
];
});
}
/**
* Refuses to run unless the process really is a sandbox (defence in depth behind SandboxBootstrapper).
*/
private function assertSandbox(): void
{
$connections = array_keys((array) config('database.connections'));
$mailers = array_keys((array) config('mail.mailers'));
if (config('database.default') !== 'sandbox' || $connections !== ['sandbox'] || $mailers !== ['array'] || config('cache.default') !== 'array' || blank(config('sandbox.run'))) {
throw new \RuntimeException('Sicherheitsprüfung des Prozess-Testers fehlgeschlagen: der Prozess ist nicht isoliert ('.json_encode(['db' => config('database.default'), 'connections' => $connections, 'mailers' => $mailers, 'cache' => config('cache.default')]).').');
}
}
/**
* @return array<string, mixed>
*/
private function plan(Booking $booking): array
{
$plan = ProcessPlan::of($booking);
$profile = $booking->process();
return [
'model' => $plan->model,
'label' => $plan->modelDefinition()::label(),
'version' => $plan->modelVersion,
'variant' => $plan->variant,
'modules' => $plan->modules,
'case_type' => strtoupper($profile->caseType->value),
'configuration' => collect(ProcessSetting::cases())->map(fn ($setting): array => ['question' => $setting->question(), 'value' => $setting->describe($profile->value($setting)), 'source' => ProcessProfile::sourceLabel($profile->source($setting))])->all(),
];
}
/**
* The case after one event: its course, the skipped steps, the simulated mails and effects.
*
* @return array<string, mixed>
*/
private function capture(SandboxContext $context): array
{
$booking = $context->booking?->fresh();
$ledger = EffectLedger::entries();
$effects = array_slice($ledger, $this->ledgerSeen);
$this->ledgerSeen = count($ledger);
if ($booking === null) {
return ['activities' => [], 'skipped' => [], 'mails' => $this->mails(), 'effects' => $effects];
}
$caseContext = CaseContext::of($booking);
$catalogue = app(ProcessCatalogue::class);
$skipped = [];
foreach ($caseContext->plan->moduleKeys() as $key) {
if (! $catalogue->hasModule($key)) {
continue;
}
$module = $catalogue->module($key);
$reason = match (true) {
! $caseContext->plan->enabled($key) => 'übersprungen (Konfiguration)',
! $module->applies($caseContext) => 'trifft hier nicht zu',
default => null,
};
if ($reason !== null) {
$skipped[] = ['label' => $module::definition()->label, 'reason' => $reason];
}
}
return [
'status' => $booking->status->getLabel(),
'situation' => CaseActivities::situation($booking),
'activities' => array_map(fn ($activity): array => ['label' => $activity->label, 'state' => $activity->state->getLabel(), 'state_key' => $activity->state->value, 'detail' => $activity->detail], CaseActivities::for($booking)),
'skipped' => $skipped,
'calendar' => ['occupying' => Booking::query()->occupying()->whereKey($booking->id)->exists(), 'hold_until' => $booking->isHoldActive() ? $booking->hold_expires_at->format('d.m.Y H:i') : null],
'price' => ['total' => $booking->total, 'lines' => array_map(fn (array $line): array => ['label' => $line['label'] ?? '', 'amount' => $line['amount'] ?? 0], (array) ($booking->quote['lines'] ?? []))],
'mails' => $this->mails(),
'effects' => $effects,
];
}
/**
* Mails sent since the last capture – simulated, never delivered. Links are shown as text only.
*
* @return list<array{subject: string, to: string, excerpt: string}>
*/
private function mails(): array
{
$new = array_slice($this->sent, $this->mailsSeen);
$this->mailsSeen = count($this->sent);
return array_values(array_map(function (Email $email): array {
$text = trim(preg_replace('/\s+/', ' ', strip_tags((string) ($email->getTextBody() ?? $email->getHtmlBody() ?? ''))) ?? '');
return [
'subject' => (string) $email->getSubject(),
'to' => implode(', ', array_map(fn ($address): string => $address->getAddress(), $email->getTo())),
'excerpt' => mb_substr((string) preg_replace('~https?://\S+~', '[Link]', $text), 0, 400),
];
}, $new));
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Process\Tester;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Monolog\Handler\NullHandler;
use RuntimeException;
/**
* Turns the process that runs a tester scenario into a sandbox before anything is resolved (requirement T2,
* docs/Prozessarchitektur/Architektur/04 §3.3). Called right after the configuration is loaded and only when the
* process was started for a run (environment FEWO_SANDBOX_RUN, set by ProcessSandbox for its child process).
*
* Default deny: the configuration is replaced, not amended – the only database is the run's own SQLite file, the only
* mailer `array`, the only cache store `array`, the queue `sync`, every disk lies in the run's directory, logging goes
* to the run's log, all secrets are blanked and the application key is a fresh one per run (links and encrypted values
* of a run are worthless outside it). Whatever is not configured does not exist in this process.
*/
final class SandboxBootstrapper
{
public const ENV = 'FEWO_SANDBOX_RUN';
public static function active(): bool
{
return filled(getenv(self::ENV) ?: null);
}
public static function directory(string $run): string
{
if (preg_match('/^[a-f0-9-]{36}$/', $run) !== 1) {
throw new RuntimeException('Ungültige Laufkennung.');
}
return storage_path('app/sandbox/runs/'.$run);
}
public static function configure(Application $app): void
{
$run = (string) getenv(self::ENV);
$directory = self::directory($run);
if (! is_dir($directory) || ! is_file($directory.'/input.json')) {
throw new RuntimeException('Prozess-Tester: Laufverzeichnis fehlt.');
}
$config = $app['config'];
// The run's own database: a copy of the migrated, empty template made at deployment (process:sandbox-template).
$template = storage_path('app/sandbox/template.sqlite');
if (! is_file($directory.'/db.sqlite')) {
if (! is_file($template) || ! copy($template, $directory.'/db.sqlite')) {
throw new RuntimeException('Prozess-Tester: Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).');
}
}
$config->set('database.default', 'sandbox');
$config->set('database.connections', ['sandbox' => [
'driver' => 'sqlite',
'database' => $directory.'/db.sqlite',
'prefix' => '',
'foreign_key_constraints' => true,
]]);
$config->set('database.redis', []);
$config->set('mail.default', 'array');
$config->set('mail.mailers', ['array' => ['transport' => 'array']]);
$config->set('mail.from', ['address' => 'tester@sandbox.invalid', 'name' => 'Prozess-Tester']);
$config->set('fewo.mail_redirect_to', null);
$config->set('cache.default', 'array');
$config->set('cache.stores', ['array' => ['driver' => 'array', 'serialize' => false]]);
$config->set('session.driver', 'array');
$config->set('queue.default', 'sync');
$config->set('queue.connections', ['sync' => ['driver' => 'sync']]);
$config->set('queue.failed', ['driver' => 'null']);
$files = $directory.'/files';
$config->set('filesystems.default', 'local');
$config->set('filesystems.disks', [
'local' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true],
'private' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true],
'public' => ['driver' => 'local', 'root' => $files.'/public', 'throw' => true],
'media' => ['driver' => 'local', 'root' => $files.'/media', 'throw' => true],
]);
$config->set('logging.default', 'sandbox');
$config->set('logging.channels', [
'sandbox' => ['driver' => 'single', 'path' => $directory.'/log.txt', 'level' => 'debug'],
'null' => ['driver' => 'monolog', 'handler' => NullHandler::class],
'emergency' => ['path' => $directory.'/log.txt'],
]);
$config->set('app.key', 'base64:'.base64_encode(random_bytes(32)));
$config->set('app.previous_keys', []);
// Secrets and outside services: blank. The scripted answers of the scenario replace them.
foreach (['services', 'fewo.mailbox', 'fewo.automation', 'fewo.llm'] as $key) {
if (is_array($config->get($key))) {
$config->set($key, array_map(fn (mixed $value): mixed => is_array($value) ? [] : null, (array) $config->get($key)));
}
}
$config->set('sandbox', ['run' => $run, 'directory' => $directory, 'probe' => self::probe($app)]);
// Registered after every framework provider, so its bindings replace the managers before anything resolves them.
$config->set('app.providers', [...($config->get('app.providers') ?? ServiceProvider::defaultProviders()->toArray()), SandboxServiceProvider::class]);
}
/**
* A probe that deliberately tries forbidden accesses – only for the negative tests of the test suite.
*/
private static function probe(Application $app): ?string
{
$probe = getenv('FEWO_SANDBOX_PROBE') ?: null;
return $probe !== null && $app->environment('testing') && class_exists($probe) ? $probe : null;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Process\Tester;
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
/**
* The connectors of a tester run: none reaches a portal. A scenario delivers portal data as events of its own.
*/
final class SandboxChannelRegistry extends ChannelRegistry
{
public function connectors(): array
{
return [];
}
public function resolve(string $key): ChannelConnector
{
throw SandboxViolation::record('connector', "Portalanbindung [{$key}] ist im Prozess-Tester nicht erlaubt.");
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Process\Tester;
use App\Actions\CreateReservation;
use App\Actions\PrepareStays;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Date;
/**
* What the events of a scenario work with inside a tester run: the tested channel and intake kind, the property, the
* case the scenario created, the landlord's inputs and the simulated clock.
*/
final class SandboxContext
{
public ?Booking $booking = null;
/**
* @param array<string, mixed> $inputs
*/
public function __construct(
public readonly Channel $channel,
public readonly IntakeKind $intake,
public readonly Property $property,
public readonly array $inputs,
) {}
public function arrival(): CarbonImmutable
{
$value = (string) ($this->inputs['arrival'] ?? '+21 days');
return CarbonImmutable::parse($value, now()->getTimezone())->startOfDay();
}
public function departure(): CarbonImmutable
{
return $this->arrival()->addDays(max(1, (int) ($this->inputs['nights'] ?? 4)));
}
public function guests(): int
{
return max(1, (int) ($this->inputs['guests'] ?? 2));
}
/**
* A request through the same action as the website's booking form.
*
* @param array<string, string> $guest
*/
public function request(array $guest): Booking
{
return $this->booking = app(CreateReservation::class)->handle(
$this->property,
new StayRequest($this->arrival(), $this->departure(), $this->guests()),
['first_name' => 'Testgast', 'last_name' => 'Sandbox', 'email' => 'gast@tester.invalid', ...$guest],
source: $this->channel->isWebsite() ? 'website' : 'channel',
originChannel: $this->channel->isWebsite() ? null : $this->channel,
);
}
/**
* Time passes: the clock moves on and the case-related schedulers run in the order of routes/console.php.
*/
public function travel(int $minutes): void
{
Date::setTestNow(now()->addMinutes($minutes));
foreach (['bookings:expire-holds', 'bookings:auto-offers', 'cases:data-requests'] as $command) {
Artisan::call($command);
}
app(SendBookingReminders::class)->handle();
app(PrepareStays::class)->handle();
app(RequestReviews::class)->handle();
}
public function travelTo(CarbonImmutable $moment): void
{
$minutes = (int) max(0, now()->diffInMinutes($moment));
$this->travel($minutes);
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Process\Tester;
use App\Channels\Mail\MailboxReader;
/**
* The mailbox of a tester run: it cannot be read. Incoming mails of a scenario are fed in directly as PortalMail.
*/
final class SandboxMailboxReader extends MailboxReader
{
public function fetch(array $senders): array
{
throw SandboxViolation::record('imap', 'Postfachabruf ist im Prozess-Tester nicht erlaubt.');
}
public function fetchAll(): array
{
throw SandboxViolation::record('imap', 'Postfachabruf ist im Prozess-Tester nicht erlaubt.');
}
public function probe(array $config): int
{
throw SandboxViolation::record('imap', 'Postfachprüfung ist im Prozess-Tester nicht erlaubt.');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Process\Tester;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
/**
* The scripted network answers of a scenario (e.g. the landlord's AI access answering an extraction). Everything else
* is refused by SandboxServiceProvider.
*/
final class SandboxNetwork
{
/** @var array<string, callable(Request): (PromiseInterface|array<string, mixed>|null)> host => answer */
private static array $answers = [];
/**
* @param callable(Request): (PromiseInterface|array<string, mixed>|null) $answer
*/
public static function script(string $host, callable $answer): void
{
self::$answers[$host] = $answer;
}
public static function reset(): void
{
self::$answers = [];
}
public static function answer(Request $request): ?PromiseInterface
{
$host = (string) parse_url($request->url(), PHP_URL_HOST);
$answer = isset(self::$answers[$host]) ? (self::$answers[$host])($request) : null;
return match (true) {
$answer === null => null,
$answer instanceof PromiseInterface => $answer,
default => Http::response($answer),
};
}
}
@@ -0,0 +1,126 @@
<?php
namespace App\Process\Tester;
use App\Channels\ChannelRegistry;
use App\Channels\Mail\MailboxReader;
use Illuminate\Cache\CacheManager;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Http\Client\Request;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
/**
* Bindings of a tester process (only registered by SandboxBootstrapper): managers that refuse every name except the
* sandbox's own – recording the attempt in the run's ledger before they throw –, a guard on the sandbox connection that
* verifies the database file, a mailbox that cannot be read, no real connectors and no network without a scripted answer.
*/
final class SandboxServiceProvider extends ServiceProvider
{
public function register(): void
{
EffectLedger::open(config('sandbox.directory').'/ledger.jsonl');
// The file the run may use, fixed now: later changes of the configuration cannot widen it.
$file = (string) config('database.connections.sandbox.database');
$this->app->singleton('db', fn ($app): DatabaseManager => new class($app, $app['db.factory'], $file) extends DatabaseManager
{
public function __construct($app, $factory, private string $file)
{
parent::__construct($app, $factory);
}
public function connection($name = null)
{
$name ??= $this->getDefaultConnection();
[$database] = $this->parseConnectionName($name);
if ($database !== 'sandbox') {
throw SandboxViolation::record('database', "Verbindung [{$name}] ist im Prozess-Tester nicht erlaubt.");
}
return parent::connection($name);
}
/** Every (re)connected sandbox connection gets the guard: each statement must go to the run's own file. */
protected function configure(Connection $connection, $type)
{
$connection = parent::configure($connection, $type);
$expected = realpath($this->file) ?: $this->file;
$connection->beforeExecuting(function (string $query, array $bindings, Connection $connection) use ($expected): void {
$actual = (string) $connection->getConfig('database');
if ((realpath($actual) ?: $actual) !== $expected) {
throw SandboxViolation::record('database', 'Abfrage an eine andere Datenbankdatei: '.basename($actual));
}
});
return $connection;
}
});
$this->app->singleton('filesystem', fn ($app): FilesystemManager => new class($app) extends FilesystemManager
{
public function build($config)
{
$root = is_array($config) ? (string) ($config['root'] ?? '') : '';
if (! str_starts_with(str_replace('\\', '/', $root), str_replace('\\', '/', (string) config('sandbox.directory')))) {
throw SandboxViolation::record('file', 'Dateiablage außerhalb des Laufverzeichnisses ist im Prozess-Tester nicht erlaubt.');
}
return parent::build($config);
}
});
// Mail and cache come from deferred providers, which would register their managers again on first use: they are
// loaded and replaced just before the application boots, when the list of deferred services is complete.
$this->app->booting(function (): void {
foreach (['mail.manager', 'cache'] as $service) {
$this->app->loadDeferredProvider($service);
}
$this->app->singleton('mail.manager', fn ($app): MailManager => new class($app) extends MailManager
{
public function mailer($name = null)
{
if (($name ?? $this->getDefaultDriver()) !== 'array') {
throw SandboxViolation::record('mail', "Mailer [{$name}] ist im Prozess-Tester nicht erlaubt.");
}
return parent::mailer($name);
}
});
$this->app->singleton('cache', fn ($app): CacheManager => new class($app) extends CacheManager
{
public function store($name = null)
{
if (($name ?? $this->getDefaultDriver()) !== 'array') {
throw SandboxViolation::record('cache', "Cache [{$name}] ist im Prozess-Tester nicht erlaubt.");
}
return parent::store($name);
}
});
});
$this->app->singleton(MailboxReader::class, fn (): MailboxReader => new SandboxMailboxReader);
$this->app->singleton(ChannelRegistry::class, fn (): ChannelRegistry => new SandboxChannelRegistry);
}
public function boot(): void
{
// No network: only the scenario's scripted answers (ProcessSandboxDriver::script) are served.
Http::preventStrayRequests();
Http::fake(function (Request $request) {
$answer = SandboxNetwork::answer($request);
if ($answer === null) {
throw SandboxViolation::record('network', 'Netzzugriff ohne Szenario-Antwort: '.$request->method().' '.parse_url($request->url(), PHP_URL_HOST));
}
EffectLedger::record('network', ['method' => $request->method(), 'host' => parse_url($request->url(), PHP_URL_HOST), 'scripted' => true]);
return $answer;
});
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Models\Channel;
use App\Models\Tenant;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* What a tester run starts from (docs/Prozessarchitektur/Architektur/04 §3.2): read – never written – from the real
* database by the landlord's request, as plain values. Only the landlord's own setup: the tenant, its websites,
* properties with seasons, offers, extras, templates and texts, the channels (the tested one with the unsaved draft)
* and the calendar as anonymous blocks. Never guests, bookings, messages, facts, access data or keys: the run creates
* its cases synthetically. Encrypted values are decrypted here and encrypted again with the run's own key.
*/
final class SandboxSnapshot
{
/** Tables copied, in insert order. */
public const TABLES = ['tenants', 'sites', 'site_domains', 'properties', 'seasons', 'special_offers', 'extras', 'cancellation_policies', 'contract_templates', 'contract_annexes', 'content_blocks', 'channels', 'blocked_periods'];
/** Columns never copied (access data, tokens, raw portal data). */
public const DROPPED = [
'tenants' => ['mailbox_password'],
'channels' => ['previous_export_token', 'export_snapshot', 'ical_analysis'],
'blocked_periods' => ['ical_properties', 'ical_raw', 'ical_interpretation', 'linked_booking_id', 'guest_name'],
];
/** Encrypted columns that are carried as plain values and encrypted again in the run. */
public const ENCRYPTED = ['tenants' => ['bank_account_holder', 'bank_iban', 'bank_bic', 'bank_name', 'tax_note']];
/**
* @param array<string, mixed> $draft model, variant, steps, settings of the tested channel and intake kind
* @return array{tenant_id: int, channel_id: int, intake: string, tables: array<string, list<array<string, mixed>>>, encrypted: array<string, list<string>>}
*/
public static function build(Channel $channel, IntakeKind $intake, array $draft): array
{
$tenant = Tenant::query()->findOrFail($channel->tenant_id);
$propertyIds = DB::table('properties')->where('tenant_id', $tenant->id)->pluck('id')->all();
$tables = [];
foreach (self::TABLES as $table) {
if (! Schema::hasTable($table)) {
continue;
}
$query = DB::table($table);
$query = match (true) {
$table === 'tenants' => $query->where('id', $tenant->id),
Schema::hasColumn($table, 'tenant_id') => $query->where('tenant_id', $tenant->id),
Schema::hasColumn($table, 'property_id') => $query->whereIn('property_id', $propertyIds),
default => null,
};
if ($query === null) {
continue;
}
$tables[$table] = $query->orderBy('id')->get()->map(fn (object $row): array => self::clean($table, (array) $row))->all();
}
// The tested channel carries the draft (also unsaved) – and creates cases from portal mails in the run.
foreach ($tables['channels'] ?? [] as $index => $row) {
if ((int) $row['id'] === $channel->id) {
$overrides = (array) json_decode((string) ($row['process_overrides'] ?? '[]'), true);
$overrides[$intake->value] = [...array_filter((array) ($draft['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== ''), 'model' => $draft['model'] ?? null, 'variant' => $draft['variant'] ?? 'standard', 'steps' => (array) ($draft['steps'] ?? [])];
$tables['channels'][$index]['process_overrides'] = json_encode($overrides);
$tables['channels'][$index]['case_intake'] = 'create';
// In the run the tested portal is active, so its (synthetic) booking mails are recognised.
$tables['channels'][$index]['is_active'] = 1;
$tables['channels'][$index]['status'] = 'active';
$settings = (array) json_decode((string) ($row['settings'] ?? '[]'), true);
$settings['email_senders'] = filled($settings['email_senders'] ?? null) ? $settings['email_senders'] : 'portal.invalid';
$tables['channels'][$index]['settings'] = json_encode($settings);
}
}
return ['tenant_id' => $tenant->id, 'channel_id' => $channel->id, 'intake' => $intake->value, 'tables' => $tables, 'encrypted' => self::ENCRYPTED];
}
/**
* @param array<string, mixed> $row
* @return array<string, mixed>
*/
private static function clean(string $table, array $row): array
{
foreach (self::DROPPED[$table] ?? [] as $column) {
if (array_key_exists($column, $row)) {
$row[$column] = null;
}
}
foreach (self::ENCRYPTED[$table] ?? [] as $column) {
if (filled($row[$column] ?? null)) {
try {
$row[$column] = Crypt::decryptString((string) $row[$column]);
} catch (Throwable) {
$row[$column] = null;
}
}
}
if ($table === 'channels' && array_key_exists('export_token', $row)) {
// The real export link is never part of a run: a random one of no use outside it.
$row['export_token'] = bin2hex(random_bytes(20));
}
if ($table === 'tenants') {
// The run is always in test operation and writes only to its own test address.
$row['operating_mode'] = 'test';
$row['test_recipient'] = 'tester@sandbox.invalid';
}
return $row;
}
/**
* Writes the snapshot into the run's own database (inside the tester process only).
*
* @param array{tables: array<string, list<array<string, mixed>>>, encrypted: array<string, list<string>>} $snapshot
*/
public static function seed(array $snapshot): void
{
if (config('database.default') !== 'sandbox') {
throw SandboxViolation::record('database', 'Einspielen nur in die Testdatenbank.');
}
Schema::disableForeignKeyConstraints();
foreach ($snapshot['tables'] as $table => $rows) {
if (! Schema::hasTable($table)) {
continue;
}
$columns = array_flip(Schema::getColumnListing($table));
foreach ($rows as $row) {
foreach ($snapshot['encrypted'][$table] ?? [] as $column) {
if (filled($row[$column] ?? null)) {
$row[$column] = Crypt::encryptString((string) $row[$column]);
}
}
DB::table($table)->insert(array_intersect_key($row, $columns));
}
}
Schema::enableForeignKeyConstraints();
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Process\Tester;
use RuntimeException;
/**
* Something inside a tester run tried to reach the real world (a database other than the run's own, the network
* without a scripted answer, the mailbox, another mailer or store). It is recorded in the run's ledger before it is
* thrown, so a run that swallowed it is still reported as aborted (docs/Prozessarchitektur/Architektur/04 §3.3).
*/
final class SandboxViolation extends RuntimeException
{
public static function record(string $kind, string $message): self
{
EffectLedger::record('violation', ['kind' => $kind, 'message' => $message]);
return new self('Prozess-Tester: unzulässiger Zugriff ('.$kind.'): '.$message);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Process\Tester\Scenarios\CommunicationFailure;
use App\Process\Tester\Scenarios\CompleteRequest;
use App\Process\Tester\Scenarios\MissingAddress;
use App\Process\Tester\Scenarios\PortalBooking;
use App\Process\Tester\Scenarios\PortalInquiry;
use App\Process\Tester\Scenarios\ReturningGuest;
use App\Process\Tester\Scenarios\Scenario;
/**
* The predefined scenarios of the process tester (decision E9).
*/
final class ScenarioCatalogue
{
/** @var list<class-string<Scenario>> */
public const SCENARIOS = [CompleteRequest::class, MissingAddress::class, PortalInquiry::class, ReturningGuest::class, CommunicationFailure::class, PortalBooking::class];
/**
* @return array<string, class-string<Scenario>>
*/
public static function for(IntakeKind $intake, bool $website): array
{
$scenarios = [];
foreach (self::SCENARIOS as $class) {
if (! in_array($intake, $class::intakes(), true)) {
continue;
}
// A website request is never a portal's request and vice versa.
if (($class === PortalInquiry::class && $website) || ($website === false && $intake === IntakeKind::Inquiry && in_array($class, [CompleteRequest::class, MissingAddress::class, ReturningGuest::class, CommunicationFailure::class], true))) {
continue;
}
$scenarios[$class::key()] = $class;
}
return $scenarios;
}
/**
* @return class-string<Scenario>|null
*/
public static function find(string $key): ?string
{
foreach (self::SCENARIOS as $class) {
if ($class::key() === $key) {
return $class;
}
}
return null;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Event;
use Symfony\Component\Mailer\Exception\TransportException;
/**
* S12: the mail server fails when the request comes in – the case must be kept and show a defined state (the real
* error type of the transport, no crash). The failure is simulated where every mail passes (MessageSending), without a
* transport of its own.
*/
final class CommunicationFailure extends Scenario
{
public static function key(): string
{
return 'mail_failure';
}
public static function label(): string
{
return 'Mailversand fällt aus';
}
public static function description(): string
{
return 'Beim Eingang der Anfrage ist der Mailserver nicht erreichbar. Der Vorgang bleibt erhalten und zeigt, was von Hand zu tun ist.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Mailserver fällt aus', function (SandboxContext $context): void {
Event::listen(MessageSending::class, function (): void {
throw new TransportException('Verbindung zum Mailserver fehlgeschlagen (simuliert).');
});
}),
new ScenarioEvent('Gast fragt mit allen Angaben an', fn (SandboxContext $context) => $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\AcceptOffer;
use App\Actions\SendOffer;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* S01/S06/S11: a complete request – offer (automatic or by the landlord), acceptance, binding booking, arrival, after
* departure (review request, closing; a switched-off step is shown as skipped).
*/
final class CompleteRequest extends Scenario
{
public static function key(): string
{
return 'complete_request';
}
public static function label(): string
{
return 'Vollständige Anfrage bis zur Buchung';
}
public static function description(): string
{
return 'Ein Gast fragt mit allen Angaben an, erhält das Angebot und nimmt es an; danach Anreise und Abreise.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Gast fragt mit allen Angaben an', fn (SandboxContext $context) => $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])),
new ScenarioEvent('Sie senden das Angebot (falls es nicht automatisch ging)', function (SandboxContext $context): void {
$booking = $context->booking->fresh();
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->process()->preReservation()) {
app(SendOffer::class)->handle($booking);
}
}),
new ScenarioEvent('Gast nimmt das Angebot an', function (SandboxContext $context): void {
$booking = $context->booking->fresh();
if ($booking->status === BookingStatus::OfferSent) {
app(AcceptOffer::class)->handle($booking, $booking->offer_version);
}
}),
new ScenarioEvent('Zwei Tage vor der Anreise', fn (SandboxContext $context) => $context->travelTo($context->arrival()->subDays(2)->setTime(9, 0))),
new ScenarioEvent('Drei Tage nach der Abreise', fn (SandboxContext $context) => $context->travelTo($context->departure()->addDays(3)->setTime(9, 0))),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* S02/S03/S04/S05: a request without address – clarification hold and data request run side by side, the hold
* expires, the guest answers later (by link or by e-mail), the offer follows; finally the offer's deadline passes.
*/
final class MissingAddress extends Scenario
{
public static function key(): string
{
return 'missing_address';
}
public static function label(): string
{
return 'Fehlende Anschrift, späte Antwort';
}
public static function description(): string
{
return 'Die Anfrage kommt ohne Anschrift: Rückfrage beim Gast und Klärungsreservierung laufen nebeneinander, die Reservierung läuft ab, der Gast antwortet später.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function inputs(): array
{
return [
...parent::inputs(),
'answer_after_hours' => ['label' => 'Antwort des Gastes nach (Stunden)', 'default' => 26, 'type' => 'int'],
'answer_by' => ['label' => 'Antwort über', 'default' => 'link', 'type' => 'select', 'options' => ['link' => 'Link im Formular', 'email' => 'E-Mail (ausgewertete Angaben)']],
];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Gast fragt ohne Anschrift an', fn (SandboxContext $context) => $context->request([])),
new ScenarioEvent('Zwei Stunden vergehen (Klärungsfrist)', fn (SandboxContext $context) => $context->travel(125)),
new ScenarioEvent('Gast antwortet mit seiner Anschrift', function (SandboxContext $context) use ($inputs): void {
$context->travel(max(0, (int) ($inputs['answer_after_hours'] ?? 26) * 60 - 125));
app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.street' => 'Teststraße 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], ($inputs['answer_by'] ?? 'link') === 'email' ? FactSource::Email : FactSource::GuestLink);
}),
new ScenarioEvent('Die Angebotsfrist vergeht ohne Annahme', fn (SandboxContext $context) => $context->travel(73 * 60)),
];
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Actions\ProcessPortalMail;
use App\Actions\RecordPortalAmounts;
use App\Channels\Mail\PortalMail;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Process\Tester\SandboxContext;
use Carbon\CarbonImmutable;
/**
* S07/S08/S13: a booking binding at the portal arrives by e-mail through the same entry as the mailbox (twice:
* duplicate), guest details and the portal's amounts follow; optionally the portal reports a cancellation; then the
* stay and after departure.
*/
final class PortalBooking extends Scenario
{
public static function key(): string
{
return 'portal_booking';
}
public static function label(): string
{
return 'Feste Buchung über das Portal';
}
public static function description(): string
{
return 'Die Buchungsmail des Portals kommt (zweimal) an, Gastdaten und Portalbeträge folgen; auf Wunsch meldet das Portal eine Stornierung.';
}
public static function intakes(): array
{
return [IntakeKind::Booking];
}
public static function inputs(): array
{
return [
...parent::inputs(),
'portal_total' => ['label' => 'Gesamtpreis laut Portal (€)', 'default' => 980, 'type' => 'int'],
'cancellation' => ['label' => 'Portal meldet eine Stornierung', 'default' => false, 'type' => 'bool'],
];
}
public function events(array $inputs): array
{
$total = max(1, (int) ($inputs['portal_total'] ?? 980)) * 100;
$events = [
new ScenarioEvent('Buchungsmail des Portals kommt an', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Neue Buchung: '.$context->property->name, $this->text($context))),
new ScenarioEvent('Dieselbe Buchungsmail kommt noch einmal', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Neue Buchung: '.$context->property->name, $this->text($context))),
new ScenarioEvent('Gastdaten laut Portal', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.first_name' => 'Testgast', 'guest.last_name' => 'Portal', 'guest.email' => 'portalgast@tester.invalid', 'booking.guests' => (string) $context->guests()], FactSource::PortalMail)),
new ScenarioEvent('Portal meldet Preis, Gastzahlung und angekündigte Auszahlung', fn (SandboxContext $context) => app(RecordPortalAmounts::class)->handle($context->booking->fresh(), $total, [['kind' => 'payout_announced', 'amount' => (int) round($total * 0.9)]], [['amount' => (int) round($total * 0.4), 'paid_on' => now()->toDateString()]], $context->channel->name)),
];
if ((bool) ($inputs['cancellation'] ?? false)) {
$events[] = new ScenarioEvent('Portal meldet eine Stornierung', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Buchung storniert: '.$this->reference($context), 'Die Buchung vom '.$context->arrival()->format('d.m.Y').' bis '.$context->departure()->format('d.m.Y').' wurde storniert. Buchungsnummer: '.$this->reference($context)));
}
$events[] = new ScenarioEvent('Drei Tage nach der Abreise', fn (SandboxContext $context) => $context->travelTo($context->departure()->addDays(3)->setTime(9, 0)));
return $events;
}
private function reference(SandboxContext $context): string
{
return 'TEST-'.$context->arrival()->format('md');
}
private function text(SandboxContext $context): string
{
return "Gast: Testgast Portal\nAnreise: ".$context->arrival()->format('d.m.Y')."\nAbreise: ".$context->departure()->format('d.m.Y')."\nBuchungsnummer: ".$this->reference($context);
}
private function sendPortalMail(SandboxContext $context, string $subject, string $text): void
{
$senders = array_values(array_filter(array_map('trim', explode(',', (string) ($context->channel->setting('email_senders') ?? '')))));
$sender = 'buchung@'.($senders[0] ?? 'portal.invalid');
app(ProcessPortalMail::class)->handle(new PortalMail('<'.md5($subject).'@tester.invalid>', $sender, $subject, $text, CarbonImmutable::now()));
$context->booking = Booking::query()->latest('id')->first() ?? $context->booking;
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Actions\TakeOverPortalInquiry;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* A2: a request of the portal – taken over like the portal's request mail, contact details from the portal, the
* address from the guest; then our own offer or information as the chosen model says.
*/
final class PortalInquiry extends Scenario
{
public static function key(): string
{
return 'portal_inquiry';
}
public static function label(): string
{
return 'Anfrage über das Portal';
}
public static function description(): string
{
return 'Das Portal leitet eine Anfrage weiter; Kontaktdaten kommen vom Portal, die Anschrift vom Gast.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Portal leitet eine Anfrage weiter', function (SandboxContext $context): void {
$context->booking = app(TakeOverPortalInquiry::class)->handle($context->channel, $context->arrival(), $context->departure(), 'ANF-'.$context->arrival()->format('md'));
}),
new ScenarioEvent('Kontaktdaten laut Portal', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.first_name' => 'Testgast', 'guest.last_name' => 'Anfrage', 'guest.email' => 'anfrage@tester.invalid', 'booking.guests' => (string) $context->guests()], FactSource::PortalMail)),
new ScenarioEvent('Gast ergänzt seine Anschrift', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.street' => 'Teststraße 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], FactSource::GuestLink)),
];
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\SendOffer;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Guest;
use App\Process\Tester\SandboxContext;
/**
* S09/S10: a returning guest (a synthetic former stay in the run's own data) asks again – with the loyalty variant the
* status check comes first and the discount line enters the price before it is fixed. Architecture proof; the rules
* are test assumptions.
*/
final class ReturningGuest extends Scenario
{
public static function key(): string
{
return 'returning_guest';
}
public static function label(): string
{
return 'Stammgast fragt an (Architekturnachweis)';
}
public static function description(): string
{
return 'Ein Gast mit einem früheren Aufenthalt fragt erneut an. Mit der Variante „Stammgastrabatt“ wird der Status geprüft und der Rabatt vor der Preisfestlegung eingerechnet.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function inputs(): array
{
return [...parent::inputs(), 'returning' => ['label' => 'Gast war schon einmal da', 'default' => true, 'type' => 'bool']];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Früherer Aufenthalt (nur in den Testdaten)', function (SandboxContext $context) use ($inputs): void {
if (! (bool) ($inputs['returning'] ?? true)) {
return;
}
$guest = Guest::query()->create(['tenant_id' => $context->property->tenant_id, 'first_name' => 'Testgast', 'last_name' => 'Sandbox', 'email' => 'gast@tester.invalid']);
Booking::query()->create(['tenant_id' => $context->property->tenant_id, 'property_id' => $context->property->id, 'guest_id' => $guest->id, 'status' => BookingStatus::Completed, 'intake' => 'inquiry',
'arrival' => now()->subYear()->toDateString(), 'departure' => now()->subYear()->addDays(7)->toDateString(), 'guests' => 2, 'total' => 80000, 'deposit' => 20000, 'completed_at' => now()->subYear()->addDays(8)]);
}),
new ScenarioEvent('Gast fragt mit allen Angaben an', fn (SandboxContext $context) => $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])),
new ScenarioEvent('Sie senden das Angebot (falls es nicht automatisch ging)', function (SandboxContext $context): void {
$booking = $context->booking->fresh();
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->process()->preReservation()) {
app(SendOffer::class)->handle($booking);
}
}),
];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Enums\IntakeKind;
/**
* A predefined tester scenario (decision E9): a fixed sequence of events through the same entry points as the real
* application; the landlord may change its inputs (dates, guests, missing details, returning guest, kind of failure),
* never the sequence.
*/
abstract class Scenario
{
abstract public static function key(): string;
abstract public static function label(): string;
abstract public static function description(): string;
/** @return list<IntakeKind> */
abstract public static function intakes(): array;
/**
* Inputs the landlord may change, with their defaults.
*
* @return array<string, array{label: string, default: string|int|bool, type: 'date'|'int'|'bool'|'select', options?: array<string, string>}>
*/
public static function inputs(): array
{
return [
'arrival' => ['label' => 'Anreise', 'default' => '+21 days', 'type' => 'date'],
'nights' => ['label' => 'Nächte', 'default' => 4, 'type' => 'int'],
'guests' => ['label' => 'Personen', 'default' => 2, 'type' => 'int'],
];
}
/**
* @param array<string, mixed> $inputs
* @return list<ScenarioEvent>
*/
abstract public function events(array $inputs): array;
}
@@ -0,0 +1,17 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Process\Tester\SandboxContext;
use Closure;
/**
* One event of a scenario: what happens (in plain words) and how – through the entry point the real application uses.
*/
final readonly class ScenarioEvent
{
/**
* @param Closure(SandboxContext): void $run
*/
public function __construct(public string $label, public Closure $run) {}
}