Files
fewo-stommer/app/Process/Tester/ProcessSandboxDriver.php
LarsandClaude Sonnet 5.5 c46f4a032b Kanalkonfigurator und Prozess-Tester auf Schablonenbasis
Geschäftsentscheidungen zuerst (Schablonen je Bereich, Voreinstellungen A3–A5), Einzelschritte
eingeklappt, Auswirkungsanalyse beim Schablonenwechsel, unbestätigte Portal-Fähigkeiten gekennzeichnet.
Tester-Bericht nennt Schablonen, unabhängig laufende Schritte und fehlende Nachweise; alle vier
Kombinationen sind als Szenario getestet. Doku: SCHABLONEN.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:56:51 +01:00

261 lines
12 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace 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\Capability;
use App\Process\CaseActivities;
use App\Process\CaseContext;
use App\Process\ChannelCapabilities;
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<string> labels of the activities that were done after the previous event */
private array $doneBefore = [];
/** @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, $channel),
'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, Channel $channel): 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),
'templates' => $this->templates($plan, $channel),
'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 function templates the case follows: what each stands for, its modules and the portal capabilities it relies on
* with their origin – a capability that is only suggested or derived is shown as not confirmed, never as proven.
*
* @return list<array{area: string, label: string, reference: string, responsibility: string, modules: list<string>, capabilities: list<array{label: string, required: string, source: string, confirmed: bool}>}>
*/
private function templates(ProcessPlan $plan, Channel $channel): array
{
$catalogue = app(ProcessCatalogue::class);
$capabilities = app(ChannelCapabilities::class)->resolve($channel);
$rows = [];
foreach ($plan->templates as $area => $reference) {
$class = $catalogue->templateClass($reference);
if ($class === null) {
continue;
}
$rows[] = [
'area' => $class::area()->label(),
'label' => $class::label(),
'reference' => $reference,
'responsibility' => $class::responsibility()->getLabel(),
'modules' => array_values(array_map(fn (string $module): string => $plan->labels[$module] ?? $module, $class::modules())),
'capabilities' => array_values(array_map(function (string $key, bool $required) use ($capabilities): array {
$capability = $capabilities[$key] ?? null;
return [
'label' => ChannelCapabilities::definitions()[$key]['question'],
'required' => $required ? 'ja' : 'nein',
'source' => $capability?->sourceLabel() ?? 'noch nicht bekannt',
'confirmed' => $capability?->source === Capability::CONFIRMED,
];
}, array_keys($class::capabilityRequirements()), $class::capabilityRequirements())),
];
}
return $rows;
}
/**
* 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];
}
}
$activities = CaseActivities::for($booking);
$waiting = array_values(array_map(fn ($activity): string => $activity->label, array_filter($activities, fn ($activity): bool => $activity->state->value === 'waiting')));
$done = array_values(array_map(fn ($activity): string => $activity->label, array_filter($activities, fn ($activity): bool => in_array($activity->state->value, ['done', 'external'], true))));
// Steps that came to an end in this event while others wait: they do not hold each other up.
$independent = $waiting === [] ? [] : array_values(array_diff($done, $this->doneBefore));
$this->doneBefore = $done;
return [
'status' => $booking->status->getLabel(),
'situation' => CaseActivities::situation($booking),
'waiting' => $waiting,
'independent' => $independent,
'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));
}
}