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

+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));
}
}