Files
fewo-stommer/app/Process/ProcessRunner.php
T
LarsandClaude Opus 5.5 7e22e12cac U-A/U-B: Prozesskern mit Fachmodulen, versionierten Modellen, eingefrorenem Prozessplan, ProcessRunner (harte/weiche Abhängigkeiten), CasePricing, Loyalty nur im Tester
CaseActivities/CaseAutomation sind Fassaden über ProcessRunner. Verhaltensvergleich v0.11:
11 Abläufe und 198 Konstellationen gleich, beabsichtigte Abweichungen I-004/I-005 (F-001/F-002).
Volle Suite vor U-B: 785/785.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:49:44 +01:00

198 lines
7.8 KiB
PHP
Raw 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;
use App\Enums\ActivityState;
use App\Models\Booking;
use App\Process\Modules\ProcessModule;
use App\Process\Modules\RunsAutomatically;
use App\Process\Modules\StepState;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* The one process core (docs/Prozessarchitektur/Architektur/02 §7): reads a case's course from its frozen plan and
* carries it on as far as its data allows.
*
* - **No second truth:** every state is derived from the case's data on each evaluation; the runner stores nothing.
* - **Readiness (requirement T1):** an automatic step is ready when it applies, is switched on, is due, its hard
* dependencies are done and nothing blocks it. A soft dependency only orders steps due in the same round. A waiting
* step therefore holds back exactly the steps that depend on it hard – a clarification hold runs on while the data
* request waits for the guest.
* - **Re-evaluation:** one step per round; after each step the case is read again and readiness is determined anew – a
* list of runnable steps is never carried over a state change.
* - **Triggers:** the existing places call {@see advance()} with what happened; only modules that declare the trigger
* are considered, so every caller keeps the scope it had in v0.11.
*/
final class ProcessRunner
{
/** The trigger of the former CaseAutomation::advance (facts, portal amounts, the landlord's "continue automatically"). */
public const AUTOMATION = 'automation';
/** @var array<int, true> cases being advanced in this process (a nested call returns at once) */
private static array $running = [];
public function __construct(private ProcessCatalogue $catalogue) {}
/**
* The activities of a case in the order of its plan, as the landlord sees them.
*
* @return list<Activity>
*/
public function activities(Booking $booking): array
{
$context = CaseContext::of($booking);
$activities = [];
foreach ($context->plan->moduleKeys() as $key) {
if (! $this->catalogue->hasModule($key)) {
// A step whose module was retired (T3): the finished case stays readable with the frozen label.
$activities[] = new Activity($key, ($context->plan->labels[$key] ?? $key).' (frühere Fassung)', ActivityState::NotApplicable);
continue;
}
$module = $this->catalogue->module($key);
if (! $context->plan->enabled($key) || ! $module->applies($context)) {
continue;
}
array_push($activities, ...$module->activities($context));
}
return $activities;
}
/**
* Carries a case on by itself as far as its data allows (only steps whose mode is automatic).
*
* @param string $trigger what happened (a trigger the modules declare, e.g. 'request.created')
*/
public function advance(Booking $booking, string $trigger = self::AUTOMATION): AdvanceResult
{
$result = new AdvanceResult;
if (isset(self::$running[$booking->id])) {
return $result;
}
$lock = Cache::lock('case-advance:'.$booking->id, 60);
if (! $lock->get()) {
// Another process is advancing this case right now and evaluates it again after each step.
return $result;
}
self::$running[$booking->id] = true;
try {
$this->rounds($booking, $trigger, $result);
} finally {
unset(self::$running[$booking->id]);
$lock->release();
}
return $result;
}
private function rounds(Booking $booking, string $trigger, AdvanceResult $result): void
{
$attempted = [];
$plan = ProcessPlan::of($booking);
$limit = count($plan->modules) + 1;
for ($round = 0; $round < $limit; $round++) {
$context = new CaseContext($booking->fresh() ?? $booking, $plan);
$ready = $this->ready($context, $trigger, $attempted, $result);
if ($ready === null) {
return;
}
$key = $ready::key();
$attempted[$key] = true;
/** @var ProcessModule&RunsAutomatically $ready */
try {
$step = CaseLog::context(fn (): StepResult => $ready->run($context), actor: CaseLog::SYSTEM.' (automatisch)');
} catch (Throwable $exception) {
report($exception);
$step = StepResult::failed('Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.');
}
if ($step->didRun()) {
$result->ran[] = $key;
} else {
$result->held[$key] = $step->reasons;
}
}
}
/**
* The next step to carry out, determined anew from the case's current data; steps that are due but cannot run are
* recorded with their reasons.
*
* @param array<string, true> $attempted
*/
private function ready(CaseContext $context, string $trigger, array $attempted, AdvanceResult $result): ?ProcessModule
{
$candidates = [];
foreach ($context->plan->moduleKeys() as $key) {
if (isset($attempted[$key]) || ! $this->catalogue->hasModule($key)) {
continue;
}
$module = $this->catalogue->module($key);
if (! $module instanceof RunsAutomatically || ! in_array($trigger, $module::definition()->triggers, true)) {
continue;
}
if (! $context->plan->enabled($key) || ! $module->applies($context) || ! $module->due($context)) {
continue;
}
$unmet = $this->unmetHardDependencies($module, $context);
if ($unmet !== []) {
// Not ready: a hard requirement is missing. Its own blockers say what (e.g. the missing details).
$result->held[$key] = $module->blockers($context) ?: array_map(fn (string $label): string => 'Wartet auf: '.$label.'.', $unmet);
continue;
}
if ($module->isOutward() && ($reason = OutwardSuspension::reason($context->booking)) !== null) {
$result->held[$key] = [$reason];
continue;
}
$candidates[$key] = $module;
}
foreach ($candidates as $key => $module) {
// A soft dependency that is ready in the same round goes first.
$before = array_filter($module::definition()->requires, fn ($dependency): bool => ! $dependency->hard && isset($candidates[$dependency->module]));
if ($before === []) {
return $module;
}
}
return $candidates === [] ? null : reset($candidates);
}
/**
* Labels of the hard dependencies that are not done. A dependency on a step that is not part of the plan or does
* not apply to the case is fulfilled (the condition does not concern this case).
*
* @return list<string>
*/
public function unmetHardDependencies(ProcessModule $module, CaseContext $context): array
{
$unmet = [];
foreach ($module::definition()->requires as $dependency) {
if (! $dependency->hard || ! array_key_exists($dependency->module, $context->plan->modules) || ! $this->catalogue->hasModule($dependency->module)) {
continue;
}
$required = $this->catalogue->module($dependency->module);
if (! $context->plan->enabled($dependency->module) || ! $required->applies($context)) {
continue;
}
$state = $required->state($context);
if ($state !== null && ! $state->fulfils() && $state !== StepState::NotApplicable) {
$unmet[] = $required::definition()->label;
}
}
return $unmet;
}
}