}> */ public const STEP_CONTROLS = [ 'guest.details' => ['parameters' => [ProcessSetting::FormRequiresAddress]], 'guest.data_request' => ['mode' => ProcessSetting::DataRequest, 'parameters' => [ProcessSetting::DataRequestReminderHours, ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax, ProcessSetting::GuestLinkValidDays]], 'hold' => ['parameters' => [ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes]], 'offer.binding' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::HoldHours, ProcessSetting::ContractTemplate]], 'offer.information' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::GuestLinkValidDays]], 'documents.send' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::ContractDelivery, ProcessSetting::ContractTemplate]], 'documents.booking_notice' => ['parameters' => [ProcessSetting::BookingNotice]], 'portal.confirmation' => ['parameters' => [ProcessSetting::AwaitPortalConfirmation, ProcessSetting::PortalConfirmationWaitHours]], 'arrival.info' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::GuestMessages], 'parameters' => [ProcessSetting::ArrivalInfoDaysBefore]], ]; public function __construct(private ProcessCatalogue $catalogue, private TemplateComposer $composer) {} /** * The intake kinds the channel delivers. * * @return list */ public function intakes(Channel $channel): array { if ($channel->isWebsite()) { return [IntakeKind::Inquiry]; } return match ($channel->booking_model) { ChannelBookingModel::Inquiry => [IntakeKind::Inquiry], ChannelBookingModel::PortalBooking => [IntakeKind::Booking], default => [IntakeKind::Inquiry, IntakeKind::Booking], }; } public function profileKey(Channel $channel): string { if ($channel->isWebsite()) { return 'website'; } $chosen = (string) (($channel->settings ?? [])['portal_profile'] ?? ''); $profiles = (array) config('channels.portal_profiles'); if ($chosen !== '' && array_key_exists($chosen, $profiles)) { return $chosen; } $name = mb_strtolower((string) $channel->name); foreach ($profiles as $key => $profile) { foreach ((array) ($profile['match'] ?? []) as $needle) { if (str_contains($name, $needle)) { return $key; } } } return 'generic'; } /** * Every model of the intake kind with whether this channel fits it and – if not – why and what to do (decision * E2/O2 and V2.1 §3.2: the capabilities of the channel decide, not a fixed list of portals). * * @param array|null $capabilityDraft unsaved capability values of the configurator * @return array, hints: list}> */ public function modelOptions(Channel $channel, IntakeKind $intake, ?array $capabilityDraft = null): array { $capabilities = app(ChannelCapabilities::class)->resolve($channel, $capabilityDraft); $options = []; foreach ($this->catalogue->admissible($intake) as $key => $model) { if ($channel->isWebsite() !== str_starts_with($key, 'a1.')) { continue; } $restrictions = []; $hints = []; foreach ($model::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.'; continue; } if ($actual->value !== $required) { $fits = collect($this->catalogue->admissible($intake))->first(fn (ProcessModel $other): bool => $other::key() !== $key && collect($other::capabilityRequirements())->every(fn (bool $value, string $name): bool => ($capabilities[$name] ?? null)?->value === $value)); $restrictions[] = new Restriction( Restriction::CAPABILITY, $model::label().' setzt voraus: „'.$definition['question'].'“ – '.($required ? 'ja' : 'nein').'. Für diesen Kanal gilt aber '.($actual->value ? 'ja' : 'nein').' ('.$actual->sourceLabel().').', $fits ? $fits::label() : null, 'Wenn das nicht stimmt: oben bei „Was kann dieses Portal?“ „'.$definition['label'].'“ auf '.($required ? 'ja' : 'nein').' stellen und bestätigen.', ); } } $options[$key] = ['model' => $model, 'admissible' => $restrictions === [], 'restrictions' => $restrictions, 'hints' => $hints]; } return $options; } /** * The models the landlord may choose now. * * @param array|null $capabilityDraft * @return array */ public function admissibleModels(Channel $channel, IntakeKind $intake, ?array $capabilityDraft = null): array { 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 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. * * @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 $templates = []): array { if (! $this->catalogue->hasModel($modelKey)) { return []; } $stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []); $conflicts = []; $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; if ($setting === null || $value === null || (string) $value === (string) $fixedValue) { continue; } $conflicts[] = ['setting' => $setting, 'stored' => $setting->describe($value), 'fixed' => $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. $responsibilities = $this->catalogue->model($modelKey)::responsibilities(); foreach (Responsibilities::SETTINGS as $field => $setting) { $value = $setting->normalize($stored[$setting->value] ?? null); $responsibility = $value === null ? null : Responsibility::tryFrom((string) $value); if ($responsibility === null || $responsibilities->admits($setting, $responsibility) || in_array($setting, array_column($conflicts, 'setting'), true)) { continue; } $allowed = collect($responsibilities->allowed($field))->map(fn (Responsibility $allowedValue): string => $setting->describe($allowedValue->value))->implode(' oder '); $conflicts[] = ['setting' => $setting, 'stored' => $setting->describe($value), 'fixed' => $allowed, '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; } /** * The draft without the stored settings the chosen model overrides (see conflicts()): the landlord has to confirm their * removal when saving, so they are neither validated against the model nor saved again. * * @param array $draft * @return array */ 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'] ?? ''), (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)) { unset($draft['settings'][$key]); } } return $draft; } /** * 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, 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, '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, 'templates' => []]; } /** * Allowed values of the performer of a step under the model (variable responsibility), as setting values. * * @return array value => label */ public function performerOptions(ProcessModel $model, string $module): array { $control = self::STEP_CONTROLS[$module]['performer'] ?? null; if ($control === null) { return []; } return collect($model::responsibilities()->allowed($control['field'])) ->mapWithKeys(fn (Responsibility $value): array => [$value->value => $value === Responsibility::Portal ? 'Portal' : ($value === Responsibility::Landlord ? 'wir (automatisch)' : $value->getLabel())]) ->all(); } /** * The fixed choices of a setting that is not free text (null: free input). * * @return array|null */ public function settingOptions(ProcessSetting $setting): ?array { return match ($setting) { ProcessSetting::ContractDelivery => collect(ContractDelivery::cases())->mapWithKeys(fn (ContractDelivery $case): array => [$case->value => $case->getLabel()])->all(), ProcessSetting::BookingNotice => collect(BookingNoticeMode::cases())->mapWithKeys(fn (BookingNoticeMode $case): array => [$case->value => $case->getLabel()])->all(), ProcessSetting::AwaitPortalConfirmation => ['1' => 'ja, erst nach der Bestätigungsmail', '0' => 'nein, sofort'], default => null, }; } /** * Allowed modes of a step (as values of its setting). * * @return array */ public function modeOptions(string $module): array { return match (self::STEP_CONTROLS[$module]['mode'] ?? null) { ProcessSetting::Processing => collect(ProcessingMode::cases())->mapWithKeys(fn (ProcessingMode $mode): array => [$mode->value => $mode->getLabel()])->all(), ProcessSetting::DataRequest => collect(DataRequestMode::cases())->mapWithKeys(fn (DataRequestMode $mode): array => [$mode->value => $mode->getLabel()])->all(), default => [], }; } /** * The course a typical new case would take with the given (possibly unsaved) configuration: every step of the model * 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 */ 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); $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, $templates) as $key) { $class = $this->catalogue->modules()[$key]; $definition = $class::definition(); $on = ($draft['steps'][$key]['on'] ?? true) !== false || ! $definition->isOptional(); $reason = match (true) { ! $on => 'im Kanal abgeschaltet', $key === 'hold' && ! $profile->preReservation() => 'keine Vorreservierung in diesem Modell', $key === 'offer.information' && $profile->preReservation() => 'nicht in diesem Modell (verbindliches Angebot)', $key === 'offer.binding' && ! $profile->preReservation() => 'erst, wenn ein Angebot von Hand gesendet wird', $key === 'portal.payout' && $profile->payments() !== Responsibility::Portal => 'wir kassieren selbst', $key === 'review.request' && $profile->guestMessages() !== Responsibility::Landlord => 'das Portal schreibt dem Gast', $key === 'guest.details' && $intake === IntakeKind::Booking && $profile->documents() === Responsibility::Portal && $profile->payments() === Responsibility::Portal && $profile->guestMessages() === Responsibility::Portal => 'wir schreiben dem Gast nicht', default => null, }; $mode = isset(self::STEP_CONTROLS[$key]['mode']) ? (string) $profile->value(self::STEP_CONTROLS[$key]['mode']) : (in_array('automatic', $definition->modes, true) ? 'automatic' : null); $performer = match ($key) { 'documents.send' => $profile->documents()->value, 'payments.monitor' => $profile->payments()->value, 'arrival.info' => $profile->guestMessages()->value, 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), 'template' => $owners[$key] ?? null]; } return $rows; } /** * Everything that is not admissible in a draft (empty = it may be saved). * * @param array $draft * @return list */ public function problems(Channel $channel, IntakeKind $intake, array $draft, bool $sandbox = false): array { $draft = $this->withoutOverriddenSettings($channel, $intake, $draft); $problems = []; if (! in_array($intake, $this->intakes($channel), true)) { $problems[] = 'Dieser Kanal liefert keine '.($intake === IntakeKind::Booking ? 'festen Buchungen' : 'Anfragen').'.'; } $key = (string) ($draft['model'] ?? ''); $options = $this->modelOptions($channel, $intake, (array) ($draft['capabilities'] ?? []) ?: null); if ($key === '' || ! array_key_exists($key, $options)) { return [...$problems, 'Das Ablaufmodell „'.$key.'“ gibt es für diese Eingangsart dieses Kanals nicht.']; } if (! $options[$key]['admissible']) { return [...$problems, ...array_map(fn (Restriction $restriction): string => $restriction->text(), $options[$key]['restrictions'])]; } $model = $options[$key]['model']; $variant = $model->variant((string) ($draft['variant'] ?? 'standard')); if ($variant === null) { return [...$problems, 'Das Modell hat diese Variante nicht.']; } if ($variant->isTesterOnly() && ! $sandbox) { $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, $templates), true)) { $problems[] = "Der Schritt {$module} gehört nicht zu diesem Modell."; continue; } $definition = $this->catalogue->modules()[$module]::definition(); if (($step['on'] ?? true) === false && ! $definition->isOptional()) { $problems[] = 'Der Schritt „'.$definition->label.'“ ist Pflicht und kann nicht abgeschaltet werden.'; } if ($definition->isTesterOnly() && ! $sandbox && ($step['on'] ?? true) !== false && $variant->isTesterOnly()) { $problems[] = 'Der Schritt „'.$definition->label.'“ ist nur im Prozess-Tester verwendbar.'; } } // Responsibilities: fixed ones are set by the model; variable ones only to the values the model allows. $responsibilities = $model::responsibilities(); foreach (Responsibilities::SETTINGS as $field => $setting) { $value = $draft['settings'][$setting->value] ?? null; if ($value === null || $value === '') { continue; } $responsibility = Responsibility::tryFrom((string) $value); if ($responsibility === null || ! $responsibilities->admits($setting, $responsibility)) { $problems[] = Responsibilities::LABELS[$field].': „'.($responsibility?->getLabel() ?? $value).'“ ist in diesem Modell nicht zulässig.'; } } 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; } /** * The profile a new case would get with the draft (model fixes and setting values applied). * * @param array $draft */ public function profileWith(Channel $channel, IntakeKind $intake, array $draft): ProcessProfile { $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'] ?? []), 'templates' => (array) ($draft['templates'] ?? [])]; $preview->setAttribute('process_overrides', $overrides); return app(ProcessSettings::class)->resolve($channel->property, $preview, $intake); } }