From e95ba4f9862158f9f8df23220425f6e24f293d94 Mon Sep 17 00:00:00 2001 From: Lars Date: Thu, 5 Nov 2026 10:48:49 +0100 Subject: [PATCH] =?UTF-8?q?Schablonenkomposition:=20Basisprozess=20externa?= =?UTF-8?q?l.booking=20mit=20Platz=20f=C3=BCr=20Finanz-=20und=20Dokumenten?= =?UTF-8?q?schablonen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vier Schablonen (Eigenes/Portal-Inkasso, Eigene/Externe Vertragsdokumentation) in app/Process/Templates, TemplateComposer prüft Ergebnisse, Verantwortlichkeiten, Ausschlüsse und harte Modulabhängigkeiten. Der Plan friert die Schablonenversionen ein. A3–A5 bleiben als Voreinstellungen; die vierte Kombination (eigenes Inkasso + externe Unterlagen) ist darstellbar. Konfigurator-Logik und ConfigureChannelProcess kennen die Schablonenwahl. Co-Authored-By: Claude Sonnet 5.5 --- app/Actions/ConfigureChannelProcess.php | 17 +- app/Process/ChannelProcessConfiguration.php | 140 ++++- app/Process/Models/A3PortalBookingModel.php | 10 + app/Process/Models/A4PortalBookingModel.php | 10 + app/Process/Models/A5PortalBookingModel.php | 10 + app/Process/Models/ExternalBookingModel.php | 107 ++++ app/Process/Models/ProcessModel.php | 63 ++- app/Process/Models/Step.php | 17 +- app/Process/ProcessCatalogue.php | 79 +++ app/Process/ProcessPlan.php | 29 +- app/Process/ProcessProfile.php | 10 +- app/Process/ProcessSettings.php | 25 + .../Templates/ExternalContractDocuments.php | 68 +++ app/Process/Templates/FunctionTemplate.php | 112 ++++ app/Process/Templates/OwnCollection.php | 78 +++ .../Templates/OwnContractDocumentation.php | 72 +++ app/Process/Templates/PortalCollection.php | 73 +++ app/Process/Templates/TemplateArea.php | 49 ++ app/Process/Templates/TemplateComposer.php | 192 +++++++ app/Process/Tester/SandboxSnapshot.php | 2 +- config/process.php | 14 + .../Feature/Process/ChannelCapabilityTest.php | 2 +- .../ChannelProcessConfiguratorTest.php | 6 +- .../Process/TemplateCompositionTest.php | 518 ++++++++++++++++++ 24 files changed, 1666 insertions(+), 37 deletions(-) create mode 100644 app/Process/Models/ExternalBookingModel.php create mode 100644 app/Process/Templates/ExternalContractDocuments.php create mode 100644 app/Process/Templates/FunctionTemplate.php create mode 100644 app/Process/Templates/OwnCollection.php create mode 100644 app/Process/Templates/OwnContractDocumentation.php create mode 100644 app/Process/Templates/PortalCollection.php create mode 100644 app/Process/Templates/TemplateArea.php create mode 100644 app/Process/Templates/TemplateComposer.php create mode 100644 tests/Feature/Process/TemplateCompositionTest.php diff --git a/app/Actions/ConfigureChannelProcess.php b/app/Actions/ConfigureChannelProcess.php index b26c80d..d351e05 100644 --- a/app/Actions/ConfigureChannelProcess.php +++ b/app/Actions/ConfigureChannelProcess.php @@ -7,6 +7,7 @@ use App\Models\Channel; use App\Process\ChannelCapabilities; use App\Process\ChannelProcessConfiguration; +use App\Process\ProcessCatalogue; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; @@ -23,10 +24,10 @@ class ConfigureChannelProcess { public const HISTORY_LIMIT = 20; - public function __construct(private ChannelProcessConfiguration $configuration, private ChannelCapabilities $capabilities) {} + public function __construct(private ChannelProcessConfiguration $configuration, private ChannelCapabilities $capabilities, private ProcessCatalogue $catalogue) {} /** - * @param array{model: string, variant?: string, steps?: array, settings?: array, capabilities?: array} $draft + * @param array{model: string, variant?: string, steps?: array, settings?: array, templates?: array, capabilities?: array} $draft * @param bool $acknowledgeConflicts the landlord confirmed that stored settings the model overrides are removed * * @throws ValidationException @@ -38,7 +39,7 @@ public function handle(Channel $channel, IntakeKind $intake, array $draft, ?stri throw ValidationException::withMessages(['process' => $problems]); } - $conflicts = $this->configuration->conflicts($channel, $intake, (string) $draft['model']); + $conflicts = $this->configuration->conflicts($channel, $intake, (string) $draft['model'], (array) ($draft['templates'] ?? [])); if ($conflicts !== [] && ! $acknowledgeConflicts) { throw ValidationException::withMessages(['process' => [ 'Bisherige Einstellungen widersprechen dem gewählten Modell und würden still überstimmt. Bitte ausdrücklich bestätigen, dass sie entfernt werden:', @@ -71,11 +72,19 @@ public function handle(Channel $channel, IntakeKind $intake, array $draft, ?stri } } + // A model with slots always stores its explicit template choice (keys; the version is frozen with each new case). + $model = $this->catalogue->model((string) $draft['model']); + $templates = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->configuration->templatesOf($model, $draft)); + if ($model->slots() === []) { + $templates = []; + } + $overrides[$intake->value] = [ ...$settings, 'model' => $draft['model'], 'variant' => $draft['variant'] ?? 'standard', 'steps' => $steps, + 'templates' => $templates, 'configured_at' => now()->toIso8601String(), 'configured_by' => $by, ]; @@ -88,7 +97,7 @@ public function handle(Channel $channel, IntakeKind $intake, array $draft, ?stri $changes = $confirmed['changes']; } $channelSettings['process_history'] = array_slice([...(array) ($channelSettings['process_history'] ?? []), [ - 'at' => now()->toIso8601String(), 'by' => $by, 'intake' => $intake->value, 'model' => $draft['model'], 'variant' => $draft['variant'] ?? 'standard', + 'at' => now()->toIso8601String(), 'by' => $by, 'intake' => $intake->value, 'model' => $draft['model'], 'variant' => $draft['variant'] ?? 'standard', 'templates' => $templates, 'capabilities' => $changes, 'removed_settings' => array_map(fn (array $conflict): string => $conflict['text'], $conflicts), ]], -self::HISTORY_LIMIT); diff --git a/app/Process/ChannelProcessConfiguration.php b/app/Process/ChannelProcessConfiguration.php index c2eb652..98c8055 100644 --- a/app/Process/ChannelProcessConfiguration.php +++ b/app/Process/ChannelProcessConfiguration.php @@ -13,6 +13,9 @@ use App\Models\Channel; use App\Process\Models\ProcessModel; use App\Process\Models\Responsibilities; +use App\Process\Templates\FunctionTemplate; +use App\Process\Templates\TemplateArea; +use App\Process\Templates\TemplateComposer; /** * What the channel configurator offers and checks (docs/Prozessarchitektur/Architektur/03): per channel and intake @@ -39,7 +42,7 @@ final class ChannelProcessConfiguration 'arrival.info' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::GuestMessages], 'parameters' => [ProcessSetting::ArrivalInfoDaysBefore]], ]; - public function __construct(private ProcessCatalogue $catalogue) {} + public function __construct(private ProcessCatalogue $catalogue, private TemplateComposer $composer) {} /** * The intake kinds the channel delivers. @@ -134,20 +137,85 @@ public function admissibleModels(Channel $channel, IntakeKind $intake, ?array $c return array_map(fn (array $option): ProcessModel => $option['model'], array_filter($this->modelOptions($channel, $intake, $capabilityDraft), fn (array $option): bool => $option['admissible'])); } + /** + * Every function template of each slot of the model with whether this channel fits it and – if not – why. The + * portal's confirmed capabilities decide; an unknown capability is never taken as proven (shown as "please confirm"). + * + * @param array|null $capabilityDraft + * @return array, admissible: bool, restrictions: list, hints: list, unconfirmed: list}>> area value => template key => option + */ + public function templateOptions(Channel $channel, ProcessModel $model, ?array $capabilityDraft = null): array + { + $capabilities = app(ChannelCapabilities::class)->resolve($channel, $capabilityDraft); + $options = []; + foreach ($model->slots() as $area) { + foreach ($this->catalogue->templates($area) as $key => $class) { + $restrictions = $hints = $unconfirmed = []; + foreach ($class::capabilityRequirements() as $capability => $required) { + $actual = $capabilities[$capability] ?? null; + $definition = ChannelCapabilities::definitions()[$capability]; + if ($actual === null || ! $actual->isKnown()) { + $hints[] = $definition['label'].' ist noch nicht bekannt – bitte bestätigen.'; + $unconfirmed[] = $capability; + + continue; + } + if ($actual->source !== Capability::CONFIRMED) { + $unconfirmed[] = $capability; + $hints[] = $definition['label'].' gilt nur als „'.($actual->source === Capability::SUGGESTED ? 'Vorschlag des Kanalprofils' : 'abgeleitet').'“, nicht als bestätigt.'; + } + if ($actual->value !== $required) { + $other = collect($this->catalogue->templates($area))->first(fn (string $candidate): bool => $candidate !== $class && collect($candidate::capabilityRequirements())->every(fn (bool $value, string $name): bool => ($capabilities[$name] ?? null)?->value === $value)); + $restrictions[] = new Restriction( + Restriction::CAPABILITY, + '„'.$class::label().'“ setzt voraus: „'.$definition['question'].'“ – '.($required ? 'ja' : 'nein').'. Für diesen Kanal gilt aber '.($actual->value ? 'ja' : 'nein').' ('.$actual->sourceLabel().').', + $other ? $other::label() : null, + 'Wenn das nicht stimmt: oben bei „Was kann dieses Portal?“ „'.$definition['label'].'“ auf '.($required ? 'ja' : 'nein').' stellen und bestätigen.', + ); + } + } + $options[$area->value][$key] = ['template' => $class, 'admissible' => $restrictions === [], 'restrictions' => $restrictions, 'hints' => $hints, 'unconfirmed' => $unconfirmed]; + } + } + + return $options; + } + + /** + * The templates a draft uses for the model slots (chosen ones, otherwise the model defaults) as key@version. + * + * @param array $draft + * @return array + */ + public function templatesOf(ProcessModel $model, array $draft): array + { + return $this->composer->resolve($model, (array) ($draft['templates'] ?? [])); + } + /** * Stored settings of the channel that the chosen model fixes differently: saving the model would silently override * them (they would stay stored but not take effect). They are listed so that the landlord confirms their removal. * + * @param array $templates area => template key chosen in the draft (templates fix responsibilities just like models) * @return list */ - public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey): array + public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey, array $templates = []): array { if (! $this->catalogue->hasModel($modelKey)) { return []; } $stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []); $conflicts = []; - foreach ($this->catalogue->model($modelKey)::fixes() as $key => $fixed) { + $model = $this->catalogue->model($modelKey); + $fixes = $model::fixes(); + $fixedBy = array_fill_keys(array_keys($fixes), 'Das Modell „'.$modelKey.'“'); + foreach ($this->composer->classes($this->composer->resolve($model, $templates)) as $class) { + foreach ($class::fixes() as $key => $fixed) { + $fixes[$key] = $fixed; + $fixedBy[$key] = 'Die Schablone „'.$class::label().'“'; + } + } + foreach ($fixes as $key => $fixed) { $setting = ProcessSetting::tryFrom($key); $value = $setting?->normalize($stored[$key] ?? null); $fixedValue = $setting?->normalize($fixed) ?? $fixed; @@ -155,7 +223,7 @@ public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey continue; } $conflicts[] = ['setting' => $setting, 'stored' => $setting->describe($value), 'fixed' => $setting->describe($fixedValue), - 'text' => $setting->question().' Bisher eingestellt: „'.$setting->describe($value).'“. Das Modell „'.$modelKey.'“ legt fest: „'.$setting->describe($fixedValue).'“.']; + 'text' => $setting->question().' Bisher eingestellt: „'.$setting->describe($value).'“. '.$fixedBy[$key].' legt fest: „'.$setting->describe($fixedValue).'“.']; } // Stored responsibilities the model does not allow (variable ones, not fixed through fixes()) are just as stale. @@ -184,7 +252,7 @@ public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey public function withoutOverriddenSettings(Channel $channel, IntakeKind $intake, array $draft): array { $stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []); - foreach ($this->conflicts($channel, $intake, (string) ($draft['model'] ?? '')) as $conflict) { + foreach ($this->conflicts($channel, $intake, (string) ($draft['model'] ?? ''), (array) ($draft['templates'] ?? [])) as $conflict) { $key = $conflict['setting']->value; $value = $draft['settings'][$key] ?? null; if (array_key_exists($key, (array) ($draft['settings'] ?? [])) && (string) $conflict['setting']->normalize($value) === (string) $conflict['setting']->normalize($stored[$key] ?? null)) { @@ -199,19 +267,19 @@ public function withoutOverriddenSettings(Channel $channel, IntakeKind $intake, * The model a new case of this channel and intake would follow now: the chosen one, or the one derived from the * settings as before (marked as derived). * - * @return array{model: string, variant: string, derived: bool} + * @return array{model: string, variant: string, derived: bool, templates: array} */ public function current(Channel $channel, IntakeKind $intake): array { $config = ProcessPlan::configurationOf($channel, $intake); if (filled($config['model'] ?? null) && $this->catalogue->hasModel((string) $config['model'])) { - return ['model' => (string) $config['model'], 'variant' => (string) ($config['variant'] ?? 'standard'), 'derived' => false]; + return ['model' => (string) $config['model'], 'variant' => (string) ($config['variant'] ?? 'standard'), 'derived' => false, 'templates' => (array) ($config['templates'] ?? [])]; } $property = $channel->property; $profile = app(ProcessSettings::class)->resolve($property, $channel, $intake); - return ['model' => $this->catalogue->derivedModel($profile), 'variant' => 'standard', 'derived' => true]; + return ['model' => $this->catalogue->derivedModel($profile), 'variant' => 'standard', 'derived' => true, 'templates' => []]; } /** @@ -265,16 +333,23 @@ public function modeOptions(string $module): array * with whether it takes part and why not, who carries it out and how. * * @param array $draft model, variant, steps, settings of channels.process_overrides[intake] - * @return list + * @return list */ public function preview(Channel $channel, IntakeKind $intake, array $draft): array { $model = $this->catalogue->model((string) ($draft['model'] ?? $this->current($channel, $intake)['model'])); $variant = (string) ($draft['variant'] ?? 'standard'); $profile = $this->profileWith($channel, $intake, $draft); - $standard = $model->modules('standard'); + $templates = $this->templatesOf($model, $draft); + $standard = $model->modules('standard', $templates); + $owners = []; + foreach ($this->composer->classes($templates) as $class) { + foreach ($class::modules() as $module) { + $owners[$module] = $class::label(); + } + } $rows = []; - foreach ($model->modules($variant) as $key) { + foreach ($model->modules($variant, $templates) as $key) { $class = $this->catalogue->modules()[$key]; $definition = $class::definition(); $on = ($draft['steps'][$key]['on'] ?? true) !== false || ! $definition->isOptional(); @@ -296,7 +371,7 @@ public function preview(Channel $channel, IntakeKind $intake, array $draft): arr default => $definition->performers[0] ?? null, }; $rows[] = ['module' => $key, 'label' => $definition->label, 'phase' => $definition->phase, 'on' => $on && $reason === null, 'reason' => $reason, - 'performer' => $performer, 'mode' => $mode, 'toggle' => $definition->toggle, 'tester_only' => $definition->isTesterOnly(), 'inserted' => ! in_array($key, $standard, true)]; + 'performer' => $performer, 'mode' => $mode, 'toggle' => $definition->toggle, 'tester_only' => $definition->isTesterOnly(), 'inserted' => ! in_array($key, $standard, true), 'template' => $owners[$key] ?? null]; } return $rows; @@ -332,8 +407,9 @@ public function problems(Channel $channel, IntakeKind $intake, array $draft, boo $problems[] = 'Die Variante „'.$variant->label.'“ ist nur im Prozess-Tester verwendbar und kann nicht gespeichert werden.'; } + $templates = $this->templatesOf($model, $draft); foreach ((array) ($draft['steps'] ?? []) as $module => $step) { - if (! $this->catalogue->hasModule($module) || ! in_array($module, $model->modules($variant->key), true)) { + if (! $this->catalogue->hasModule($module) || ! in_array($module, $model->modules($variant->key, $templates), true)) { $problems[] = "Der Schritt {$module} gehört nicht zu diesem Modell."; continue; @@ -360,7 +436,41 @@ public function problems(Channel $channel, IntakeKind $intake, array $draft, boo } } - return array_values(array_unique($problems)); + return array_values(array_unique([...$problems, ...$this->templateProblems($channel, $model, $draft)])); + } + + /** + * What is wrong with the function templates of a draft: composition, the confirmed capabilities of the portal and + * responsibilities set by hand that contradict a template. + * + * @param array $draft + * @return list + */ + private function templateProblems(Channel $channel, ProcessModel $model, array $draft): array + { + $variant = (string) ($draft['variant'] ?? 'standard'); + $problems = $this->composer->problems($model, (array) ($draft['templates'] ?? []), $variant); + if ($model->slots() === []) { + return $problems; + } + $capabilities = (array) ($draft['capabilities'] ?? []) ?: null; + $options = $this->templateOptions($channel, $model, $capabilities); + foreach ($this->composer->classes($this->templatesOf($model, $draft)) as $area => $class) { + foreach ($options[$area][$class::key()]['restrictions'] ?? [] as $restriction) { + $problems[] = $restriction->text(); + } + $setting = TemplateArea::from($area)->setting(); + $value = $setting->normalize($draft['settings'][$setting->value] ?? null); + if ($value !== null && (string) $value !== $class::responsibility()->value) { + $problems[] = $setting->question().' „'.$setting->describe($value).'“ widerspricht der Schablone „'.$class::label().'“ ('.$setting->describe($class::responsibility()->value).').'; + } + } + $messages = app(ChannelCapabilities::class)->resolve($channel, $capabilities)[ChannelCapabilities::MESSAGES_GUEST] ?? null; + if (($draft['settings'][ProcessSetting::GuestMessages->value] ?? null) === Responsibility::Portal->value && $messages !== null && $messages->isKnown() && $messages->value === false) { + $problems[] = 'Gastkommunikation durch das Portal ist eingestellt, das Portal schreibt den Gast laut bestätigter Fähigkeit aber nicht an.'; + } + + return $problems; } /** @@ -373,7 +483,7 @@ public function profileWith(Channel $channel, IntakeKind $intake, array $draft): $draft = $this->withoutOverriddenSettings($channel, $intake, $draft); $preview = clone $channel; $overrides = (array) ($channel->process_overrides ?? []); - $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'] ?? [])]; + $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'] ?? []), 'templates' => (array) ($draft['templates'] ?? [])]; $preview->setAttribute('process_overrides', $overrides); return app(ProcessSettings::class)->resolve($channel->property, $preview, $intake); diff --git a/app/Process/Models/A3PortalBookingModel.php b/app/Process/Models/A3PortalBookingModel.php index aeddf8a..81d175b 100644 --- a/app/Process/Models/A3PortalBookingModel.php +++ b/app/Process/Models/A3PortalBookingModel.php @@ -48,6 +48,16 @@ public static function responsibilities(): Responsibilities ); } + public static function isLegacy(): bool + { + return true; + } + + public static function presetTemplates(): array + { + return ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own']; + } + public static function fixes(): array { return ['payments' => 'landlord', 'documents' => 'landlord']; diff --git a/app/Process/Models/A4PortalBookingModel.php b/app/Process/Models/A4PortalBookingModel.php index 33daf3f..e68866b 100644 --- a/app/Process/Models/A4PortalBookingModel.php +++ b/app/Process/Models/A4PortalBookingModel.php @@ -48,6 +48,16 @@ public static function responsibilities(): Responsibilities ); } + public static function isLegacy(): bool + { + return true; + } + + public static function presetTemplates(): array + { + return ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']; + } + public static function fixes(): array { return ['payments' => 'portal', 'documents' => 'landlord']; diff --git a/app/Process/Models/A5PortalBookingModel.php b/app/Process/Models/A5PortalBookingModel.php index 8a7b410..11efb6e 100644 --- a/app/Process/Models/A5PortalBookingModel.php +++ b/app/Process/Models/A5PortalBookingModel.php @@ -48,6 +48,16 @@ public static function responsibilities(): Responsibilities ); } + public static function isLegacy(): bool + { + return true; + } + + public static function presetTemplates(): array + { + return ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.external']; + } + public static function fixes(): array { return ['payments' => 'portal', 'documents' => 'portal']; diff --git a/app/Process/Models/ExternalBookingModel.php b/app/Process/Models/ExternalBookingModel.php new file mode 100644 index 0000000..a38b8c2 --- /dev/null +++ b/app/Process/Models/ExternalBookingModel.php @@ -0,0 +1,107 @@ + Responsibility::Portal], + variable: [ + 'collection' => [Responsibility::Landlord, Responsibility::Portal], + 'contract_documents' => [Responsibility::Landlord, Responsibility::Portal], + 'guest_messages' => [Responsibility::Landlord, Responsibility::Portal], + 'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody], + 'local_services' => [Responsibility::Landlord], + ], + ); + } + + public static function providedResults(): array + { + return self::PROVIDES; + } + + public static function defaultTemplates(): array + { + return [ + TemplateArea::Collection->value => 'collection.own', + TemplateArea::ContractDocuments->value => 'contract_docs.own', + ]; + } + + public function steps(): array + { + return [ + Step::module('intake.record'), + Step::module('guest.details'), + Step::point(Point::AfterGuestIdentified), + Step::module('binding.portal'), + Step::module('portal.confirmation'), + Step::point(Point::AfterBinding), + Step::slot(TemplateArea::ContractDocuments), + Step::module('channels.block'), + Step::slot(TemplateArea::Collection), + Step::module('case.tasks'), + Step::module('change.proposal'), + Step::module('arrival.details'), + Step::module('arrival.info'), + Step::module('guest.data_request'), + Step::point(Point::BeforeStay), + Step::module('stay'), + Step::module('review.request'), + Step::point(Point::BeforeSettlement), + Step::module('case.closure'), + Step::module('case.settlement'), + ]; + } +} diff --git a/app/Process/Models/ProcessModel.php b/app/Process/Models/ProcessModel.php index fe4f129..bda08c5 100644 --- a/app/Process/Models/ProcessModel.php +++ b/app/Process/Models/ProcessModel.php @@ -5,6 +5,8 @@ use App\Enums\CaseType; use App\Enums\IntakeKind; use App\Enums\ProcessSetting; +use App\Process\ProcessCatalogue; +use App\Process\Templates\TemplateArea; /** * A centrally defined, versioned process model (docs/Prozessarchitektur/Architektur/02 §5): its course of steps with @@ -74,17 +76,74 @@ public function variant(string $key): ?Variant } /** - * The modules of the course in order, with the variant's modules at their points. + * The function template areas this model offers a slot for (empty: the model's course is fixed). + * + * @return list + */ + public function slots(): array + { + return array_values(array_map(fn (Step $step): TemplateArea => $step->slot, array_filter($this->steps(), fn (Step $step): bool => $step->isSlot()))); + } + + /** + * The results the base course provides to the templates of its slots (see FunctionTemplate::requires()). * * @return list */ - public function modules(?string $variant = 'standard'): array + public static function providedResults(): array + { + return []; + } + + /** + * The template (key) every slot gets when none was chosen: area value => template key. + * + * @return array + */ + public static function defaultTemplates(): array + { + return []; + } + + /** + * Whether the model is kept for compatibility (existing channels and frozen plans) and no longer offered as a + * choice: its combination is a preset of a composable model. + */ + public static function isLegacy(): bool + { + return false; + } + + /** + * The template combination that reproduces this legacy model (area value => template key), or empty. + * + * @return array + */ + public static function presetTemplates(): array + { + return []; + } + + /** + * The modules of the course in order, with the variant's modules at their points and the chosen templates' modules + * at their slots. + * + * @param array $templates area value => template key or key@version (missing areas: the default) + * @return list + */ + public function modules(?string $variant = 'standard', array $templates = []): array { $chosen = $this->variant($variant ?? 'standard'); + $catalogue = app(ProcessCatalogue::class); $modules = []; foreach ($this->steps() as $step) { if ($step->isPoint()) { array_push($modules, ...($chosen?->modulesAt($step->point) ?? [])); + } elseif ($step->isSlot()) { + $reference = $templates[$step->slot->value] ?? static::defaultTemplates()[$step->slot->value] ?? null; + if ($reference !== null && ($class = $catalogue->templateClass($reference)) !== null) { + array_push($modules, ...$class::modules()); + } } else { $modules[] = $step->module; } diff --git a/app/Process/Models/Step.php b/app/Process/Models/Step.php index 9bf065f..14c1965 100644 --- a/app/Process/Models/Step.php +++ b/app/Process/Models/Step.php @@ -2,12 +2,15 @@ namespace App\Process\Models; +use App\Process\Templates\TemplateArea; + /** - * One entry of a model's course: a module or an extension point where variants insert modules. + * One entry of a model's course: a module, an extension point where variants insert modules, or a slot where the + * function template chosen for its area puts its modules. */ final readonly class Step { - private function __construct(public ?string $module, public ?Point $point) {} + private function __construct(public ?string $module, public ?Point $point, public ?TemplateArea $slot = null) {} public static function module(string $key): self { @@ -19,8 +22,18 @@ public static function point(Point $point): self return new self(null, $point); } + public static function slot(TemplateArea $area): self + { + return new self(null, null, $area); + } + public function isPoint(): bool { return $this->point !== null; } + + public function isSlot(): bool + { + return $this->slot !== null; + } } diff --git a/app/Process/ProcessCatalogue.php b/app/Process/ProcessCatalogue.php index 32bf0dc..5d5267f 100644 --- a/app/Process/ProcessCatalogue.php +++ b/app/Process/ProcessCatalogue.php @@ -7,6 +7,8 @@ use App\Process\Models\ProcessModel; use App\Process\Modules\ProcessModule; use App\Process\Modules\RunsAutomatically; +use App\Process\Templates\FunctionTemplate; +use App\Process\Templates\TemplateArea; use InvalidArgumentException; /** @@ -97,6 +99,53 @@ public function models(): array return $models; } + /** + * @return array>> + */ + public function templateVersions(): array + { + return (array) config('process.templates', []); + } + + /** + * The class of a template named by key (latest version) or key@version; null when it is not registered. + * + * @return class-string|null + */ + public function templateClass(string $reference): ?string + { + [$key, $version] = array_pad(explode('@', $reference, 2), 2, null); + $versions = $this->templateVersions()[$key] ?? []; + if ($versions === []) { + return null; + } + + return $versions[$version === null ? max(array_keys($versions)) : (int) $version] ?? null; + } + + public function hasTemplate(string $reference): bool + { + return $this->templateClass($reference) !== null; + } + + /** + * The latest version of every template, optionally of one area. + * + * @return array> + */ + public function templates(?TemplateArea $area = null): array + { + $templates = []; + foreach (array_keys($this->templateVersions()) as $key) { + $class = $this->templateClass($key); + if ($area === null || $class::area() === $area) { + $templates[$key] = $class; + } + } + + return $templates; + } + /** * The model a case follows when nobody chose one: derived from its frozen profile exactly as the v0.11 course * branched (legacy mapping, docs/Prozessarchitektur/Architektur/06 §4). @@ -151,12 +200,42 @@ public function problems(): array $problems[] = 'Zyklische harte Abhängigkeit: '.implode(' → ', $cycle); } + foreach ($this->templateVersions() as $key => $versions) { + foreach ($versions as $version => $class) { + if ($class::key() !== $key || $class::version() !== $version) { + $problems[] = "Schablone {$key}@{$version}: Klasse {$class} meldet ".$class::reference().'.'; + } + foreach ($class::modules() as $module) { + if (! $this->hasModule($module)) { + $problems[] = "Schablone {$class::reference()}: Modul {$module} ist nicht registriert."; + } + } + if (! in_array($class::area()->result(), $class::provides(), true)) { + $problems[] = "Schablone {$class::reference()}: liefert das Ergebnis ihres Bereichs ({$class::area()->result()}) nicht."; + } + if ($class::fixes() === [] || array_keys($class::fixes()) !== [$class::area()->setting()->value]) { + $problems[] = "Schablone {$class::reference()}: darf nur die Verantwortlichkeit ihres Bereichs festlegen."; + } + } + } + foreach ($this->modelVersions() as $key => $versions) { foreach ($versions as $version => $class) { if ($class::key() !== $key || $class::version() !== $version) { $problems[] = "Modell {$key}@{$version}: Klasse {$class} meldet ".$class::key().'@'.$class::version().'.'; } $model = app($class); + foreach ($model->slots() as $area) { + $default = $class::defaultTemplates()[$area->value] ?? null; + if ($default === null || ! $this->hasTemplate($default) || $this->templateClass($default)::area() !== $area) { + $problems[] = "Modell {$key}@{$version}: Platz {$area->value} hat keine gültige Standardschablone."; + } + } + foreach ($class::presetTemplates() as $area => $reference) { + if (! $this->hasTemplate($reference) || $this->templateClass($reference)::area()->value !== $area) { + $problems[] = "Modell {$key}@{$version}: Voreinstellung {$area} nennt die Schablone {$reference} nicht (richtig)."; + } + } foreach ($model->variants() as $variant) { foreach ($model->modules($variant->key) as $module) { if (! $this->hasModule($module)) { diff --git a/app/Process/ProcessPlan.php b/app/Process/ProcessPlan.php index e4aba86..a7a8ce2 100644 --- a/app/Process/ProcessPlan.php +++ b/app/Process/ProcessPlan.php @@ -6,6 +6,7 @@ use App\Models\Booking; use App\Models\Channel; use App\Process\Models\ProcessModel; +use App\Process\Templates\TemplateComposer; use DomainException; /** @@ -27,6 +28,7 @@ final class ProcessPlan * @param array $modules module key => frozen version * @param array}> $steps * @param array $labels module key => label at the time of freezing + * @param array $templates area => function template key@version the plan was composed with */ public function __construct( public readonly string $model, @@ -37,6 +39,7 @@ public function __construct( public readonly string $source = self::DERIVED, public readonly array $labels = [], public readonly ?string $notice = null, + public readonly array $templates = [], ) {} /** @@ -64,7 +67,7 @@ public static function derive(ProcessProfile $profile): self * Ablauf), when admissible for the case's type; otherwise the derived one with a notice. Tester-only variants or * modules are refused outside the process tester (decision E7). * - * @param array $configuration model, variant, steps of channels.process_overrides[intake] + * @param array $configuration model, variant, steps, templates of channels.process_overrides[intake] */ public static function freeze(ProcessProfile $profile, array $configuration, bool $sandbox = false): self { @@ -96,7 +99,16 @@ public static function freeze(ProcessProfile $profile, array $configuration, boo } } - return self::build($model, $variant, (array) ($configuration['steps'] ?? []), $sandbox ? self::TESTER : self::CONFIGURED); + $templates = []; + if ($model->slots() !== []) { + $composer = app(TemplateComposer::class); + $templates = $composer->resolve($model, (array) ($configuration['templates'] ?? [])); + if (($problems = $composer->problems($model, $templates, $variant)) !== []) { + return self::derive($profile)->withNotice("Schablonen von {$chosen} nicht zulässig (".implode(' ', $problems).') – abgeleitetes Modell verwendet.'); + } + } + + return self::build($model, $variant, (array) ($configuration['steps'] ?? []), $sandbox ? self::TESTER : self::CONFIGURED, $templates); } /** @@ -110,29 +122,30 @@ public static function configurationOf(?Channel $channel, IntakeKind $intake): a return []; } - return array_intersect_key((array) (($channel->process_overrides ?? [])[$intake->value] ?? []), array_flip(['model', 'variant', 'steps'])); + return array_intersect_key((array) (($channel->process_overrides ?? [])[$intake->value] ?? []), array_flip(['model', 'variant', 'steps', 'templates'])); } /** * @param array $steps + * @param array $templates area => key@version */ - private static function build(ProcessModel $model, string $variant, array $steps, string $source): self + private static function build(ProcessModel $model, string $variant, array $steps, string $source, array $templates = []): self { $catalogue = app(ProcessCatalogue::class); $modules = []; $labels = []; - foreach ($model->modules($variant) as $key) { + foreach ($model->modules($variant, $templates) as $key) { $class = $catalogue->modules()[$key]; $modules[$key] = $class::version(); $labels[$key] = $class::definition()->label; } - return new self($model::key(), $model::version(), $variant, $modules, array_intersect_key($steps, $modules), $source, $labels); + return new self($model::key(), $model::version(), $variant, $modules, array_intersect_key($steps, $modules), $source, $labels, null, $templates); } private function withNotice(string $notice): self { - return new self($this->model, $this->modelVersion, $this->variant, $this->modules, $this->steps, $this->source, $this->labels, $notice); + return new self($this->model, $this->modelVersion, $this->variant, $this->modules, $this->steps, $this->source, $this->labels, $notice, $this->templates); } public function modelDefinition(): ProcessModel @@ -204,6 +217,7 @@ public function toArray(): array 'source' => $this->source, 'labels' => $this->labels, 'notice' => $this->notice, + 'templates' => $this->templates === [] ? null : $this->templates, ], fn (mixed $value): bool => $value !== null); } @@ -221,6 +235,7 @@ public static function fromArray(array $data): self (string) ($data['source'] ?? self::DERIVED), (array) ($data['labels'] ?? []), isset($data['notice']) ? (string) $data['notice'] : null, + array_map('strval', (array) ($data['templates'] ?? [])), ); } } diff --git a/app/Process/ProcessProfile.php b/app/Process/ProcessProfile.php index 8e7ee69..d617576 100644 --- a/app/Process/ProcessProfile.php +++ b/app/Process/ProcessProfile.php @@ -32,6 +32,9 @@ final class ProcessProfile /** Fixed by the process model chosen for the channel (Architektur V2). */ public const MODEL = 'model'; + /** Fixed by a function template chosen for the channel (Schablonenkomposition). */ + public const TEMPLATE = 'template'; + /** Fixed by the case type (A6), not settable. */ public const CASE_TYPE = 'case_type'; @@ -53,7 +56,9 @@ public function __construct( /** * The case type of a constellation: internal occasions are A6; requests are A1 (own way) or A2 (intermediary); - * binding external bookings are A3–A5 by who handles documents and payments. + * binding external bookings are A3–A5 by who handles documents and payments. Only a classification (labels, reports, + * compatibility): the course follows the composed plan, and a combination without an archetype of its own – + * collection by us, contract documents by the portal – is classified A3 (we collect), never by a new case type. */ public static function caseTypeFor(IntakeKind $intake, bool $viaChannel, Responsibility $documents, Responsibility $payments): CaseType { @@ -61,7 +66,7 @@ public static function caseTypeFor(IntakeKind $intake, bool $viaChannel, Respons IntakeKind::Internal => CaseType::A6, IntakeKind::Inquiry => $viaChannel ? CaseType::A2 : CaseType::A1, IntakeKind::Booking => match (true) { - $documents === Responsibility::Portal => CaseType::A5, + $documents === Responsibility::Portal && $payments === Responsibility::Portal => CaseType::A5, $payments === Responsibility::Portal => CaseType::A4, default => CaseType::A3, }, @@ -193,6 +198,7 @@ public static function sourceLabel(string $source): string self::WEBSITE => 'Einstellung der eigenen Webseite', self::CASE_TYPE => 'fest für diese Vorgangsart', self::MODEL => 'festgelegt durch das gewählte Ablaufmodell', + self::TEMPLATE => 'festgelegt durch die gewählte Funktionsschablone', 'migration' => 'aus dem bisherigen Stand übernommen', default => 'Grundeinstellung', }; diff --git a/app/Process/ProcessSettings.php b/app/Process/ProcessSettings.php index 97b447c..59da17b 100644 --- a/app/Process/ProcessSettings.php +++ b/app/Process/ProcessSettings.php @@ -11,6 +11,8 @@ use App\Models\Property; use App\Models\Tenant; use App\Process\Models\ProcessModel; +use App\Process\Templates\FunctionTemplate; +use App\Process\Templates\TemplateComposer; /** * Resolves the effective process settings: built-in default → landlord default (tenant) → deviation of the property @@ -61,6 +63,14 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak } } + // Function templates chosen for the model's slots fix the responsibility of their area. + foreach ($this->chosenTemplates($channel, $intake, $model) as $class) { + foreach ($class::fixes() as $key => $fixed) { + $values[$key] = $fixed; + $sources[$key] = ProcessProfile::TEMPLATE; + } + } + if ($intake === IntakeKind::Internal) { // Own use, private stays and blocks (A6): no rental documents, no payment reminders, no guest mails – fixed by // the case type, not by a setting. @@ -80,6 +90,21 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak return new ProcessProfile($intake, ProcessProfile::caseTypeFor($intake, $channel?->isPortal() ?? false, $documents, $payments), $values, $sources); } + /** + * The function templates in force for the chosen model's slots (chosen ones, otherwise the model's defaults). + * + * @return array> + */ + private function chosenTemplates(?Channel $channel, IntakeKind $intake, ?ProcessModel $model): array + { + if ($model === null || $model->slots() === []) { + return []; + } + $composer = app(TemplateComposer::class); + + return $composer->classes($composer->resolve($model, (array) (ProcessPlan::configurationOf($channel, $intake)['templates'] ?? []))); + } + /** * The model chosen for the channel and intake kind (Kanal › Ablauf), when it is registered and fits the intake. */ diff --git a/app/Process/Templates/ExternalContractDocuments.php b/app/Process/Templates/ExternalContractDocuments.php new file mode 100644 index 0000000..7c83c10 --- /dev/null +++ b/app/Process/Templates/ExternalContractDocuments.php @@ -0,0 +1,68 @@ + true]; + } + + public static function provides(): array + { + return [TemplateArea::ContractDocuments->result(), 'contract.documents_by_portal']; + } + + public static function dimensions(): array + { + return [ + 'Vertragsbedingungen' => 'Das Portal verantwortet Abschluss und Bedingungen.', + 'Erstellung' => 'Durch das Portal.', + 'Bereitstellung / Versand' => 'Durch das Portal; wir senden keinen Vertrag. Die Buchungsinformation bleibt einzeln einstellbar.', + 'Nachweis' => 'Bestätigung des Portals (E-Mail oder Vermerk des Vermieters).', + ]; + } +} diff --git a/app/Process/Templates/FunctionTemplate.php b/app/Process/Templates/FunctionTemplate.php new file mode 100644 index 0000000..4ff82b8 --- /dev/null +++ b/app/Process/Templates/FunctionTemplate.php @@ -0,0 +1,112 @@ + + */ + abstract public static function modules(): array; + + /** Who answers for the result of the area. It becomes the value of the area's responsibility setting. */ + abstract public static function responsibility(): Responsibility; + + /** + * The portal capability that must hold for the template to fit: capability key => required value (the channel's + * confirmed capabilities decide; an unknown one is a hint, never taken as proven). + * + * @return array + */ + public static function capabilityRequirements(): array + { + return []; + } + + /** + * Results of the process this template needs (provided by the base process or another template). + * + * @return list + */ + public static function requires(): array + { + return []; + } + + /** + * Results this template provides. The result of its area is always among them. + * + * @return list + */ + public static function provides(): array + { + return [static::area()->result()]; + } + + /** + * Templates (keys) that must not be combined with this one, with the reason. + * + * @return array + */ + public static function incompatibleWith(): array + { + return []; + } + + /** + * What the template stands for along the business dimensions of its area (shown in the configurator): + * dimension label => statement. + * + * @return array + */ + public static function dimensions(): array + { + return []; + } + + /** + * Capabilities that are not built yet; they appear as extensions, never as promises. + * + * @return list + */ + public static function extensions(): array + { + return []; + } + + /** + * The settings the template fixes for the cases that follow it (setting key => value). + * + * @return array + */ + public static function fixes(): array + { + return [static::area()->setting()->value => static::responsibility()->value]; + } + + public static function reference(): string + { + return static::key().'@'.static::version(); + } +} diff --git a/app/Process/Templates/OwnCollection.php b/app/Process/Templates/OwnCollection.php new file mode 100644 index 0000000..132114b --- /dev/null +++ b/app/Process/Templates/OwnCollection.php @@ -0,0 +1,78 @@ + false]; + } + + public static function requires(): array + { + return ['binding.portal_total']; + } + + public static function provides(): array + { + return [TemplateArea::Collection->result(), 'money.guest_payments_monitored']; + } + + public static function dimensions(): array + { + return [ + 'Zahlungsplan' => 'Anzahlung und Restzahlung nach den Zahlungsfristen des Vermieters.', + 'Zahlungsanforderung' => 'Aufgabe vor Fälligkeit; Versand durch uns.', + 'Zahlungseingang' => 'Wir erfassen die Zahlungen des Gastes.', + 'Erinnerung' => 'Aufgabe mit Versand per Klick (nicht automatisch).', + 'Abschluss' => 'Kaufmännischer Abschluss mit tatsächlichen Nachweisen.', + ]; + } + + public static function extensions(): array + { + return ['Mehrstufige Mahnungen (rechtliche Ausgestaltung offen)', 'Bank-Abgleich der Zahlungseingänge']; + } +} diff --git a/app/Process/Templates/OwnContractDocumentation.php b/app/Process/Templates/OwnContractDocumentation.php new file mode 100644 index 0000000..4f5cb56 --- /dev/null +++ b/app/Process/Templates/OwnContractDocumentation.php @@ -0,0 +1,72 @@ + false]; + } + + public static function requires(): array + { + return ['guest.identified']; + } + + public static function provides(): array + { + return [TemplateArea::ContractDocuments->result(), 'contract.documents_by_us']; + } + + public static function dimensions(): array + { + return [ + 'Vertragsbedingungen' => 'Das Portal verantwortet den Vertragsabschluss; die Bedingungen der Unterlagen sind unsere.', + 'Erstellung' => 'Durch uns (Vorlage der Wohnung oder des Kanals).', + 'Bereitstellung / Versand' => 'Durch uns; automatisch, nach Freigabe oder von Hand, per E-Mail oder nur intern abgelegt.', + 'Nachweis' => 'Gespeichertes Dokument und Versandvermerk am Vorgang.', + ]; + } +} diff --git a/app/Process/Templates/PortalCollection.php b/app/Process/Templates/PortalCollection.php new file mode 100644 index 0000000..25dbf8f --- /dev/null +++ b/app/Process/Templates/PortalCollection.php @@ -0,0 +1,73 @@ + true]; + } + + public static function requires(): array + { + return ['binding.portal_total']; + } + + public static function provides(): array + { + return [TemplateArea::Collection->result(), 'money.portal_payout_checked']; + } + + public static function dimensions(): array + { + return [ + 'Zahlungsplan' => 'Beim Portal; wir zeigen nur „laut Portal“.', + 'Zahlungsanforderung' => 'Keine eigene gegenüber dem Gast.', + 'Zahlungseingang' => 'Angaben des Portals werden erfasst (kein Geld auf unserem Konto).', + 'Auszahlung' => 'Kontrolle gegen Nachweis; Differenzen werden bearbeitet.', + 'Abschluss' => 'Kaufmännischer Abschluss erst mit tatsächlichem Nachweis der Auszahlung.', + ]; + } +} diff --git a/app/Process/Templates/TemplateArea.php b/app/Process/Templates/TemplateArea.php new file mode 100644 index 0000000..1d716d0 --- /dev/null +++ b/app/Process/Templates/TemplateArea.php @@ -0,0 +1,49 @@ + 'Finanzabwicklung (Inkasso)', + self::ContractDocuments => 'Vertragsdokumentation', + }; + } + + public function question(): string + { + return match ($this) { + self::Collection => 'Wer zieht das Geld des Gastes ein?', + self::ContractDocuments => 'Wer stellt dem Gast die Vertragsunterlagen bereit?', + }; + } + + /** The process result every template of this area provides – exactly once per process. */ + public function result(): string + { + return match ($this) { + self::Collection => 'money.collection_handled', + self::ContractDocuments => 'contract.documented', + }; + } + + /** The responsibility setting the chosen template fixes. */ + public function setting(): ProcessSetting + { + return match ($this) { + self::Collection => ProcessSetting::Payments, + self::ContractDocuments => ProcessSetting::Documents, + }; + } +} diff --git a/app/Process/Templates/TemplateComposer.php b/app/Process/Templates/TemplateComposer.php new file mode 100644 index 0000000..2ffacba --- /dev/null +++ b/app/Process/Templates/TemplateComposer.php @@ -0,0 +1,192 @@ + $chosen area value => template key or key@version + * @return array area value => key@version + */ + public function resolve(ProcessModel $model, array $chosen): array + { + $resolved = []; + foreach ($model->slots() as $area) { + $reference = (string) ($chosen[$area->value] ?? $model::defaultTemplates()[$area->value] ?? ''); + $class = $reference === '' ? null : $this->catalogue->templateClass($reference); + $resolved[$area->value] = $class === null ? $reference : $class::reference(); + } + + return $resolved; + } + + /** + * The template classes behind a resolved combination (unknown references are left out). + * + * @param array $resolved + * @return array> + */ + public function classes(array $resolved): array + { + $classes = []; + foreach ($resolved as $area => $reference) { + if (($class = $this->catalogue->templateClass($reference)) !== null) { + $classes[$area] = $class; + } + } + + return $classes; + } + + /** + * @param array $chosen area value => template key or key@version + * @return list + */ + public function problems(ProcessModel $model, array $chosen, string $variant = 'standard'): array + { + $problems = []; + $slots = array_map(fn (TemplateArea $area): string => $area->value, $model->slots()); + foreach (array_keys($chosen) as $area) { + if (! in_array($area, $slots, true)) { + $problems[] = 'Das Modell „'.$model::label().'“ hat keinen Platz für „'.$area.'“.'; + } + } + if ($slots === []) { + return $problems; + } + + $resolved = $this->resolve($model, array_intersect_key($chosen, array_flip($slots))); + $classes = []; + foreach ($resolved as $area => $reference) { + $class = $this->catalogue->templateClass($reference); + if ($class === null) { + $problems[] = 'Die Schablone „'.$reference.'“ gibt es nicht.'; + + continue; + } + if ($class::area()->value !== $area) { + $problems[] = 'Die Schablone „'.$class::label().'“ gehört zu „'.$class::area()->label().'“, nicht zu „'.TemplateArea::from($area)->label().'“.'; + + continue; + } + $classes[$area] = $class; + } + + $problems = [...$problems, ...$this->resultProblems($model, $classes), ...$this->pairProblems($classes), ...$this->planProblems($model, $classes, $variant)]; + + return array_values(array_unique($problems)); + } + + /** + * Prerequisites and double effects at the level of business results. + * + * @param array> $classes + * @return list + */ + private function resultProblems(ProcessModel $model, array $classes): array + { + $problems = []; + $providers = []; + foreach ($model::providedResults() as $result) { + $providers[$result][] = 'der Basisprozess'; + } + foreach ($classes as $class) { + foreach ($class::provides() as $result) { + $providers[$result][] = '„'.$class::label().'“'; + } + } + foreach ($providers as $result => $by) { + if (count($by) > 1) { + $problems[] = 'Das Ergebnis „'.$result.'“ würde doppelt erzeugt: '.implode(' und ', $by).'.'; + } + } + foreach ($classes as $class) { + foreach ($class::requires() as $needed) { + if (! isset($providers[$needed])) { + $problems[] = '„'.$class::label().'“ setzt das Ergebnis „'.$needed.'“ voraus, das in dieser Kombination niemand liefert.'; + } + } + } + + return $problems; + } + + /** + * Mutually exclusive templates and contradictory responsibilities. + * + * @param array> $classes + * @return list + */ + private function pairProblems(array $classes): array + { + $problems = []; + $fixed = []; + foreach ($classes as $class) { + foreach ($class::incompatibleWith() as $other => $reason) { + if (collect($classes)->contains(fn (string $chosen): bool => $chosen::key() === $other)) { + $problems[] = '„'.$class::label().'“ und „'.$this->catalogue->templateClass($other)::label().'“ lassen sich nicht kombinieren: '.$reason; + } + } + foreach ($class::fixes() as $setting => $value) { + if (isset($fixed[$setting]) && $fixed[$setting]['value'] !== $value) { + $problems[] = 'Widersprüchliche Verantwortlichkeit ('.$setting.'): „'.$fixed[$setting]['by'].'“ und „'.$class::label().'“ legen Unterschiedliches fest.'; + } + $fixed[$setting] = ['value' => $value, 'by' => $class::label()]; + } + } + + return $problems; + } + + /** + * What the composed course needs from the modules: no module twice, and a hard dependency on a module that one of the + * templates of this model's slots would have supplied must be in the plan. + * + * @param array> $classes + * @return list + */ + private function planProblems(ProcessModel $model, array $classes, string $variant): array + { + $problems = []; + $modules = $model->modules($variant, array_map(fn (string $class): string => $class::reference(), $classes)); + foreach (array_count_values($modules) as $module => $count) { + if ($count > 1) { + $problems[] = 'Das Modul „'.$module.'“ wäre mehrfach im Ablauf.'; + } + } + + $templateOwned = []; + foreach ($model->slots() as $area) { + foreach ($this->catalogue->templates($area) as $class) { + array_push($templateOwned, ...$class::modules()); + } + } + foreach (array_unique($modules) as $key) { + if (! $this->catalogue->hasModule($key)) { + $problems[] = 'Das Modul „'.$key.'“ ist nicht registriert.'; + + continue; + } + foreach ($this->catalogue->modules()[$key]::definition()->requires as $dependency) { + if ($dependency->hard && ! in_array($dependency->module, $modules, true) && in_array($dependency->module, $templateOwned, true)) { + $problems[] = 'Das Modul „'.$key.'“ braucht zwingend „'.$dependency->module.'“, das in dieser Kombination fehlt.'; + } + } + } + + return $problems; + } +} diff --git a/app/Process/Tester/SandboxSnapshot.php b/app/Process/Tester/SandboxSnapshot.php index dd78a71..d90bde1 100644 --- a/app/Process/Tester/SandboxSnapshot.php +++ b/app/Process/Tester/SandboxSnapshot.php @@ -63,7 +63,7 @@ public static function build(Channel $channel, IntakeKind $intake, array $draft) 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'] ?? [])]; + $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'] ?? []), 'templates' => (array) ($draft['templates'] ?? [])]; $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. diff --git a/config/process.php b/config/process.php index f775e5f..eea93aa 100644 --- a/config/process.php +++ b/config/process.php @@ -8,6 +8,7 @@ use App\Process\Modules\Offer; use App\Process\Modules\Settlement; use App\Process\Modules\Stay; +use App\Process\Templates; /* |-------------------------------------------------------------------------- @@ -72,5 +73,18 @@ 'a4.portal_booking' => [1 => Models\A4PortalBookingModelV1::class, 2 => Models\A4PortalBookingModel::class], 'a5.portal_booking' => [1 => Models\A5PortalBookingModelV1::class, 2 => Models\A5PortalBookingModel::class], 'a6.internal' => [1 => Models\A6InternalModel::class], + // Base process with slots for function templates; A3–A5 above are its presets (compatibility). + 'external.booking' => [1 => Models\ExternalBookingModel::class], + ], + + /* + | Function templates (docs/Prozessarchitektur/SCHABLONEN.md): versioned combinations of the modules above for the slots + | of a model. A plan freezes the template versions it was built with. + */ + 'templates' => [ + 'collection.own' => [1 => Templates\OwnCollection::class], + 'collection.portal' => [1 => Templates\PortalCollection::class], + 'contract_docs.own' => [1 => Templates\OwnContractDocumentation::class], + 'contract_docs.external' => [1 => Templates\ExternalContractDocuments::class], ], ]; diff --git a/tests/Feature/Process/ChannelCapabilityTest.php b/tests/Feature/Process/ChannelCapabilityTest.php index 811537d..58850a5 100644 --- a/tests/Feature/Process/ChannelCapabilityTest.php +++ b/tests/Feature/Process/ChannelCapabilityTest.php @@ -244,7 +244,7 @@ public function test_unknown_capabilities_block_nothing_but_ask_for_confirmation $options = app(ChannelProcessConfiguration::class)->modelOptions($generic, IntakeKind::Booking); - $this->assertSame(['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking'], array_keys(array_filter($options, fn (array $option): bool => $option['admissible']))); + $this->assertSame(['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking', 'external.booking'], array_keys(array_filter($options, fn (array $option): bool => $option['admissible']))); $this->assertNotSame([], $options['a4.portal_booking']['hints']); } diff --git a/tests/Feature/Process/ChannelProcessConfiguratorTest.php b/tests/Feature/Process/ChannelProcessConfiguratorTest.php index 17090e1..a1262e1 100644 --- a/tests/Feature/Process/ChannelProcessConfiguratorTest.php +++ b/tests/Feature/Process/ChannelProcessConfiguratorTest.php @@ -72,15 +72,15 @@ public function test_only_admissible_models_per_channel_and_intake_are_offered() $website = Channel::websiteOf($this->property); $this->assertSame(['a2.offer', 'a2.information'], array_keys($configuration->admissibleModels($fewo, IntakeKind::Inquiry))); - $this->assertSame(['a4.portal_booking'], array_keys($configuration->admissibleModels($fewo, IntakeKind::Booking)), 'O2: FeWo-direkt bookings only A4 for now'); - $this->assertSame(['a3.portal_booking'], array_keys($configuration->admissibleModels($ds, IntakeKind::Booking))); + $this->assertSame(['a4.portal_booking', 'external.booking'], array_keys($configuration->admissibleModels($fewo, IntakeKind::Booking)), 'O2: of the archetypes only A4 fits FeWo-direkt; the base process is open and restricts per template'); + $this->assertSame(['a3.portal_booking', 'external.booking'], array_keys($configuration->admissibleModels($ds, IntakeKind::Booking))); $this->assertSame([IntakeKind::Booking], $configuration->intakes($ds)); $this->assertSame(['a2.offer', 'a2.information'], array_keys($configuration->admissibleModels($listing, IntakeKind::Inquiry))); $this->assertSame(['a1.offer', 'a1.information'], array_keys($configuration->admissibleModels($website, IntakeKind::Inquiry))); // The restriction lives in the channel profile, not in the process core: a changed profile releases more models. $fewo->update(['settings' => [...(array) $fewo->settings, 'portal_profile' => 'generic']]); - $this->assertSame(['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking'], array_keys($configuration->admissibleModels($fewo->fresh(), IntakeKind::Booking))); + $this->assertSame(['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking', 'external.booking'], array_keys($configuration->admissibleModels($fewo->fresh(), IntakeKind::Booking))); $this->expectException(ValidationException::class); app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, ['model' => 'a4.portal_booking']); diff --git a/tests/Feature/Process/TemplateCompositionTest.php b/tests/Feature/Process/TemplateCompositionTest.php new file mode 100644 index 0000000..feff81d --- /dev/null +++ b/tests/Feature/Process/TemplateCompositionTest.php @@ -0,0 +1,518 @@ +travelTo(CarbonImmutable::parse('2026-10-23 18:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Storage::fake('local'); + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + config(['mail.default' => 'array']); + Mail::swap(new MailManager($this->app)); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org']); + Http::preventStrayRequests(); + } + + /** + * @return array collection, documents, classification, whether the payout check is part of the course + */ + public static function combinations(): array + { + return [ + 'own collection + own documents (A3)' => ['collection.own', 'contract_docs.own', CaseType::A3, false], + 'portal collection + own documents (A4)' => ['collection.portal', 'contract_docs.own', CaseType::A4, true], + 'portal collection + external documents (A5)' => ['collection.portal', 'contract_docs.external', CaseType::A5, true], + 'own collection + external documents (no archetype)' => ['collection.own', 'contract_docs.external', CaseType::A3, false], + ]; + } + + public function test_the_catalogue_with_templates_is_consistent(): void + { + $this->assertSame([], app(ProcessCatalogue::class)->problems()); + } + + #[DataProvider('combinations')] + public function test_every_combination_is_composed_into_a_valid_versioned_plan(string $collection, string $documents, CaseType $type, bool $payout): void + { + $model = app(ProcessCatalogue::class)->model('external.booking'); + $chosen = ['collection' => $collection, 'contract_documents' => $documents]; + + $this->assertSame([], app(TemplateComposer::class)->problems($model, $chosen)); + + $channel = $this->configured($chosen); + $booking = $this->takeOver($channel, 'COMBO'); + $plan = ProcessPlan::of($booking); + + $this->assertSame(['external.booking', 1], [$plan->model, $plan->modelVersion]); + $this->assertEquals(['collection' => $collection.'@1', 'contract_documents' => $documents.'@1'], $plan->templates); + $this->assertSame($payout, array_key_exists('portal.payout', $plan->modules)); + $this->assertArrayHasKey('payments.monitor', $plan->modules); + $this->assertArrayHasKey('documents.send', $plan->modules); + $this->assertSame($type, $booking->case_type, 'the case type is only a classification'); + $this->assertNull($plan->notice); + } + + public function test_the_fourth_combination_collects_ourselves_while_the_portal_provides_the_documents(): void + { + $booking = $this->takeOver($this->configured(['collection' => 'collection.own', 'contract_documents' => 'contract_docs.external']), 'VIER'); + $profile = $booking->process(); + + $this->assertSame([Responsibility::Landlord, Responsibility::Portal], [$profile->payments(), $profile->documents()]); + $this->assertSame(ProcessProfile::TEMPLATE, $profile->source(ProcessSetting::Payments)); + $this->assertSame(ProcessProfile::TEMPLATE, $profile->source(ProcessSetting::Documents)); + + $activities = collect(CaseActivities::for($booking))->keyBy('key'); + $this->assertNotSame(ActivityState::External, $activities['payment']->state, 'we monitor the guest payments ourselves'); + $this->assertStringNotContainsString('Portal', $activities['payment']->label, 'no portal collection shown'); + $this->assertNull($activities['payout'] ?? null, 'no payout check without portal collection'); + $this->assertNull($booking->fresh()->confirmation_sent_at, 'the portal provides the contract documents: we send none'); + } + + #[DataProvider('archetypes')] + public function test_a_combination_behaves_like_the_archetype_it_reproduces(string $legacy, string $collection, string $documents): void + { + $old = $this->takeOver($this->legacyChannel($legacy), 'ALT', '2027-07-10'); + $new = $this->takeOver($this->configured(['collection' => $collection, 'contract_documents' => $documents]), 'NEU', '2027-08-10'); + + $oldValues = $old->process()->values; + $newValues = $new->process()->values; + unset($oldValues['contract_template_id'], $newValues['contract_template_id']); + $this->assertEquals($oldValues, $newValues, 'identical effective configuration'); + $this->assertSame($old->case_type, $new->case_type); + + $summarise = fn (Booking $booking): array => collect(CaseActivities::for($booking))->map(fn ($activity): array => [$activity->key, $activity->label, $activity->state->value])->all(); + $this->assertSame($summarise($old), $summarise($new), 'identical activities and states'); + + $oldModules = array_keys(ProcessPlan::of($old)->modules); + $newModules = array_keys(ProcessPlan::of($new)->modules); + $this->assertSame(array_values(array_diff($oldModules, $legacy === 'a3.portal_booking' ? ['portal.payout'] : [])), $newModules, 'the course is the archetype course (the payout check only where the portal collects)'); + } + + /** + * @return array + */ + public static function archetypes(): array + { + return [ + 'A3' => ['a3.portal_booking', 'collection.own', 'contract_docs.own'], + 'A4' => ['a4.portal_booking', 'collection.portal', 'contract_docs.own'], + 'A5' => ['a5.portal_booking', 'collection.portal', 'contract_docs.external'], + ]; + } + + public function test_the_archetypes_are_presets_of_the_base_process(): void + { + $catalogue = app(ProcessCatalogue::class); + foreach (['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking'] as $key) { + $model = $catalogue->model($key); + $this->assertTrue($model::isLegacy()); + $this->assertSame([], app(TemplateComposer::class)->problems($catalogue->model('external.booking'), $model::presetTemplates())); + } + $this->assertFalse(ExternalBookingModel::isLegacy()); + } + + public function test_unsuitable_combinations_are_refused_with_a_reason(): void + { + $composer = app(TemplateComposer::class); + $model = app(ProcessCatalogue::class)->model('external.booking'); + + $this->assertStringContainsString('gehört zu', implode(' ', $composer->problems($model, ['collection' => 'contract_docs.own'])), 'a template only fits the slot of its area'); + $this->assertStringContainsString('gibt es nicht', implode(' ', $composer->problems($model, ['collection' => 'collection.gibt-es-nicht']))); + $this->assertStringContainsString('keinen Platz', implode(' ', $composer->problems($model, ['gastronomie' => 'collection.own']))); + } + + public function test_double_effects_missing_prerequisites_contradictions_and_exclusions_are_detected(): void + { + $this->register(DoubleCollectionTemplate::class, NeedyDocumentsTemplate::class, ContradictingDocumentsTemplate::class, ExcludingDocumentsTemplate::class, DuplicateModuleTemplate::class); + $composer = app(TemplateComposer::class); + $model = app(ProcessCatalogue::class)->model('external.booking'); + $problems = fn (array $chosen): string => implode(' | ', $composer->problems($model, $chosen)); + + $this->assertStringContainsString('doppelt erzeugt', $problems(['contract_documents' => DoubleCollectionTemplate::key()]), 'the collection result may come from one template only'); + $this->assertStringContainsString('voraus', $problems(['contract_documents' => NeedyDocumentsTemplate::key()])); + $this->assertStringContainsString('Widersprüchliche Verantwortlichkeit', $problems(['contract_documents' => ContradictingDocumentsTemplate::key()])); + $this->assertStringContainsString('nicht kombinieren', $problems(['collection' => 'collection.portal', 'contract_documents' => ExcludingDocumentsTemplate::key()])); + $this->assertSame('', $problems(['collection' => 'collection.own', 'contract_documents' => ExcludingDocumentsTemplate::key()]), 'the exclusion only concerns portal collection'); + $this->assertStringContainsString('mehrfach', $problems(['collection' => DuplicateModuleTemplate::key()])); + } + + public function test_a_hard_dependency_on_a_module_the_templates_would_have_supplied_is_unmet(): void + { + config(['process.models' => [...config('process.models'), 'test.model' => [1 => ModelWithDependentStep::class]]]); + $this->register(SuppliesStayTemplate::class); + $model = app(ProcessCatalogue::class)->model('test.model'); + + $this->assertStringContainsString('braucht zwingend', implode(' ', app(TemplateComposer::class)->problems($model, ['collection' => 'collection.own']))); + $this->assertSame([], app(TemplateComposer::class)->problems($model, ['collection' => SuppliesStayTemplate::key()])); + } + + public function test_a_new_template_version_applies_to_new_cases_only_and_old_plans_stay_readable(): void + { + $channel = $this->configured(['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own']); + $first = $this->takeOver($channel, 'V1'); + + config(['process.templates' => [...config('process.templates'), 'collection.own' => [1 => OwnCollection::class, 2 => OwnCollectionVersion2::class]]]); + $second = $this->takeOver($channel->fresh(), 'V2', '2027-08-10'); + + $this->assertSame('collection.own@1', ProcessPlan::of($first->fresh())->templates['collection']); + $this->assertSame('collection.own@2', ProcessPlan::of($second)->templates['collection']); + $this->assertSame($first->profile['plan'], $first->fresh()->profile['plan'], 'the running case keeps its frozen plan'); + + $legacy = ProcessPlan::fromArray(['model' => 'a3.portal_booking', 'model_version' => 2, 'modules' => ['intake.record' => 1]]); + $this->assertSame([], $legacy->templates, 'plans frozen before the composition have no templates'); + } + + public function test_the_unsaved_choice_shows_in_the_preview_with_the_template_of_each_step(): void + { + $channel = $this->channel('Test Portal'); + $rows = collect(app(ChannelProcessConfiguration::class)->preview($channel, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.external']])); + + $this->assertSame('Portal-Inkasso', $rows->firstWhere('module', 'portal.payout')['template']); + $this->assertSame('Externe Vertragsunterlagen', $rows->firstWhere('module', 'documents.send')['template']); + $this->assertNull($rows->firstWhere('module', 'stay')['template']); + } + + public function test_the_base_process_cannot_be_saved_with_templates_the_portal_cannot_support(): void + { + $channel = $this->channel('FeWo-direkt Test'); + $configure = app(ConfigureChannelProcess::class); + $draft = ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own'], 'capabilities' => ['collects_payment' => '1', 'provides_contract_documents' => '0']]; + + try { + $configure->handle($channel, IntakeKind::Booking, $draft); + $this->fail('own collection although the portal collects'); + } catch (ValidationException $exception) { + $this->assertStringContainsString('Zieht das Portal das Geld', implode(' ', $exception->errors()['process'])); + } + $this->assertNull(($channel->fresh()->process_overrides ?? [])['booking'] ?? null, 'nothing saved'); + + $configure->handle($channel, IntakeKind::Booking, [...$draft, 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']]); + $this->assertEquals(['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own'], $channel->fresh()->process_overrides['booking']['templates']); + } + + /** + * @param array $templates + */ + private function configured(array $templates): Channel + { + $channel = $this->channel('Vergleichsportal', suffix: md5(json_encode($templates))); + app(ConfigureChannelProcess::class)->handle($channel, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => $templates]); + + return $channel->fresh(); + } + + /** + * @param class-string ...$classes + */ + private function register(string ...$classes): void + { + $templates = config('process.templates'); + foreach ($classes as $class) { + $templates[$class::key()] = [1 => $class]; + } + config(['process.templates' => $templates]); + } + + private function legacyChannel(string $model): Channel + { + $channel = $this->channel('Vergleichsportal', suffix: 'alt'); + app(ConfigureChannelProcess::class)->handle($channel, IntakeKind::Booking, ['model' => $model]); + + return $channel->fresh(); + } + + private function takeOver(Channel $channel, string $reference, string $arrival = '2027-07-10'): Booking + { + $arrival = CarbonImmutable::parse($arrival); + + return app(TakeOverExternalBooking::class)->handle($this->property, $channel, $arrival, $arrival->addDays(7), ['portal_reference' => $reference]); + } + + private function channel(string $name, string $suffix = ''): Channel + { + return Channel::factory()->for($this->property)->create(['name' => $name, 'booking_model' => 'portal_booking', 'import_enabled' => false, 'settings' => ['import_url' => 'https://portal.example/'.md5($name.$suffix).'.ics', 'portal_profile' => 'generic']]); + } +} + +/** Test doubles: templates and a model that exist only to provoke the composition checks. */ +abstract class TestTemplate extends FunctionTemplate +{ + public static function version(): int + { + return 1; + } + + public static function key(): string + { + return 'test.'.strtolower(substr(strrchr(static::class, '\\'), 1)); + } + + public static function purpose(): string + { + return 'Testschablone'; + } + + public static function label(): string + { + return static::key(); + } +} + +final class DoubleCollectionTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::ContractDocuments; + } + + public static function modules(): array + { + return ['documents.send']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } + + public static function provides(): array + { + return [TemplateArea::ContractDocuments->result(), TemplateArea::Collection->result()]; + } +} + +final class NeedyDocumentsTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::ContractDocuments; + } + + public static function modules(): array + { + return ['documents.send']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } + + public static function requires(): array + { + return ['signature.qualified']; + } +} + +final class ContradictingDocumentsTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::ContractDocuments; + } + + public static function modules(): array + { + return ['documents.send']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } + + public static function fixes(): array + { + return ['documents' => 'landlord', 'payments' => 'portal']; + } +} + +final class ExcludingDocumentsTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::ContractDocuments; + } + + public static function modules(): array + { + return ['documents.send']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } + + public static function incompatibleWith(): array + { + return ['collection.portal' => 'Beide würden die Auszahlung dokumentieren.']; + } +} + +final class DuplicateModuleTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::Collection; + } + + public static function modules(): array + { + return ['payments.monitor', 'documents.send']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } +} + +final class SuppliesStayTemplate extends TestTemplate +{ + public static function area(): TemplateArea + { + return TemplateArea::Collection; + } + + public static function modules(): array + { + return ['stay']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } +} + +final class OwnCollectionVersion2 extends TestTemplate +{ + public static function key(): string + { + return 'collection.own'; + } + + public static function version(): int + { + return 2; + } + + public static function area(): TemplateArea + { + return TemplateArea::Collection; + } + + public static function modules(): array + { + return ['payments.monitor']; + } + + public static function responsibility(): Responsibility + { + return Responsibility::Landlord; + } +} + +/** A model whose review step needs the stay, which a collection template may supply. */ +final class ModelWithDependentStep extends ProcessModel +{ + public static function key(): string + { + return 'test.model'; + } + + public static function version(): int + { + return 1; + } + + public static function label(): string + { + return 'Testmodell'; + } + + public static function description(): string + { + return ''; + } + + public static function caseTypes(): array + { + return [CaseType::A3]; + } + + public static function intakes(): array + { + return [IntakeKind::Booking]; + } + + public static function responsibilities(): Responsibilities + { + return Responsibilities::of(fixed: []); + } + + public static function defaultTemplates(): array + { + return ['collection' => 'collection.own']; + } + + public function steps(): array + { + return [Step::module('intake.record'), Step::slot(TemplateArea::Collection), Step::module('review.request')]; + } +}