diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index 0d254d5..415afc3 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -16,6 +16,8 @@ use App\Pricing\CaseMoney; use App\Process\CaseActivities; use App\Process\CaseAutomation; +use App\Process\ProcessCatalogue; +use App\Process\ProcessPlan; use App\Process\ProcessProfile; use App\Support\Money; use Carbon\CarbonImmutable; @@ -121,6 +123,7 @@ public static function configure(Schema $schema): Schema ->schema([ TextEntry::make('status')->label('Status')->badge(), TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()), + TextEntry::make('templates')->label('Funktionsschablonen')->state(fn (Booking $record): ?string => self::templates($record))->placeholder('– (fester Ablauf)'), TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'), TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(), TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(), @@ -238,6 +241,17 @@ private static function history(Booking $booking): HtmlString return new HtmlString($rows === '' ? 'Noch keine Einträge.' : ''); } + /** + * The function templates the case was composed with, as frozen in its plan (null for the fixed models). + */ + private static function templates(Booking $record): ?string + { + $catalogue = app(ProcessCatalogue::class); + $labels = array_map(fn (string $reference): string => ($class = $catalogue->templateClass($reference)) !== null ? $class::label().' ('.$reference.')' : $reference, ProcessPlan::of($record)->templates); + + return $labels === [] ? null : implode(' · ', $labels); + } + private static function profile(Booking $booking): HtmlString { $profile = $booking->process(); diff --git a/app/Filament/Resources/Channels/Pages/ChannelProcess.php b/app/Filament/Resources/Channels/Pages/ChannelProcess.php index f624b1e..02fc8cb 100644 --- a/app/Filament/Resources/Channels/Pages/ChannelProcess.php +++ b/app/Filament/Resources/Channels/Pages/ChannelProcess.php @@ -15,11 +15,14 @@ use App\Process\ChannelCapabilities; use App\Process\ChannelProcessConfiguration; use App\Process\ConfigurationImpact; +use App\Process\Models\ExternalBookingModel; use App\Process\Models\ProcessModel; use App\Process\ProcessCatalogue; use App\Process\ProcessProfile; use App\Process\ProcessSettings; use App\Process\Restriction; +use App\Process\Templates\FunctionTemplate; +use App\Process\Templates\TemplateArea; use Filament\Actions\Action; use Filament\Notifications\Notification; use Filament\Resources\Pages\Concerns\InteractsWithRecord; @@ -46,7 +49,7 @@ class ChannelProcess extends Page public string $intake = 'inquiry'; - /** @var array, settings: array}> */ + /** @var array, settings: array, templates: array}> */ public array $drafts = []; /** @var array capability key => '1' | '0' | '' (unknown); saving confirms what is shown */ @@ -69,6 +72,7 @@ public function mount(int|string $record): void 'model' => $model, 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), + 'templates' => (array) ($stored['templates'] ?? []), 'settings' => array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, array_intersect_key($stored, array_flip(array_map(fn (ProcessSetting $setting): string => $setting->value, ProcessSetting::cases())))), 'derived' => $current['derived'], ]; @@ -140,7 +144,124 @@ public function models(): array */ public function conflicts(): array { - return app(ChannelProcessConfiguration::class)->conflicts($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]['model']); + return app(ChannelProcessConfiguration::class)->conflicts($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]['model'], $this->drafts[$this->intake]['templates']); + } + + /** + * The models offered as a choice: the archetypes A3–A5 are presets of the base process, so they only appear while one + * of them is the current choice (then with the hint to move to the templates). + * + * @param array, hints: list}> $models + * @return array, hints: list}> + */ + public function visibleModels(array $models): array + { + return array_filter($models, fn (array $option, string $key): bool => ! $option['model']::isLegacy() || $key === $this->drafts[$this->intake]['model'], ARRAY_FILTER_USE_BOTH); + } + + /** + * Whether the chosen model composes function templates (otherwise its course is fixed). + */ + public function composable(): bool + { + return $this->model()->slots() !== []; + } + + /** + * The business decisions of the chosen base process: per slot the templates with fit, selection and what each stands + * for. The first view of the configurator; the single steps stay below. + * + * @return list, admissible: bool, selected: bool, restrictions: list, hints: list, unconfirmed: list, modules: list}>}> + */ + public function decisions(): array + { + $model = $this->model(); + if ($model->slots() === []) { + return []; + } + $configuration = app(ChannelProcessConfiguration::class); + $catalogue = app(ProcessCatalogue::class); + $resolved = $configuration->templatesOf($model, $this->draft()); + $options = $configuration->templateOptions($this->record, $model, $this->capabilityDraft); + $decisions = []; + foreach ($model->slots() as $area) { + $selected = isset($resolved[$area->value]) ? explode('@', $resolved[$area->value])[0] : null; + $decisions[] = [ + 'area' => $area, + 'selected' => $selected, + 'options' => array_values(array_map(fn (array $option, string $key): array => [ + ...$option, + 'key' => $key, + 'selected' => $key === $selected, + 'modules' => array_map(fn (string $module): string => $catalogue->modules()[$module]::definition()->label, $option['template']::modules()), + ], $options[$area->value] ?? [], array_keys($options[$area->value] ?? []))), + ]; + } + + return $decisions; + } + + /** + * The archetypes as known combinations (presets) the landlord can start from. + * + * @return array}> + */ + public function presets(): array + { + $presets = []; + foreach (app(ProcessCatalogue::class)->models() as $key => $candidate) { + if ($candidate::isLegacy() && in_array(IntakeKind::from($this->intake), $candidate::intakes(), true)) { + $presets[$key] = ['label' => $candidate::label(), 'templates' => $candidate::presetTemplates()]; + } + } + + return $presets; + } + + /** + * Chooses the template of an area. Switches of steps that drop out of the course are removed from the draft; the + * consequences are listed by templateImpacts() before anything is saved. + */ + public function chooseTemplate(string $area, string $key): void + { + $model = $this->model(); + $option = app(ChannelProcessConfiguration::class)->templateOptions($this->record, $model, $this->capabilityDraft)[$area][$key] ?? null; + if ($option === null || ! $option['admissible']) { + return; + } + $this->acknowledge = false; + $this->drafts[$this->intake]['templates'] = [...app(ChannelProcessConfiguration::class)->templatesOf($model, $this->draft()), $area => $key]; + $this->drafts[$this->intake]['templates'] = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->drafts[$this->intake]['templates']); + $modules = $model->modules($this->drafts[$this->intake]['variant'], $this->drafts[$this->intake]['templates']); + $this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($modules)); + } + + /** + * Moves from a fixed archetype to the base process with the combination the archetype stands for. Switches and settings + * stay as they are; what contradicts the templates shows as a conflict that has to be confirmed. + */ + public function applyPreset(string $archetype): void + { + $presets = $this->presets(); + $base = app(ProcessCatalogue::class)->model(ExternalBookingModel::key()); + if (! isset($presets[$archetype]) || ! in_array(IntakeKind::from($this->intake), $base::intakes(), true)) { + return; + } + $this->acknowledge = false; + $this->drafts[$this->intake]['model'] = $base::key(); + $this->drafts[$this->intake]['variant'] = 'standard'; + $this->drafts[$this->intake]['templates'] = $presets[$archetype]['templates']; + $this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($base->modules('standard', $presets[$archetype]['templates']))); + } + + /** + * What the draft's change of templates means (modules, responsibilities, stored switches and settings). + * + * @return list> + */ + public function templateImpacts(): array + { + return app(ConfigurationImpact::class)->ofTemplates($this->record, IntakeKind::from($this->intake), $this->draft()); } public function chooseModel(string $model): void @@ -149,9 +270,13 @@ public function chooseModel(string $model): void return; } $this->acknowledge = false; + // Leaving an archetype for a model with slots keeps its combination as the starting point of the templates. + $previous = app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']); $this->drafts[$this->intake]['model'] = $model; $this->drafts[$this->intake]['variant'] = 'standard'; - $this->drafts[$this->intake]['steps'] = []; + $this->drafts[$this->intake]['templates'] = $this->model()->slots() === [] ? [] : $previous::presetTemplates(); + // Switches of steps the new course still has stay; only those that have no counterpart there drop out. + $this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($this->model()->modules('standard', $this->drafts[$this->intake]['templates']))); } public function model(): ProcessModel diff --git a/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php b/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php index f149275..a1f449a 100644 --- a/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php +++ b/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php @@ -67,7 +67,7 @@ public function mount(int|string $record): void if ($this->draft === []) { $current = app(ChannelProcessConfiguration::class)->current($this->record, IntakeKind::from($this->intake)); $stored = (array) (($this->record->process_overrides ?? [])[$this->intake] ?? []); - $this->draft = ['model' => $current['model'], 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), 'settings' => []]; + $this->draft = ['model' => $current['model'], 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), 'templates' => $current['templates'], 'settings' => []]; } $this->scenario = (string) array_key_first($this->scenarios()); $this->resetInputs(); diff --git a/app/Process/ChannelProcessConfiguration.php b/app/Process/ChannelProcessConfiguration.php index 98c8055..f322fbb 100644 --- a/app/Process/ChannelProcessConfiguration.php +++ b/app/Process/ChannelProcessConfiguration.php @@ -11,6 +11,7 @@ use App\Enums\ProcessSetting; use App\Enums\Responsibility; use App\Models\Channel; +use App\Process\Models\ExternalBookingModel; use App\Process\Models\ProcessModel; use App\Process\Models\Responsibilities; use App\Process\Templates\FunctionTemplate; @@ -181,6 +182,24 @@ public function templateOptions(Channel $channel, ProcessModel $model, ?array $c return $options; } + /** + * The templates in force for new cases of the channel and intake kind (key@version per area): the saved choice of a + * model with slots, otherwise the combination a legacy archetype reproduces (empty when there is none). + * + * @return array + */ + public function currentTemplates(Channel $channel, IntakeKind $intake): array + { + $current = $this->current($channel, $intake); + $model = $this->catalogue->model($current['model']); + + if ($model->slots() !== []) { + return $this->composer->resolve($model, $current['templates']); + } + + return $model::presetTemplates() === [] ? [] : $this->composer->resolve($this->catalogue->model(ExternalBookingModel::key()), $model::presetTemplates()); + } + /** * The templates a draft uses for the model slots (chosen ones, otherwise the model defaults) as key@version. * @@ -239,6 +258,14 @@ public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey 'text' => $setting->question().' Bisher eingestellt: „'.$setting->describe($value).'“. Das Modell „'.$modelKey.'“ erlaubt: „'.$allowed.'“.']; } + // A model with slots does not narrow the guest communication itself: the portal's capability does. + $messages = $model->slots() === [] ? null : (app(ChannelCapabilities::class)->resolve($channel)[ChannelCapabilities::MESSAGES_GUEST] ?? null); + $storedMessages = ProcessSetting::GuestMessages->normalize($stored[ProcessSetting::GuestMessages->value] ?? null); + if ($messages !== null && $messages->isKnown() && $messages->value === false && $storedMessages === Responsibility::Portal->value) { + $conflicts[] = ['setting' => ProcessSetting::GuestMessages, 'stored' => ProcessSetting::GuestMessages->describe($storedMessages), 'fixed' => ProcessSetting::GuestMessages->describe(Responsibility::Landlord->value), + 'text' => ProcessSetting::GuestMessages->question().' Bisher eingestellt: „'.ProcessSetting::GuestMessages->describe($storedMessages).'“. Laut Fähigkeit des Portals schreibt es den Gast aber nicht an; künftig: „'.ProcessSetting::GuestMessages->describe(Responsibility::Landlord->value).'“.']; + } + return $conflicts; } diff --git a/app/Process/ConfigurationImpact.php b/app/Process/ConfigurationImpact.php index 3080e57..190ad19 100644 --- a/app/Process/ConfigurationImpact.php +++ b/app/Process/ConfigurationImpact.php @@ -6,6 +6,7 @@ use App\Enums\IntakeKind; use App\Models\Channel; use App\Process\Modules\ModuleDefinition; +use App\Process\Templates\TemplateComposer; /** * Rule-based comparison of a configuration draft (docs/Prozessarchitektur/MODUL_KONFIGURATIONSMATRIX.md §5): for every @@ -15,7 +16,7 @@ */ final class ConfigurationImpact { - public function __construct(private ProcessCatalogue $catalogue, private ChannelProcessConfiguration $configuration) {} + public function __construct(private ProcessCatalogue $catalogue, private ChannelProcessConfiguration $configuration, private TemplateComposer $composer) {} /** * @param array $draft @@ -61,6 +62,63 @@ public function of(Channel $channel, IntakeKind $intake, array $draft): array return $impacts; } + /** + * What a change of function templates means (docs/Prozessarchitektur/SCHABLONEN.md): per changed area the modules that + * drop out, join or stay, the responsibility that changes, the stored switches and settings that no longer apply and + * what the new template still needs or does not build yet. Compared with the templates in force for new cases. Pure: + * nothing is changed, nothing is dropped silently – the landlord sees every consequence before saving. + * + * @param array $draft + * @return list, added: list, kept: list, responsibility: ?array{from: string, to: string}, switches_lost: list, settings_replaced: list, needs: list, extensions: list}> + */ + public function ofTemplates(Channel $channel, IntakeKind $intake, array $draft): array + { + $model = $this->catalogue->model((string) ($draft['model'] ?? '')); + if ($model->slots() === []) { + return []; + } + $current = $this->configuration->currentTemplates($channel, $intake); + $target = $this->composer->resolve($model, (array) ($draft['templates'] ?? [])); + $stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []); + $labelOf = fn (string $module): string => ($this->catalogue->hasModule($module) ? $this->catalogue->modules()[$module]::definition()->label : $module); + $impacts = []; + + foreach ($model->slots() as $area) { + $from = $current[$area->value] ?? null; + $to = $target[$area->value] ?? null; + $toClass = $to === null ? null : $this->catalogue->templateClass($to); + if ($toClass === null || $from === $to) { + continue; + } + $fromClass = $from === null ? null : $this->catalogue->templateClass($from); + $before = $fromClass === null ? [] : $fromClass::modules(); + $after = $toClass::modules(); + $removed = array_values(array_diff($before, $after)); + $setting = $area->setting(); + $storedValue = $setting->normalize($stored[$setting->value] ?? null); + + $impacts[] = [ + 'area' => $area->label(), + 'from' => $fromClass === null ? null : $fromClass::label(), + 'to' => $toClass::label(), + 'removed' => array_map($labelOf, $removed), + 'added' => array_map($labelOf, array_values(array_diff($after, $before))), + 'kept' => array_map($labelOf, array_values(array_intersect($after, $before))), + 'responsibility' => $fromClass !== null && $fromClass::responsibility() !== $toClass::responsibility() + ? ['from' => $setting->describe($fromClass::responsibility()->value), 'to' => $setting->describe($toClass::responsibility()->value)] + : null, + 'switches_lost' => array_map($labelOf, array_values(array_filter($removed, fn (string $module): bool => ($stored['steps'][$module]['on'] ?? true) === false))), + 'settings_replaced' => $storedValue !== null && (string) $storedValue !== $toClass::responsibility()->value + ? [$setting->question().' Bisher gespeichert: „'.$setting->describe($storedValue).'“, künftig durch die Schablone: „'.$setting->describe($toClass::responsibility()->value).'“. Der gespeicherte Wert muss beim Speichern ausdrücklich entfernt werden.'] + : [], + 'needs' => array_map(fn (string $result): string => 'Voraussetzung: '.$result, $toClass::requires()), + 'extensions' => $toClass::extensions(), + ]; + } + + return $impacts; + } + /** * The results that stay necessary although the step is off: what the steps depending on it still need. * diff --git a/app/Process/Tester/ProcessSandboxDriver.php b/app/Process/Tester/ProcessSandboxDriver.php index 465fb5c..cd260d1 100644 --- a/app/Process/Tester/ProcessSandboxDriver.php +++ b/app/Process/Tester/ProcessSandboxDriver.php @@ -8,8 +8,10 @@ use App\Models\Channel; use App\Models\Property; use App\Models\Tenant; +use App\Process\Capability; use App\Process\CaseActivities; use App\Process\CaseContext; +use App\Process\ChannelCapabilities; use App\Process\ProcessCatalogue; use App\Process\ProcessPlan; use App\Process\ProcessProfile; @@ -37,6 +39,9 @@ final class ProcessSandboxDriver private int $ledgerSeen = 0; + /** @var list 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 = []; @@ -98,7 +103,7 @@ public function run(array $input): array 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), + '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(), @@ -122,7 +127,7 @@ private function assertSandbox(): void /** * @return array */ - private function plan(Booking $booking): array + private function plan(Booking $booking, Channel $channel): array { $plan = ProcessPlan::of($booking); $profile = $booking->process(); @@ -134,10 +139,49 @@ private function plan(Booking $booking): array '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. * @@ -172,9 +216,18 @@ private function capture(SandboxContext $context): array } } + $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], diff --git a/docs/Prozessarchitektur/SCHABLONEN.md b/docs/Prozessarchitektur/SCHABLONEN.md new file mode 100644 index 0000000..b6f9848 --- /dev/null +++ b/docs/Prozessarchitektur/SCHABLONEN.md @@ -0,0 +1,64 @@ +# Funktionsschablonen und Basisprozess „Extern verbindliche Portalbuchung“ + +Stand: 05.11.2026 · Branch `feature/schablonenkomposition` · kurze technische Umsetzungsgrundlage, keine neue Architekturstudie. + +## 1. Prinzip + +Der Basisprozess bleibt (P01–P05, `ProcessRunner`, Moduldefinitionen, harte/weiche Abhängigkeiten). Neu ist nur: + +- **Platz (Slot)** im Modell (`Step::slot(TemplateArea)`), an dem die gewählte **Funktionsschablone** ihre bereits vorhandenen Module einsetzt. +- **Schablone** (`App\Process\Templates\FunctionTemplate`, versioniert, in `config/process.php › templates`): Zweck, Module, benötigte/gelieferte Ergebnisse, Verantwortlichkeit, Portal-Fähigkeit, Ausschlüsse, Dimensionen, noch nicht gebaute Erweiterungen. +- **`TemplateComposer`** (rein lesend): löst die Wahl auf, prüft Plätze/Bereiche, Voraussetzungen, doppelte Ergebnisse, Ausschlüsse, widersprüchliche Verantwortlichkeiten, doppelte Module und harte Modulabhängigkeiten. Keine Regelsprache, keine zweite Engine. +- Der **Plan** (`ProcessPlan`) friert Schablonen mit Version ein (`bookings.profile.plan.templates`, optional – alte Pläne bleiben lesbar). Die Schablone legt die Verantwortlichkeit ihres Bereichs fest (`ProcessSettings`, Quelle `template`); alle anderen Parameter laufen weiter über Systemstandard → Vermieter → Wohnung → Kanal × Eingangsart → eingefroren. +- `CaseType` A1–A6 bleibt **abgeleitete Klassifikation** (Berichte, Altfälle). Die vierte Kombination (eigenes Inkasso + externe Unterlagen) wird als A3 klassifiziert („wir kassieren“); es gibt kein A7. + +## 2. Zuordnung: bisheriger Funktionsblock → Module → Schablone + +| Funktionsblock (Prozesslandkarte) | Module | Zuordnung | +|---|---|---| +| Eingang, Gastangaben, Verbindlichkeit beim Portal, Bestätigung abwarten, Kalender sperren | `intake.record`, `guest.details`, `binding.portal`, `portal.confirmation`, `channels.block` | fester Bestandteil des Basisprozesses | +| Datenbeschaffung | `guest.data_request` | fest, Ausführung am Modul wählbar (automatisch/Freigabe/von Hand/nicht erforderlich) – eigene Schablone erst bei echten Alternativen | +| **Vertragsdokumentation** | `documents.send`, `documents.booking_notice` | **Schablonen** `contract_docs.own` / `contract_docs.external` | +| **Finanzabwicklung** | `payments.monitor` (+ `portal.payout`) | **Schablonen** `collection.own` (Zahlungsüberwachung) / `collection.portal` (Portalzahlungen + Auszahlungskontrolle) | +| Aufgaben, Änderungen | `case.tasks`, `change.proposal` | fest (ereignisgesteuert) | +| Anreise, Aufenthalt, Bewertung | `arrival.details`, `arrival.info`, `stay`, `review.request` | fest, Absender am Modul wählbar (Gastkommunikation) | +| Abschluss | `case.closure`, `case.settlement` | fest (Pflicht, Nachweise nach O5) | +| Angebot/Annahme (A1/A2), interne Belegung (A6), Tester-Module | `offer.*`, `hold`, `availability.check`, `payments.internal`, `documents.stay_confirmation`, `guest.*`/`pricing.*` (Tester) | nicht Teil dieses Umbaus; spätere Schablonen nutzen dasselbe Prinzip | + +Es wurden bewusst **nur zwei Bereiche** zu Schablonen: dort liegen die unterschiedlichen Verantwortlichkeiten. Module wurden nicht zusammengefasst. + +## 3. Die vier Schablonen + +| Schablone | Module | Verantwortung | Portal-Fähigkeit | Liefert | Braucht | +|---|---|---|---|---|---| +| `collection.own@1` Eigenes Inkasso | `payments.monitor` | wir | Portal zieht **nicht** ein | `money.collection_handled`, `money.guest_payments_monitored` | `binding.portal_total` | +| `collection.portal@1` Portal-Inkasso | `payments.monitor`, `portal.payout` | Portal | Portal zieht ein | `money.collection_handled`, `money.portal_payout_checked` | `binding.portal_total` | +| `contract_docs.own@1` Eigene Vertragsdokumentation | `documents.send`, `documents.booking_notice` | wir | Portal stellt **keine** Unterlagen bereit | `contract.documented`, `contract.documents_by_us` | `guest.identified` | +| `contract_docs.external@1` Externe Vertragsunterlagen | dieselben Module | Portal | Portal stellt Unterlagen bereit | `contract.documented`, `contract.documents_by_portal` | – | + +Die Schablonen der Dokumente unterscheiden sich nicht in den Modulen, sondern in **Verantwortung, Ausführungsart (Portal statt wir) und Nachweis** (§4.2 des Auftrags): Vertragsbedingungen – Erstellung – Bereitstellung/Versand – Nachweis stehen als `dimensions()` an der Schablone; Erstellung, Ablage, Bereitstellung und Versand bleiben am Modul einzeln einstellbar (`processing`, `contract_delivery`, Vorlage). Was die Unterlagen des Portals über Zahlungen sagen, ändert nichts an der Zahlungsüberwachung: sie folgt allein der Finanzschablone. + +## 4. Die vier Pflichtkombinationen + +| # | Inkasso | Dokumente | Klassifikation | Entspricht | +|---|---|---|---|---| +| 1 | eigenes | eigene | A3 | A3 v2 | +| 2 | Portal | eigene | A4 | A4 v2 | +| 3 | Portal | externe | A5 | A5 v2 | +| 4 | eigenes | externe | A3 | – (bisher nicht darstellbar) | + +`TemplateCompositionTest` beweist: Kombinationen 1–3 haben dasselbe wirksame Profil, dieselben Aktivitäten/Zustände und denselben Ablauf wie A3–A5 (nur `portal.payout` entfällt, wo wir selbst kassieren). `TemplateProcessTesterTest` spielt alle vier im isolierten Prozess-Tester durch. + +## 5. Unbestätigte Portal-Fähigkeiten + +Die Schablonenwahl prüft die **bestätigten** Fähigkeiten des Kanals. Widerspruch → Schablone nicht wählbar, mit Begründung und Weg. Unbekannt oder nur vorgeschlagen/abgeleitet → nicht gesperrt, aber überall als „nicht bestätigt“ gekennzeichnet (Konfigurator, Tester-Bericht); sie gilt nie als nachgewiesen. + +## 6. Umgang mit A3–A5 + +`external.booking@1` ist der Basisprozess für neue Konfigurationen. A3/A4/A5 (v1/v2) bleiben registriert (eingefrorene Pläne, Altkanäle) und sind im Konfigurator **Voreinstellungen** („Auf Schablonen umstellen“ / „Bekannte Kombinationen“). Gespeicherte Kanäle ändern sich nicht, bis jemand ausdrücklich speichert. `ProcessCatalogue::derivedModel` und die Altfall-Ableitung bleiben unverändert. + +## 7. Bewusste Grenzen / offen + +- Mahnstufen, Zahlungsplan je Kanal, Bank-Abgleich: Erweiterungen (`OwnCollection::extensions()`), nicht erfunden. +- Weitere Bereiche (Gastkommunikation, Datenbeschaffung, Aufenthalt) nutzen später dasselbe Prinzip (`TemplateArea` um einen Fall und einen Platz im Modell erweitern). +- A1/A2 und A6 haben noch keine Plätze. diff --git a/docs/STATUS.md b/docs/STATUS.md index f26ec74..c6d4a7e 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,15 @@ # Projektstand +## Nachtrag (05.11.2026): Schablonenkomposition für extern verbindliche Buchungen + +**Branch `feature/schablonenkomposition`** – Details, Zuordnung und Grenzen: [SCHABLONEN.md](Prozessarchitektur/SCHABLONEN.md). + +- Basisprozess `external.booking@1` mit Plätzen für **Finanzabwicklung** (`collection.own` / `collection.portal`) und **Vertragsdokumentation** (`contract_docs.own` / `contract_docs.external`). Alle vier Kombinationen laufen im Prozesskern und im Prozess-Tester; die vierte (eigenes Inkasso + externe Unterlagen) war mit A3–A5 nicht darstellbar. +- A3–A5 bleiben als Voreinstellungen/Altfassungen erhalten (Äquivalenz mit den Archetypen ist getestet); `CaseType` ist nur noch Klassifikation, kein A7. +- Der Plan friert die Schablonenversionen ein; laufende Vorgänge und Altpläne bleiben unverändert. Keine Migration. +- Kanalkonfigurator: Geschäftsentscheidungen zuerst, Einzelschritte eingeklappt, Auswirkungsanalyse beim Schablonenwechsel, Konflikte (A4→A3-Fall) bleiben bestätigungspflichtig. Tester-Bericht nennt Schablonen, unabhängig laufende Schritte, fehlende Nachweise und nicht bestätigte Portal-Fähigkeiten. +- Offen: Bereitstellung auf `develop`/stommer.info (siehe Abschnitt unten, sobald erfolgt). + ## Nachtrag (05.11.2026): Konfigurierbarkeit der Fachmodule - **Speicherkonflikt behoben:** Ein bestätigter Wechsel A4 → A3 (Destination Solutions mit `payments = portal`) scheiterte an „Inkasso … nicht zulässig“, weil der Entwurf den Altwert vor der bestätigten Entfernung gegen das neue Modell prüfte; nicht mehr erlaubte variable Verantwortlichkeiten zählten zudem nicht als Konflikt. Jetzt: `ChannelProcessConfiguration::conflicts()` + `withoutOverriddenSettings()`, Regressionstests in `ChannelCapabilityTest`. diff --git a/resources/views/filament/resources/channels/channel-process-test.blade.php b/resources/views/filament/resources/channels/channel-process-test.blade.php index 4564c5d..a087e6b 100644 --- a/resources/views/filament/resources/channels/channel-process-test.blade.php +++ b/resources/views/filament/resources/channels/channel-process-test.blade.php @@ -65,6 +65,20 @@ @endif @if ($plan = $report['plan'] ?? null)

{{ $plan['label'] }} ({{ $plan['model'] }} Version {{ $plan['version'] }}{{ $plan['variant'] !== 'standard' ? ', Variante '.$plan['variant'] : '' }}) · Vorgangsart {{ $plan['case_type'] }}

+ @if (($plan['templates'] ?? []) !== []) +
+ Verwendete Funktionsschablonen +
    + @foreach ($plan['templates'] as $template) +
  • {{ $template['area'] }}: {{ $template['label'] }} ({{ $template['reference'] }}, Verantwortung: {{ $template['responsibility'] }}; Schritte: {{ implode(', ', $template['modules']) }}) + @foreach ($template['capabilities'] as $capability) +
    Voraussetzung „{{ $capability['label'] }}“ = {{ $capability['required'] }} – {{ $capability['confirmed'] ? 'bestätigt' : 'NICHT bestätigt, wird nicht als nachgewiesen behandelt' }} ({{ $capability['source'] }})
    + @endforeach +
  • + @endforeach +
+
+ @endif
Wirksame Einstellungen
    @foreach ($plan['configuration'] as $row)
  • {{ $row['question'] }}: {{ $row['value'] }} ({{ $row['source'] }})
  • @endforeach @@ -77,6 +91,12 @@
    {{ $index + 1 }}. {{ $event['label'] }}{{ $event['at'] }} (simuliert)
    @if ($event['error'])

    Fehler: {{ $event['error'] }}

    @endif @isset($event['situation'])

    {{ $event['status'] }} · {{ $event['situation'] }}

    @endisset + @if (($event['independent'] ?? []) !== []) +

    Läuft unabhängig weiter, obwohl anderes wartet: {{ implode(', ', $event['independent']) }}

    + @endif + @if (($event['waiting'] ?? []) !== []) +

    Wartet / Nachweis fehlt: {{ implode(', ', $event['waiting']) }}

    + @endif
      @foreach ($event['activities'] as $activity)
    • {{ $activity['state'] }} – {{ $activity['label'] }}@if ($activity['detail']) · {{ $activity['detail'] }}@endif
    • diff --git a/resources/views/filament/resources/channels/channel-process.blade.php b/resources/views/filament/resources/channels/channel-process.blade.php index e6c3c51..f1dc860 100644 --- a/resources/views/filament/resources/channels/channel-process.blade.php +++ b/resources/views/filament/resources/channels/channel-process.blade.php @@ -10,6 +10,7 @@ $model = $this->model(); $steps = $this->steps(); $problems = $this->problems(); + $composable = $this->composable(); @endphp @if (count($this->tabs()) > 1) @@ -42,7 +43,7 @@

      Für diese Eingangsart gibt es keine Ablaufmodelle.

      @endif
      - @foreach ($models as $key => $option) + @foreach ($this->visibleModels($models) as $key => $option) @php($candidate = $option['model'])
      @endforeach
      @@ -83,6 +88,58 @@ @endif + @if ($composable) + @php($decisions = $this->decisions()) + + @if (($presets = $this->presets()) !== []) +
      Bekannte Kombinationen als Ausgangspunkt: + @foreach ($presets as $archetype => $preset) + + @endforeach +
      + @endif + @foreach ($decisions as $decision) +

      {{ $decision['area']->label() }} – {{ $decision['area']->question() }}

      +
      + @foreach ($decision['options'] as $option) + @php($template = $option['template']) +
      + +
        + @foreach ($template::dimensions() as $dimension => $statement)
      • {{ $dimension }}: {{ $statement }}
      • @endforeach +
      +
      Schritte: {{ implode(', ', $option['modules']) }}@if ($template::extensions() !== []) · noch nicht vorhanden: {{ implode('; ', $template::extensions()) }}@endif
      + @foreach ($option['restrictions'] as $restriction) +

      Passt gerade nicht ({{ $restriction->kind }}): {{ $restriction->reason }}@if ($restriction->alternative)
      Zulässig ist stattdessen: {{ $restriction->alternative }}.@endif @if ($restriction->change)
      {{ $restriction->change }}.@endif

      + @endforeach + @foreach ($option['hints'] as $hint)

      {{ $hint }}

      @endforeach +
      + @endforeach +
      + @endforeach +
      + + @if ($templateImpacts = $this->templateImpacts()) + + @foreach ($templateImpacts as $impact) +
      + {{ $impact['area'] }}: {{ $impact['from'] ?? 'bisher keine Schablone' }} → {{ $impact['to'] }} + @if ($impact['responsibility'])
      Verantwortung: {{ $impact['responsibility']['from'] }} → {{ $impact['responsibility']['to'] }}
      @endif + @if ($impact['removed'] !== [])
      Entfällt: {{ implode(', ', $impact['removed']) }}
      @endif + @if ($impact['added'] !== [])
      Kommt hinzu: {{ implode(', ', $impact['added']) }}
      @endif + @if ($impact['kept'] !== [])
      Bleibt mit allen Einstellungen: {{ implode(', ', $impact['kept']) }}
      @endif + @foreach ($impact['switches_lost'] as $lost)
      Ihr gespeicherter Schalter für „{{ $lost }}“ hat dann keinen Bezug mehr.
      @endforeach + @foreach ($impact['settings_replaced'] as $text)
      {{ $text }}
      @endforeach + @foreach ($impact['needs'] as $need)
      {{ $need }}
      @endforeach +
      + @endforeach +
      + @endif + @endif + @if ($problems !== [])
        @@ -104,7 +161,8 @@ @endif
        -
        +
        + Einzelschritte einstellen ({{ count($steps) }} Schritte) @foreach (collect($steps)->groupBy('phase') as $phase => $group)

        {{ $phases[$phase] ?? $phase }}

        @foreach ($group as $index => $step) @@ -113,6 +171,7 @@ {{ $step['label'] }} @if ($step['tester_only']) · nur im Prozess-Tester@endif @if ($step['inserted']) · Zusatzschritt der Variante@endif + @if ($step['template'] ?? null) · Schablone: {{ $step['template'] }}@endif @if ($step['optional']) @@ -173,7 +232,7 @@
        @endforeach @endforeach -
        +
    diff --git a/tests/Feature/Process/TemplateConfiguratorTest.php b/tests/Feature/Process/TemplateConfiguratorTest.php new file mode 100644 index 0000000..8eddfb8 --- /dev/null +++ b/tests/Feature/Process/TemplateConfiguratorTest.php @@ -0,0 +1,236 @@ +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(); + $this->actingAs(User::factory()->create()); + } + + public function test_the_page_shows_the_business_decisions_first_and_keeps_the_steps_reachable(): void + { + $ds = $this->channel('Destination Solution', []); + + Livewire::test(ChannelProcess::class, ['record' => $ds->getRouteKey()]) + ->call('chooseModel', 'external.booking') + ->assertSee('Geschäftsentscheidungen') + ->assertSee('Wer zieht das Geld des Gastes ein?') + ->assertSee('Eigenes Inkasso') + ->assertSee('Portal-Inkasso') + ->assertSee('Eigene Vertragsdokumentation') + ->assertSee('Externe Vertragsunterlagen') + ->assertSee('Mehrstufige Mahnungen', escape: false) + ->assertSee('Einzelschritte einstellen') + ->assertSee('Zahlungen des Gastes'); + } + + public function test_an_archetype_moves_to_the_base_process_with_the_same_combination_and_saves(): void + { + $fewo = $this->channel('FeWo-direkt', [], 'mixed'); + $page = Livewire::test(ChannelProcess::class, ['record' => $fewo->getRouteKey()])->set('intake', 'booking'); + + $page->assertSee('Auf Schablonen umstellen')->call('applyPreset', 'a4.portal_booking'); + $this->assertSame(['external.booking', ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']], [$page->get('drafts')['booking']['model'], $page->get('drafts')['booking']['templates']]); + $this->assertSame([], $page->instance()->problems()); + + $page->call('save')->assertNotified('Ablauf gespeichert'); + $this->assertSame('external.booking', $fewo->fresh()->process_overrides['booking']['model']); + $this->assertEquals(['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own'], $fewo->fresh()->process_overrides['booking']['templates']); + + $booking = $this->takeOver($fewo->fresh(), 'FD-1'); + $this->assertEquals(['collection' => 'collection.portal@1', 'contract_documents' => 'contract_docs.own@1'], ProcessPlan::of($booking)->templates); + $this->assertSame('A4', strtoupper($booking->case_type->value)); + } + + public function test_a_template_the_portal_cannot_support_cannot_be_chosen_and_says_why(): void + { + $fewo = $this->channel('FeWo-direkt', [], 'mixed'); + $page = Livewire::test(ChannelProcess::class, ['record' => $fewo->getRouteKey()])->set('intake', 'booking')->call('applyPreset', 'a4.portal_booking'); + + $page->call('chooseTemplate', 'collection', 'collection.own'); + $this->assertSame('collection.portal', $page->get('drafts')['booking']['templates']['collection'], 'refused: FeWo-direkt collects the money'); + $page->assertSee('Passt gerade nicht')->assertSee('Zieht das Portal das Geld des Gastes ein?'); + + // The landlord corrects the capability first: now the template fits. + $page->set('capabilityDraft.collects_payment', '0')->call('chooseTemplate', 'collection', 'collection.own'); + $this->assertSame('collection.own', $page->get('drafts')['booking']['templates']['collection']); + } + + public function test_unconfirmed_capabilities_are_flagged_and_never_taken_as_proven(): void + { + $generic = $this->channel('Irgendein Portal', [], 'portal_booking'); + $options = app(ChannelProcessConfiguration::class)->templateOptions($generic, app(ProcessCatalogue::class)->model('external.booking')); + + $this->assertTrue($options['collection']['collection.own']['admissible'], 'unknown blocks nothing'); + $this->assertSame(['collects_payment'], $options['collection']['collection.own']['unconfirmed']); + $this->assertNotSame([], $options['contract_documents']['contract_docs.external']['hints']); + + $fewo = $this->channel('FeWo-direkt Profil', [], 'mixed'); + $suggested = app(ChannelProcessConfiguration::class)->templateOptions($fewo, app(ProcessCatalogue::class)->model('external.booking')); + $this->assertContains('collects_payment', $suggested['collection']['collection.portal']['unconfirmed'], 'a suggestion of the channel profile is not a confirmation'); + $this->assertStringContainsString('nicht als bestätigt', implode(' ', $suggested['collection']['collection.portal']['hints'])); + } + + /** The A4 → A3 regression of the archetypes, now as a switch of the collection template */ + public function test_switching_the_collection_template_shows_every_consequence_and_needs_the_confirmation(): void + { + $ds = $this->channel('Destination Solution', ['booking' => ['payments' => 'portal', 'guest_messages' => 'portal', 'contract_delivery' => 'manual', 'steps' => ['review.request' => ['on' => false]]]]); + $ds->update(['settings' => [...(array) $ds->settings, 'capabilities' => ['messages_guest' => ['value' => false, 'at' => now()->toIso8601String(), 'by' => 'Lars']]]]); + $page = Livewire::test(ChannelProcess::class, ['record' => $ds->getRouteKey()])->set('intake', 'booking'); + + $page->set('capabilityDraft.collects_payment', '0')->call('chooseModel', 'external.booking')->call('chooseTemplate', 'collection', 'collection.own'); + $conflicts = collect($page->instance()->conflicts())->map(fn (array $conflict): string => $conflict['setting']->value)->all(); + $this->assertEqualsCanonicalizing(['payments', 'guest_messages'], $conflicts, 'the stale collection and the stale portal communication are conflicts, not silent changes'); + $page->assertSee('Bisherige Einstellungen widersprechen'); + + $page->call('save')->assertNotified('Nicht gespeichert'); + $this->assertSame('portal', $ds->fresh()->process_overrides['booking']['payments'], 'nothing changed without the confirmation'); + + $page->set('acknowledge', true)->call('save')->assertNotified('Ablauf gespeichert'); + $saved = $ds->fresh()->process_overrides['booking']; + $this->assertSame('external.booking', $saved['model']); + $this->assertArrayNotHasKey('payments', $saved); + $this->assertArrayNotHasKey('guest_messages', $saved); + $this->assertSame('manual', $saved['contract_delivery'], 'parameters of the kept modules survive'); + $this->assertSame(['review.request' => ['on' => false]], $saved['steps'], 'so does a switched-off optional step'); + $this->assertStringContainsString('Bisher eingestellt', $ds->fresh()->settings['process_history'][0]['removed_settings'][0]); + $this->assertEquals(['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own'], $saved['templates']); + } + + public function test_the_impact_of_a_template_change_names_modules_responsibility_and_open_ends(): void + { + $fewo = $this->channel('FeWo-direkt', ['booking' => ['steps' => []]], 'mixed'); + app(ConfigureChannelProcess::class)->handle($fewo, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']]); + + $impact = app(ConfigurationImpact::class)->ofTemplates($fewo->fresh(), IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.external']]); + + $impact = collect($impact)->keyBy('area'); + $this->assertEqualsCanonicalizing(['Finanzabwicklung (Inkasso)', 'Vertragsdokumentation'], $impact->keys()->all()); + $finance = $impact['Finanzabwicklung (Inkasso)']; + $documents = $impact['Vertragsdokumentation']; + $this->assertSame(['Portal-Inkasso', 'Eigenes Inkasso'], [$finance['from'], $finance['to']]); + $this->assertSame(['Auszahlung des Portals'], $finance['removed']); + $this->assertSame(['Zahlungen des Gastes'], $finance['kept']); + $this->assertSame(['from' => 'Das Portal', 'to' => 'Wir'], $finance['responsibility']); + $this->assertContains('Mehrstufige Mahnungen (rechtliche Ausgestaltung offen)', $finance['extensions']); + $this->assertSame(['from' => 'Wir', 'to' => 'Das Portal'], $documents['responsibility']); + $this->assertSame([], app(ConfigurationImpact::class)->ofTemplates($fewo->fresh(), IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']]), 'no change, no impact'); + } + + public function test_the_modules_of_a_template_stay_individually_configurable_and_the_inheritance_holds(): void + { + Settings::tenant()->update(['process_defaults' => ['contract_delivery' => 'manual']]); + $ds = $this->channel('Destination Solution', []); + app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own']]); + + $page = Livewire::test(ChannelProcess::class, ['record' => $ds->fresh()->getRouteKey()])->set('intake', 'booking'); + $documents = collect($page->instance()->steps())->firstWhere('module', 'documents.send'); + $this->assertSame('Eigene Vertragsdokumentation', $documents['template']); + $this->assertContains('contract_delivery', array_column($documents['parameters'], 'key'), 'the module of the template has its own parameters'); + $this->assertNotNull($documents['mode_setting'], 'and its own mode'); + $this->assertSame('manual', app(ProcessSettings::class)->resolve($this->property, $ds->fresh(), IntakeKind::Booking)->value(ProcessSetting::ContractDelivery)); + $this->assertSame(ProcessProfile::TENANT, app(ProcessSettings::class)->resolve($this->property, $ds->fresh(), IntakeKind::Booking)->source(ProcessSetting::ContractDelivery)); + + $page->set('drafts.booking.settings.contract_delivery', 'automatic')->set('drafts.booking.settings.processing', 'approval')->call('save')->assertNotified('Ablauf gespeichert'); + $profile = app(ProcessSettings::class)->resolve($this->property, $ds->fresh(), IntakeKind::Booking); + $this->assertSame(['automatic', ProcessProfile::CHANNEL], [$profile->value(ProcessSetting::ContractDelivery), $profile->source(ProcessSetting::ContractDelivery)]); + $this->assertSame(ProcessProfile::TEMPLATE, $profile->source(ProcessSetting::Payments)); + } + + public function test_a_template_does_not_override_a_parameter_set_by_hand_and_a_contradicting_responsibility_is_refused(): void + { + $ds = $this->channel('Destination Solution', []); + $configuration = app(ChannelProcessConfiguration::class); + + $problems = $configuration->problems($ds, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own'], 'settings' => ['payments' => 'portal']]); + $this->assertNotSame([], $problems, 'a responsibility set by hand may not contradict the template'); + $this->assertStringContainsString('widerspricht der Schablone', implode(' ', $problems)); + $this->assertSame([], $configuration->problems($ds, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own'], 'settings' => ['payments' => 'landlord', 'contract_delivery' => 'manual']])); + + $this->expectException(ValidationException::class); + app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own'], 'settings' => ['payments' => 'portal']]); + } + + public function test_changing_the_templates_leaves_running_cases_and_their_plans_untouched(): void + { + $ds = $this->channel('Destination Solution', []); + app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own']]); + $running = $this->takeOver($ds->fresh(), 'DS-ALT'); + $frozen = $running->fresh()->profile; + + app(ConfigureChannelProcess::class)->handle($ds->fresh(), IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.external'], 'capabilities' => ['collects_payment' => '1', 'provides_contract_documents' => '1']]); + $new = $this->takeOver($ds->fresh(), 'DS-NEU', '2027-09-10'); + + $this->assertSame($frozen, $running->fresh()->profile, 'the running case keeps profile and plan'); + $this->assertSame('collection.own@1', ProcessPlan::of($running->fresh())->templates['collection']); + $this->assertSame('collection.portal@1', ProcessPlan::of($new)->templates['collection']); + $this->assertSame(['landlord', 'portal'], [$running->fresh()->process()->payments()->value, $new->process()->payments()->value]); + } + + /** + * @param array $overrides + */ + private function channel(string $name, array $overrides, string $model = 'portal_booking'): Channel + { + return Channel::factory()->for($this->property)->create(['name' => $name, 'booking_model' => $model, 'process_overrides' => $overrides, 'import_enabled' => false, 'settings' => ['import_url' => 'https://portal.example/'.md5($name).'.ics']]); + } + + 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]); + } +} diff --git a/tests/Feature/Process/TemplateProcessTesterTest.php b/tests/Feature/Process/TemplateProcessTesterTest.php new file mode 100644 index 0000000..1f81cc4 --- /dev/null +++ b/tests/Feature/Process/TemplateProcessTesterTest.php @@ -0,0 +1,134 @@ +travelTo(CarbonImmutable::parse('2026-10-23 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Content::save(['contract.terms' => '

    Echte Bedingungen

    ', 'stay.cancellation' => '

    Echtes Storno

    ']); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'vermieter@example.org', 'process_defaults' => ['processing' => 'automatic']]); + $this->user = User::factory()->create(); + ProcessTesterTest::template(); + $this->portal = Channel::factory()->for($this->property)->create(['name' => 'Destination Solution', 'booking_model' => 'portal_booking', 'status' => 'setup', 'is_active' => false, 'import_enabled' => false, 'settings' => ['import_url' => 'https://ds.example/a.ics', 'email_senders' => 'ds.example', 'portal_profile' => 'generic']]); + } + + /** + * @return array + */ + public static function combinations(): array + { + return [ + 'eigenes Inkasso + eigene Vertragsdokumentation' => ['collection.own', 'contract_docs.own'], + 'Portal-Inkasso + eigene Vertragsdokumentation' => ['collection.portal', 'contract_docs.own'], + 'Portal-Inkasso + externe Vertragsunterlagen' => ['collection.portal', 'contract_docs.external'], + 'eigenes Inkasso + externe Vertragsunterlagen' => ['collection.own', 'contract_docs.external'], + ]; + } + + #[DataProvider('combinations')] + public function test_every_combination_runs_in_the_tester_and_differs_as_its_templates_promise(string $collection, string $documents): void + { + $report = $this->play($collection, $documents); + + $this->assertNull($report['aborted'] ?? null, json_encode($report)); + $this->assertSame([], $report['violations']); + $this->assertSame(['external.booking', 1], [$report['plan']['model'], $report['plan']['version']]); + $this->assertEqualsCanonicalizing([$collection.'@1', $documents.'@1'], array_column($report['plan']['templates'], 'reference'), 'the report names the templates used'); + foreach ($report['plan']['templates'] as $template) { + $this->assertNotEmpty($template['modules']); + $this->assertFalse($template['capabilities'][0]['confirmed'], 'a capability nobody confirmed is not shown as proven'); + } + + [$known, , $confirmed] = $report['timeline']; + $labels = fn (array $event): array => array_column($event['activities'], 'label'); + $states = fn (array $event): array => array_column($event['activities'], 'state_key', 'label'); + + // Finance: exactly one of the two collections shows up. + if ($collection === 'collection.own') { + $this->assertContains('Anzahlung erhalten', $labels($known)); + $this->assertNotContains('Auszahlung von Destination Solution auf unser Konto', $labels($known)); + $this->assertEmpty(array_filter($labels($known), fn (string $label): bool => str_starts_with($label, 'Zahlung des Gastes an')), 'no portal collection'); + $this->assertContains('Anzahlung erhalten', $known['waiting'], 'we wait for the guest payments: evidence is missing'); + } else { + $this->assertNotContains('Anzahlung erhalten', $labels($known), 'no own payment request towards the guest'); + $this->assertSame('external', $states($known)['Zahlung des Gastes an Destination Solution']); + $this->assertContains('Auszahlung von Destination Solution auf unser Konto', $known['waiting'], 'the payout evidence is missing'); + } + + // Contract documentation: ours has to be checked and sent, the portal's is external. Only ours ever goes out as a contract. + if ($documents === 'contract_docs.own') { + $this->assertSame('waiting', $states($known)['Buchungsunterlagen prüfen und senden'], 'our documents wait for the portal confirmation'); + $this->assertSame('open', $states($confirmed)['Buchungsunterlagen prüfen und senden'], 'then the landlord sends them (approval, not automatic)'); + } else { + $this->assertSame('external', $states($known)['Buchungsunterlagen an den Gast']); + $this->assertNotContains('Buchungsunterlagen prüfen und senden', $labels($confirmed)); + $this->assertEmpty(array_filter(array_column($confirmed['mails'], 'subject'), fn (string $subject): bool => str_contains($subject, 'Buchungsbestätigung') || str_contains($subject, 'Mietvertrag')), 'no contract from us'); + } + + // Independent steps keep running while the confirmation, the documents and the payments wait. + $this->assertContains('Kontaktdaten des Gastes', $known['independent']); + $this->assertContains('Anreisedaten', $known['independent']); + $this->assertContains('Bestätigung des Portals abwarten', $confirmed['independent'], 'the confirmation ends while the payments still wait'); + $this->assertContains('Buchungsinformation an den Gast (automatisch)', $confirmed['independent']); + + $this->assertSame(0, Booking::query()->count(), 'nothing reached the real data'); + $this->assertSame(0, BookingTask::query()->count()); + } + + public function test_the_tester_runs_the_fourth_combination_and_marks_it_as_such(): void + { + $report = $this->play('collection.own', 'contract_docs.external'); + + $this->assertSame('A3', $report['plan']['case_type'], 'classified by who collects – no archetype of its own'); + $values = collect($report['plan']['configuration'])->keyBy('question'); + $this->assertSame(['Wir', 'festgelegt durch die gewählte Funktionsschablone'], [$values['Wer kümmert sich um die Zahlungen des Gastes?']['value'] ?? null, $values['Wer kümmert sich um die Zahlungen des Gastes?']['source'] ?? null]); + } + + /** + * @return array + */ + private function play(string $collection, string $documents): array + { + $draft = ['model' => 'external.booking', 'templates' => ['collection' => $collection, 'contract_documents' => $documents], 'settings' => ['await_portal_confirmation' => '1', 'booking_notice' => 'automatic']]; + + return app(ProcessSandbox::class)->run($this->portal, IntakeKind::Booking, $draft, 'portal_confirmation_wait', ['arrival' => '2026-11-14', 'nights' => 4, 'guests' => 2, 'confirmation' => 'late'], 6, $this->user)->report; + } +}