labels of the activities that were done after the previous event */ private array $doneBefore = []; /** @var list every mail of the run (simulated: the only mailer is `array`) */ private array $sent = []; /** * @param array $input input.json of the run * @return array 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 */ 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, capabilities: list}> */ 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 */ 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 */ 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)); } }