diff --git a/app/Actions/ConfigureChannelProcess.php b/app/Actions/ConfigureChannelProcess.php new file mode 100644 index 0000000..b4930d5 --- /dev/null +++ b/app/Actions/ConfigureChannelProcess.php @@ -0,0 +1,68 @@ +, settings?: array} $draft + * + * @throws ValidationException + */ + public function handle(Channel $channel, IntakeKind $intake, array $draft, ?string $by = null): Channel + { + $problems = $this->configuration->problems($channel, $intake, $draft); + if ($problems !== []) { + throw ValidationException::withMessages(['process' => $problems]); + } + + return DB::transaction(function () use ($channel, $intake, $draft, $by): Channel { + $channel = Channel::query()->lockForUpdate()->findOrFail($channel->id); + $overrides = (array) ($channel->process_overrides ?? []); + $current = (array) ($overrides[$intake->value] ?? []); + + $settings = []; + foreach (ProcessSetting::cases() as $setting) { + $value = array_key_exists($setting->value, (array) ($draft['settings'] ?? [])) ? $setting->normalize($draft['settings'][$setting->value]) : $setting->normalize($current[$setting->value] ?? null); + if ($value !== null && in_array($intake, $setting->channelIntakes(), true)) { + $settings[$setting->value] = $value; + } + } + + $steps = []; + foreach ((array) ($draft['steps'] ?? []) as $module => $step) { + if (array_key_exists('on', $step) && $step['on'] === false) { + $steps[$module] = ['on' => false]; + } + } + + $overrides[$intake->value] = [ + ...$settings, + 'model' => $draft['model'], + 'variant' => $draft['variant'] ?? 'standard', + 'steps' => $steps, + 'configured_at' => now()->toIso8601String(), + 'configured_by' => $by ?? auth()->user()?->name, + ]; + $channel->update(['process_overrides' => $overrides]); + + return $channel; + }); + } +} diff --git a/app/Filament/Resources/Channels/ChannelResource.php b/app/Filament/Resources/Channels/ChannelResource.php index 48b9725..a8f3645 100644 --- a/app/Filament/Resources/Channels/ChannelResource.php +++ b/app/Filament/Resources/Channels/ChannelResource.php @@ -4,6 +4,7 @@ use App\Filament\Concerns\FollowsAdminMode; use App\Filament\Concerns\SelectsRecordProperty; +use App\Filament\Resources\Channels\Pages\ChannelProcess; use App\Filament\Resources\Channels\Pages\ChannelRules; use App\Filament\Resources\Channels\Pages\CreateChannel; use App\Filament\Resources\Channels\Pages\EditChannel; @@ -61,6 +62,7 @@ public static function getPages(): array 'create' => CreateChannel::route('/create'), 'edit' => EditChannel::route('/{record}/edit'), 'rules' => ChannelRules::route('/{record}/rules'), + 'process' => ChannelProcess::route('/{record}/process'), ]; } } diff --git a/app/Filament/Resources/Channels/Pages/ChannelProcess.php b/app/Filament/Resources/Channels/Pages/ChannelProcess.php new file mode 100644 index 0000000..5470513 --- /dev/null +++ b/app/Filament/Resources/Channels/Pages/ChannelProcess.php @@ -0,0 +1,231 @@ +, settings: array}> */ + public array $drafts = []; + + public function mount(int|string $record): void + { + $this->record = $this->resolveRecord($record); + $configuration = app(ChannelProcessConfiguration::class); + foreach ($configuration->intakes($this->record) as $intake) { + $current = $configuration->current($this->record, $intake); + $stored = (array) (($this->record->process_overrides ?? [])[$intake->value] ?? []); + $models = $configuration->admissibleModels($this->record, $intake); + $model = array_key_exists($current['model'], $models) || $models === [] ? $current['model'] : (string) array_key_first($models); + $this->drafts[$intake->value] = [ + 'model' => $model, + 'variant' => $current['variant'], + 'steps' => (array) ($stored['steps'] ?? []), + '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'], + ]; + } + $this->intake = (string) array_key_first($this->drafts); + } + + public function getTitle(): string + { + return 'Ablauf: '.$this->record->name; + } + + public function expert(): bool + { + $user = auth()->user(); + + return ! $user instanceof User || $user->adminMode() === AdminMode::Expert; + } + + /** + * @return array intake value => tab label + */ + public function tabs(): array + { + return collect(array_keys($this->drafts))->mapWithKeys(fn (string $intake): array => [$intake => $intake === IntakeKind::Booking->value ? 'Feste Buchungen' : 'Anfragen'])->all(); + } + + public function question(): string + { + return $this->intake === IntakeKind::Booking->value + ? 'Wie wird eine feste Buchung über '.$this->record->name.' abgewickelt?' + : 'Wie wird eine Anfrage über '.$this->record->name.' abgewickelt?'; + } + + /** + * @return array + */ + public function models(): array + { + return app(ChannelProcessConfiguration::class)->admissibleModels($this->record, IntakeKind::from($this->intake)); + } + + public function chooseModel(string $model): void + { + $this->drafts[$this->intake]['model'] = $model; + $this->drafts[$this->intake]['variant'] = 'standard'; + $this->drafts[$this->intake]['steps'] = []; + } + + public function model(): ProcessModel + { + return app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']); + } + + public function profile(): ProcessProfile + { + return app(ChannelProcessConfiguration::class)->profileWith($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]); + } + + /** + * The step cards: preview row + controls of each step. + * + * @return list> + */ + public function steps(): array + { + $configuration = app(ChannelProcessConfiguration::class); + $catalogue = app(ProcessCatalogue::class); + $model = $this->model(); + $profile = $this->profile(); + $draft = $this->drafts[$this->intake]; + + return array_map(function (array $row) use ($configuration, $catalogue, $model, $profile): array { + $definition = $catalogue->modules()[$row['module']]::definition(); + $controls = ChannelProcessConfiguration::STEP_CONTROLS[$row['module']] ?? []; + $parameters = array_values(array_filter($controls['parameters'] ?? [], fn (ProcessSetting $setting): bool => in_array(IntakeKind::from($this->intake), $setting->channelIntakes(), true) && ! $model::fixesSetting($setting) && ($this->expert() || in_array($setting, [ProcessSetting::HoldHours, ProcessSetting::DataRequestReminderHours, ProcessSetting::ArrivalInfoDaysBefore, ProcessSetting::ClarificationHoldAutoMinutes], true)))); + + return [...$row, + 'purpose' => $definition->purpose, + 'waits' => $definition->waits, + 'optional' => $definition->isOptional(), + 'version' => $catalogue->modules()[$row['module']]::version(), + 'mode_setting' => isset($controls['mode']) && ! $model::fixesSetting($controls['mode']) ? $controls['mode'] : null, + 'mode_options' => $configuration->modeOptions($row['module']), + 'performer_setting' => isset($controls['performer']) ? $controls['performer']['setting'] : null, + 'performer_options' => $configuration->performerOptions($model, $row['module']), + 'parameters' => array_map(fn (ProcessSetting $setting): array => $this->setting($setting, $profile), $parameters), + ]; + }, $configuration->preview($this->record, IntakeKind::from($this->intake), $draft)); + } + + /** + * One setting with its effective value and origin (set here, by the model, inherited from where). + * + * @return array{key: string, question: string, value: string, source: string, set: bool} + */ + public function setting(ProcessSetting $setting, ProcessProfile $profile): array + { + $source = $profile->source($setting); + + return [ + 'key' => $setting->value, + 'question' => $setting->question(), + 'value' => $setting === ProcessSetting::ContractTemplate ? (string) ($profile->value($setting) ?? 'Vorlage der Wohnung') : $setting->describe($profile->value($setting)), + 'source' => in_array($source, [ProcessProfile::CHANNEL, ProcessProfile::WEBSITE], true) ? 'hier gesetzt' : 'geerbt: '.ProcessProfile::sourceLabel($source), + 'set' => array_key_exists($setting->value, $this->drafts[$this->intake]['settings']) && filled($this->drafts[$this->intake]['settings'][$setting->value]), + ]; + } + + public function inherit(string $setting): void + { + unset($this->drafts[$this->intake]['settings'][$setting]); + } + + public function toggleStep(string $module): void + { + $on = ($this->drafts[$this->intake]['steps'][$module]['on'] ?? true) !== false; + $this->drafts[$this->intake]['steps'][$module] = ['on' => ! $on]; + } + + /** + * @return list + */ + public function problems(): array + { + return app(ChannelProcessConfiguration::class)->problems($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]); + } + + /** + * Running cases of this channel and intake kind (they keep their frozen plan). + */ + public function runningCases(): int + { + return Booking::query() + ->where(fn ($query) => $query->where('origin_channel_id', $this->record->id)->orWhere('import_channel_id', $this->record->id)) + ->where('intake', $this->intake) + ->whereNotIn('status', ['cancelled', 'declined', 'expired', 'completed']) + ->count(); + } + + public function save(): void + { + try { + $this->record = app(ConfigureChannelProcess::class)->handle($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]); + } catch (ValidationException $exception) { + Notification::make()->title('Nicht gespeichert')->body(collect($exception->errors())->flatten()->implode(' '))->danger()->persistent()->send(); + + return; + } + $this->drafts[$this->intake]['derived'] = false; + $running = $this->runningCases(); + Notification::make()->title('Ablauf gespeichert')->body('Gilt für neue Vorgänge.'.($running > 0 ? ' '.$running.' laufende Vorgänge behalten ihren bisherigen Ablauf.' : ''))->success()->send(); + } + + /** + * The effective value a new case would get, for the landlord's comparison (expert view). + */ + public function standard(ProcessSetting $setting): string + { + $profile = app(ProcessSettings::class)->resolve($this->record->property, null, IntakeKind::from($this->intake)); + + return $setting->describe($profile->value($setting)); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('save')->label('Speichern')->action(fn () => $this->save()), + Action::make('connection')->label('Kanaldaten')->color('gray')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])), + ]; + } +} diff --git a/app/Filament/Resources/Channels/Pages/EditChannel.php b/app/Filament/Resources/Channels/Pages/EditChannel.php index 7d8e91e..95553f7 100644 --- a/app/Filament/Resources/Channels/Pages/EditChannel.php +++ b/app/Filament/Resources/Channels/Pages/EditChannel.php @@ -19,6 +19,7 @@ class EditChannel extends EditRecord protected function getHeaderActions(): array { return [ + Action::make('process')->label('Ablauf')->url(fn (): string => ChannelResource::getUrl('process', ['record' => $this->record])), Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record]))->visible(fn (): bool => $this->record->isPortal()), Action::make('analyze')->label('Kalender analysieren')->visible(fn (): bool => $this->record->isPortal())->action(function (AnalyzeChannelCalendar $analyze): void { try { @@ -38,10 +39,8 @@ protected function mutateFormDataBeforeFill(array $data): array protected function handleRecordUpdate(Model $record, array $data): Model { - // The own website's entry only keeps its settings; there is no connection to configure. + // The own website's entry has no connection to configure; its process is set up under "Ablauf" (ChannelProcess). if ($record instanceof Channel && $record->isWebsite()) { - $record->update(['process_overrides' => $data['process_overrides'] ?? []]); - return $record; } diff --git a/app/Filament/Resources/Channels/Schemas/ChannelForm.php b/app/Filament/Resources/Channels/Schemas/ChannelForm.php index 849d993..f2b8091 100644 --- a/app/Filament/Resources/Channels/Schemas/ChannelForm.php +++ b/app/Filament/Resources/Channels/Schemas/ChannelForm.php @@ -8,9 +8,7 @@ use App\Enums\ChannelEchoBehavior; use App\Enums\ChannelExportMode; use App\Enums\ChannelStatus; -use App\Enums\IntakeKind; -use App\Enums\ProcessSetting; -use App\Filament\Forms\ProcessSettingFields; +use App\Filament\Resources\Channels\ChannelResource; use App\Models\Channel; use App\Models\Property; use App\Support\CurrentProperty; @@ -21,6 +19,7 @@ use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Infolists\Components\TextEntry; +use Filament\Schemas\Components\Component; use Filament\Schemas\Components\Group; use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Utilities\Get; @@ -68,7 +67,12 @@ public static function configure(Schema $schema, bool $selectProperty = false): ->required() ->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.') ->columnSpanFull(), - ...self::processSections(), + Select::make('settings.portal_profile')->label('Art des Portals (Kanalprofil)') + ->options(fn (): array => collect(config('channels.portal_profiles'))->except('website')->map(fn (array $profile): string => $profile['label'])->all()) + ->placeholder('am Namen erkennen') + ->helperText('Legt fest, welche Ablaufmodelle für Anfragen und feste Buchungen dieses Portals wählbar sind (Kanal › Ablauf). Weitere Modelle werden nach fachlicher Prüfung im Kanalprofil freigegeben.') + ->columnSpanFull(), + ...self::processLink('Ablauf dieses Portals'), Select::make('connector') ->label('Kalenderanbindung') ->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.') @@ -125,56 +129,27 @@ public static function configure(Schema $schema, bool $selectProperty = false): */ private static function websiteSections(): array { - $defaults = (array) (Settings::tenant()?->process_defaults ?? []); - $inherited = function (ProcessSetting $setting) use ($defaults): string { - $value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default(); - - return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value); - }; - $settings = array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array(IntakeKind::Inquiry, $setting->channelIntakes(), true))); - return [ Section::make('Anfragen über die eigene Webseite') - ->description('Nur ausfüllen, was für Anfragen über Ihre Webseite anders sein soll als in Ihren Standardeinstellungen (System › So arbeite ich). Telefon- und E-Mail-Anfragen folgen weiter den Standardeinstellungen.') - ->columns(2) + ->description('Wie Anfragen über Ihre Webseite abgewickelt werden – Ablaufmodell, Schritte, Fristen –, stellen Sie unter „Ablauf“ ein. Telefon- und E-Mail-Anfragen folgen Ihren Standardeinstellungen (System › So arbeite ich).') ->columnSpanFull() ->visible(fn (?Channel $record): bool => $record?->isWebsite() ?? false) - ->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settings, $inherited)), + ->schema(self::processLink('Ablauf der Webseite')), ]; } /** - * What a contract template brings along, shown under the template choice. - */ - /** - * Deviations of this portal from the landlord's defaults, separately for requests and for bookings that are already - * binding when they arrive. Empty fields follow the defaults (System › So arbeite ich). + * The process of a channel is set up step by step on its own page (Kanal › Ablauf), no longer as a flat list here. * - * @return list
+ * @return list */ - private static function processSections(): array + private static function processLink(string $label): array { - $defaults = (array) (Settings::tenant()?->process_defaults ?? []); - $inherited = function (ProcessSetting $setting) use ($defaults): string { - $value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default(); - - return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value); - }; - $settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => $setting !== ProcessSetting::FormRequiresAddress && in_array($intake, $setting->channelIntakes(), true))); - return [ - Section::make('Anfragen über dieses Portal') - ->description('Nur ausfüllen, was bei diesem Portal anders ist als in Ihren Standardeinstellungen.') - ->columns(2) - ->columnSpanFull() - ->collapsible() - ->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settingsFor(IntakeKind::Inquiry), $inherited)), - Section::make('Feste Buchungen über dieses Portal') - ->description('Buchungen, die beim Portal schon verbindlich sind. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Anlagen mit.') - ->columns(2) - ->columnSpanFull() - ->collapsible() - ->schema(ProcessSettingFields::make('process_overrides.booking.', $settingsFor(IntakeKind::Booking), $inherited)), + TextEntry::make('process_link')->hiddenLabel()->columnSpanFull() + ->state(fn (?Channel $record): string => $record === null ? 'Den Ablauf richten Sie nach dem Anlegen unter „Ablauf“ ein.' : $label.': Ablaufmodell wählen und Schritte einstellen.') + ->url(fn (?Channel $record): ?string => $record === null ? null : ChannelResource::getUrl('process', ['record' => $record])) + ->color('primary'), ]; } } diff --git a/app/Process/ChannelProcessConfiguration.php b/app/Process/ChannelProcessConfiguration.php new file mode 100644 index 0000000..89b8f45 --- /dev/null +++ b/app/Process/ChannelProcessConfiguration.php @@ -0,0 +1,256 @@ +}> + */ + 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::ContractTemplate]], + 'arrival.info' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::GuestMessages], 'parameters' => [ProcessSetting::ArrivalInfoDaysBefore]], + ]; + + public function __construct(private ProcessCatalogue $catalogue) {} + + /** + * 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'; + } + + /** + * The models the landlord may choose for this channel and intake kind. + * + * @return array + */ + public function admissibleModels(Channel $channel, IntakeKind $intake): array + { + $allowed = (array) (config('channels.portal_profiles.'.$this->profileKey($channel))[$intake->value] ?? []); + + return array_filter($this->catalogue->admissible($intake), fn (ProcessModel $model): bool => in_array($model::key(), $allowed, true)); + } + + /** + * 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} + */ + 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]; + } + + $property = $channel->property; + $profile = app(ProcessSettings::class)->resolve($property, $channel, $intake); + + return ['model' => $this->catalogue->derivedModel($profile), 'variant' => 'standard', 'derived' => true]; + } + + /** + * 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(); + } + + /** + * 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); + $standard = $model->modules('standard'); + $rows = []; + foreach ($model->modules($variant) 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)]; + } + + 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 + { + $problems = []; + if (! in_array($intake, $this->intakes($channel), true)) { + $problems[] = 'Dieser Kanal liefert keine '.($intake === IntakeKind::Booking ? 'festen Buchungen' : 'Anfragen').'.'; + } + $key = (string) ($draft['model'] ?? ''); + $models = $this->admissibleModels($channel, $intake); + if ($key === '' || ! array_key_exists($key, $models)) { + return [...$problems, 'Das Ablaufmodell „'.$key.'“ ist für diesen Kanal nicht zulässig. Zulässig: '.(implode(', ', array_map(fn (ProcessModel $model): string => $model::label(), $models)) ?: 'keines').'.']; + } + $model = $models[$key]; + $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.'; + } + + foreach ((array) ($draft['steps'] ?? []) as $module => $step) { + if (! $this->catalogue->hasModule($module) || ! in_array($module, $model->modules($variant->key), 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)); + } + + /** + * 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 + { + $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'] ?? [])]; + $preview->setAttribute('process_overrides', $overrides); + + return app(ProcessSettings::class)->resolve($channel->property, $preview, $intake); + } +} diff --git a/app/Process/ProcessProfile.php b/app/Process/ProcessProfile.php index 2149157..9442b03 100644 --- a/app/Process/ProcessProfile.php +++ b/app/Process/ProcessProfile.php @@ -27,6 +27,9 @@ final class ProcessProfile /** The own website's entry of the channel manager (v0.11). */ public const WEBSITE = 'website'; + /** Fixed by the process model chosen for the channel (Architektur V2). */ + public const MODEL = 'model'; + /** Fixed by the case type (A6), not settable. */ public const CASE_TYPE = 'case_type'; @@ -167,6 +170,7 @@ public static function sourceLabel(string $source): string self::CHANNEL => 'Abweichung des Portals', self::WEBSITE => 'Einstellung der eigenen Webseite', self::CASE_TYPE => 'fest für diese Vorgangsart', + self::MODEL => 'festgelegt durch das gewählte Ablaufmodell', 'migration' => 'aus dem bisherigen Stand übernommen', default => 'Grundeinstellung', }; diff --git a/app/Process/ProcessSettings.php b/app/Process/ProcessSettings.php index ed6c719..97b447c 100644 --- a/app/Process/ProcessSettings.php +++ b/app/Process/ProcessSettings.php @@ -10,6 +10,7 @@ use App\Models\Channel; use App\Models\Property; use App\Models\Tenant; +use App\Process\Models\ProcessModel; /** * Resolves the effective process settings: built-in default → landlord default (tenant) → deviation of the property @@ -49,6 +50,17 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak } } + // Architektur V2: the process model chosen for the channel and intake kind fixes some settings (e.g. the + // pre-reservation of the offer model, the responsibilities of A3–A5); these win over every level. + $model = $this->chosenModel($channel, $intake); + foreach ($model === null ? [] : $model::fixes() as $key => $fixed) { + $setting = ProcessSetting::tryFrom($key); + if ($setting !== null) { + $values[$key] = $setting->normalize($fixed) ?? $fixed; + $sources[$key] = ProcessProfile::MODEL; + } + } + 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. @@ -68,6 +80,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 model chosen for the channel and intake kind (Kanal › Ablauf), when it is registered and fits the intake. + */ + private function chosenModel(?Channel $channel, IntakeKind $intake): ?ProcessModel + { + $key = (string) (ProcessPlan::configurationOf($channel, $intake)['model'] ?? ''); + $catalogue = app(ProcessCatalogue::class); + if ($key === '' || ! $catalogue->hasModel($key)) { + return null; + } + $model = $catalogue->model($key); + + return in_array($intake, $model::intakes(), true) ? $model : null; + } + /** * Settings of a request from the own website: the website's entry of the channel manager is its channel level * (the case itself stays direct, without a channel). diff --git a/config/channels.php b/config/channels.php index 2a7c054..63eeaa5 100644 --- a/config/channels.php +++ b/config/channels.php @@ -25,6 +25,20 @@ */ 'uid_suffix' => '@fewo-stommer', + /* + | Business and integration capabilities per kind of channel (decision E2/O2): which process models may be chosen for + | requests and for bookings that are binding at the portal. A channel names its profile in settings.portal_profile + | (Kanal › Ablauf); without one it is recognised by its name, else "generic". Further models are released here after + | a business review – never as a special rule in the process core. + */ + 'portal_profiles' => [ + 'website' => ['label' => 'Eigene Webseite', 'inquiry' => ['a1.offer', 'a1.information'], 'booking' => []], + 'fewo_direkt' => ['label' => 'FeWo-direkt (Vrbo)', 'match' => ['fewo-direkt', 'fewo direkt', 'vrbo'], 'inquiry' => ['a2.offer', 'a2.information'], 'booking' => ['a4.portal_booking']], + 'destination_solutions' => ['label' => 'Destination Solutions', 'match' => ['destination solution'], 'inquiry' => [], 'booking' => ['a3.portal_booking']], + 'inquiry_listing' => ['label' => 'Inserat mit Anfragen (z. B. ferienundwohnen.de, Ostseeklar)', 'match' => ['ferienundwohnen', 'ostseeklar', 'strandurlaub', 'ferienunterkunft'], 'inquiry' => ['a2.offer', 'a2.information'], 'booking' => []], + 'generic' => ['label' => 'Sonstiges Portal', 'inquiry' => ['a2.offer', 'a2.information'], 'booking' => ['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking']], + ], + 'removal_confirmation_runs' => 2, 'max_automatic_removals' => 5, 'export_request_history_limit' => 100, diff --git a/resources/views/filament/pages/effective-settings.blade.php b/resources/views/filament/pages/effective-settings.blade.php index e91f3d3..fd8c652 100644 --- a/resources/views/filament/pages/effective-settings.blade.php +++ b/resources/views/filament/pages/effective-settings.blade.php @@ -2,7 +2,7 @@ @php $cell = 'padding:.4rem .5rem;border-bottom:1px solid rgba(128,128,128,.2);vertical-align:top'; $muted = 'color:#6b7280;font-size:.8rem'; - $levels = [\App\Process\ProcessProfile::SYSTEM => 'Grundeinstellung', \App\Process\ProcessProfile::TENANT => 'Ihr Standard', \App\Process\ProcessProfile::PROPERTY => 'Wohnung', \App\Process\ProcessProfile::CHANNEL => 'Portal', \App\Process\ProcessProfile::WEBSITE => 'Webseite', \App\Process\ProcessProfile::CASE_TYPE => 'fest (A6)']; + $levels = [\App\Process\ProcessProfile::SYSTEM => 'Grundeinstellung', \App\Process\ProcessProfile::TENANT => 'Ihr Standard', \App\Process\ProcessProfile::PROPERTY => 'Wohnung', \App\Process\ProcessProfile::CHANNEL => 'Portal', \App\Process\ProcessProfile::WEBSITE => 'Webseite', \App\Process\ProcessProfile::CASE_TYPE => 'fest (A6)', \App\Process\ProcessProfile::MODEL => 'Ablaufmodell']; @endphp diff --git a/resources/views/filament/resources/channels/channel-process.blade.php b/resources/views/filament/resources/channels/channel-process.blade.php new file mode 100644 index 0000000..41d2458 --- /dev/null +++ b/resources/views/filament/resources/channels/channel-process.blade.php @@ -0,0 +1,138 @@ + + @php + $muted = 'color:#6b7280;font-size:.8rem'; + $card = 'border:1px solid rgba(128,128,128,.3);border-radius:.5rem;padding:.75rem 1rem;margin-bottom:.6rem'; + $input = 'border:1px solid rgba(128,128,128,.4);border-radius:.375rem;padding:.3rem .45rem;background:transparent'; + $phases = ['P01' => 'Eingang und Daten', 'P02' => 'Angebot und Verbindlichkeit', 'P03' => 'Abwicklung', 'P04' => 'Aufenthalt', 'P05' => 'Abschluss']; + $performers = ['system' => 'System', 'landlord' => 'Sie', 'guest' => 'Gast', 'portal' => 'Portal', 'service_provider' => 'Dienstleister', 'none' => 'niemand']; + $draft = $this->drafts[$this->intake]; + $models = $this->models(); + $model = $this->model(); + $steps = $this->steps(); + $problems = $this->problems(); + @endphp + + @if (count($this->tabs()) > 1) +
+ @foreach ($this->tabs() as $key => $label) + {{ $label }} + @endforeach +
+ @endif + + + @if ($models === []) +

Für diesen Kanal ist für diese Eingangsart kein Ablaufmodell freigegeben (Kanalprofil). Vorgänge folgen weiter dem aus den Einstellungen abgeleiteten Ablauf.

+ @endif +
+ @foreach ($models as $key => $candidate) + + @endforeach +
+ + @if (count($model->variants()) > 1) +
+ + @if ($model->variant($draft['variant'])?->isTesterOnly()) +

Nur im Prozess-Tester verwendbar (Architekturnachweis). Sie können diese Variante mit „Ablauf testen“ durchspielen, aber nicht speichern.

+ @endif +
+ @endif +
+ + @if ($problems !== []) + +
    + @foreach ($problems as $problem)
  • {{ $problem }}
  • @endforeach +
+
+ @endif + +
+
+ @foreach (collect($steps)->groupBy('phase') as $phase => $group) +

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

+ @foreach ($group as $index => $step) +
+
+ {{ $step['label'] }} + @if ($step['tester_only']) · nur im Prozess-Tester@endif + @if ($step['inserted']) · Zusatzschritt der Variante@endif + + @if ($step['optional']) + + {{ ($draft['steps'][$step['module']]['on'] ?? true) === false ? 'aus' : 'an' }} + + @else + 🔒 Pflicht + @endif +
+
{{ $step['purpose'] }}
+
+ Wer: {{ $performers[$step['performer']] ?? $step['performer'] ?? '–' }} + @if ($step['waits'] !== []) · kann warten auf: {{ implode(', ', array_map(fn ($wait) => ['guest' => 'Gast', 'portal' => 'Portal', 'landlord' => 'Sie', 'time' => 'Frist'][$wait] ?? $wait, $step['waits'])) }}@endif + @if (! $step['on'] && $step['reason']) · übersprungen: {{ $step['reason'] }}@endif + @if ($this->expert()) · {{ $step['module'] }} v{{ $step['version'] }}@endif +
+ + @if ($step['mode_setting'] && $step['mode_options'] !== []) + + @endif + + @if ($step['performer_setting'] && count($step['performer_options']) > 1) + + @endif + + @foreach ($step['parameters'] as $parameter) + + @endforeach +
+ @endforeach + @endforeach +
+ + +
    + @foreach ($steps as $step) +
  1. + {{ $step['label'] }} + – {{ $step['on'] ? ($performers[$step['performer']] ?? $step['performer'] ?? '').($step['mode'] ? ', '.(\App\Enums\ProcessingMode::tryFrom($step['mode'])?->getLabel() ?? \App\Enums\DataRequestMode::tryFrom($step['mode'])?->getLabel() ?? $step['mode']) : '') : 'übersprungen: '.$step['reason'] }} +
  2. + @endforeach +
+

Gilt für neue Vorgänge. Laufende Vorgänge dieses Kanals ({{ $this->runningCases() }}) behalten ihren bisherigen Ablauf.

+ @if (\Illuminate\Support\Facades\Route::has('filament.admin.resources.channels.test')) + Ablauf testen + @endif +
+
+
diff --git a/tests/Feature/ChannelManagerTest.php b/tests/Feature/ChannelManagerTest.php index ca56780..4bb1540 100644 --- a/tests/Feature/ChannelManagerTest.php +++ b/tests/Feature/ChannelManagerTest.php @@ -8,6 +8,7 @@ use App\Enums\IntakeKind; use App\Enums\ProcessSetting; use App\Filament\Pages\EffectiveSettings; +use App\Filament\Resources\Channels\Pages\ChannelProcess; use App\Filament\Resources\Channels\Pages\EditChannel; use App\Filament\Resources\Channels\Pages\ListChannels; use App\Models\Booking; @@ -113,10 +114,12 @@ public function test_the_channel_manager_lists_the_website_and_saves_its_setting Livewire::test(EditChannel::class, ['record' => $website->getRouteKey()]) ->assertSee('Anfragen über die eigene Webseite') - ->assertDontSee('Eigener iCal-Exportlink') - ->fillForm(['process_overrides' => ['inquiry' => ['clarification_hold_manual_minutes' => '0', 'form_requires_address' => '1']]]) - ->call('save') - ->assertHasNoFormErrors(); + ->assertDontSee('Eigener iCal-Exportlink'); + // Architektur V2: the process of the website is set up step by step under "Ablauf" (no flat list in the form). + Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()]) + ->set('drafts.inquiry.settings.clarification_hold_manual_minutes', '0') + ->set('drafts.inquiry.settings.form_requires_address', '1') + ->call('save'); $profile = app(ProcessSettings::class)->forWebsite($this->property); $this->assertSame(0, $profile->clarificationHoldMinutes()); diff --git a/tests/Feature/Process/ChannelProcessConfiguratorTest.php b/tests/Feature/Process/ChannelProcessConfiguratorTest.php new file mode 100644 index 0000000..17090e1 --- /dev/null +++ b/tests/Feature/Process/ChannelProcessConfiguratorTest.php @@ -0,0 +1,214 @@ +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(); + } + + /** K01 / E2 / O2 */ + public function test_only_admissible_models_per_channel_and_intake_are_offered(): void + { + $configuration = app(ChannelProcessConfiguration::class); + $fewo = $this->channel('FeWo-direkt', 'mixed'); + $ds = $this->channel('Destination Solution', 'portal_booking'); + $listing = $this->channel('Ostseeklar', 'inquiry'); + $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([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->expectException(ValidationException::class); + app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, ['model' => 'a4.portal_booking']); + } + + /** K01, K05, N4 */ + public function test_a_mixed_channel_gets_different_models_for_requests_and_bookings_and_running_cases_keep_their_plan(): void + { + $fewo = $this->channel('FeWo-direkt', 'mixed'); + $running = app(TakeOverExternalBooking::class)->handle($this->property, $fewo, CarbonImmutable::parse('2026-12-05'), CarbonImmutable::parse('2026-12-12'), ['portal_reference' => 'HA-ALT']); + $before = $running->fresh()->profile; + + app(ConfigureChannelProcess::class)->handle($fewo, IntakeKind::Inquiry, ['model' => 'a2.information']); + app(ConfigureChannelProcess::class)->handle($fewo->fresh(), IntakeKind::Booking, ['model' => 'a4.portal_booking']); + + $inquiry = app(TakeOverPortalInquiry::class)->handle($fewo->fresh(), CarbonImmutable::parse('2026-11-14'), CarbonImmutable::parse('2026-11-18'), 'HA-ANF'); + $booking = app(TakeOverExternalBooking::class)->handle($this->property, $fewo->fresh(), CarbonImmutable::parse('2027-07-10'), CarbonImmutable::parse('2027-07-17'), ['portal_reference' => 'HA-NEU']); + + $this->assertSame(['a2.information', ProcessPlan::CONFIGURED, CaseType::A2], [$inquiry->profile['plan']['model'], $inquiry->profile['plan']['source'], $inquiry->case_type]); + $this->assertFalse($inquiry->process()->preReservation(), 'the model fixes the pre-reservation'); + $this->assertSame(ProcessProfile::MODEL, $inquiry->process()->source(ProcessSetting::PreReservation)); + $this->assertSame(['a4.portal_booking', CaseType::A4], [$booking->profile['plan']['model'], $booking->case_type]); + $this->assertSame($before, $running->fresh()->profile, 'K05: the running case keeps its frozen profile and plan'); + $this->assertSame(CaseType::A3, $running->fresh()->case_type); + } + + /** K07 */ + public function test_mandatory_steps_and_inadmissible_responsibilities_are_refused(): void + { + $fewo = $this->channel('FeWo-direkt', 'mixed'); + $configuration = app(ChannelProcessConfiguration::class); + + $this->assertNotSame([], $configuration->problems($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'steps' => ['binding.portal' => ['on' => false]]])); + $this->assertNotSame([], $configuration->problems($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'steps' => ['channels.block' => ['on' => false]]])); + $this->assertNotSame([], $configuration->problems($fewo, IntakeKind::Inquiry, ['model' => 'a2.offer', 'steps' => ['availability.check' => ['on' => false]]])); + $this->assertNotSame([], $configuration->problems($fewo, IntakeKind::Inquiry, ['model' => 'a2.offer', 'steps' => ['offer.acceptance' => ['on' => false]]])); + $this->assertNotSame([], $configuration->problems($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'settings' => ['payments' => 'landlord']]), 'A4 fixes portal collection'); + $this->assertSame([], $configuration->problems($fewo, IntakeKind::Inquiry, ['model' => 'a2.offer', 'steps' => ['review.request' => ['on' => false], 'guest.data_request' => ['on' => false]]]), 'optional steps may be switched off'); + } + + /** K08 / O1: a variable responsibility changes without a model change, a fixed one cannot */ + public function test_arrival_information_can_go_to_the_portal_within_a4_without_changing_the_model(): void + { + $fewo = $this->channel('FeWo-direkt', 'mixed'); + app(ConfigureChannelProcess::class)->handle($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'settings' => ['guest_messages' => 'portal']]); + + $booking = app(TakeOverExternalBooking::class)->handle($this->property, $fewo->fresh(), CarbonImmutable::parse('2027-07-10'), CarbonImmutable::parse('2027-07-17'), ['portal_reference' => 'HA-K08']); + + $this->assertSame([CaseType::A4, 'a4.portal_booking'], [$booking->case_type, $booking->profile['plan']['model']]); + $arrival = collect(CaseActivities::for($booking))->firstWhere('key', 'arrival_info'); + $this->assertSame(ActivityState::External, $arrival->state); + $documents = collect(CaseActivities::for($booking))->firstWhere('key', 'documents'); + $this->assertNotSame(ActivityState::External, $documents->state, 'the contract documentation stays ours in A4 (O1)'); + $this->assertNotSame([], app(ChannelProcessConfiguration::class)->problems($fewo->fresh(), IntakeKind::Booking, ['model' => 'a4.portal_booking', 'settings' => ['documents' => 'portal']]), 'contract documentation decides the case type'); + } + + /** N5 */ + public function test_a_switched_off_optional_step_is_skipped_and_has_no_effect(): void + { + $website = Channel::websiteOf($this->property); + app(ConfigureChannelProcess::class)->handle($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'steps' => ['review.request' => ['on' => false]]]); + $booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']); + $booking->forceFill(['status' => BookingStatus::Confirmed, 'confirmed_at' => now()])->saveQuietly(); + + $this->assertNull(collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'review')); + $preview = collect(app(ChannelProcessConfiguration::class)->preview($website->fresh(), IntakeKind::Inquiry, ['model' => 'a1.offer', 'steps' => ['review.request' => ['on' => false]]]))->firstWhere('module', 'review.request'); + $this->assertSame([false, 'im Kanal abgeschaltet'], [$preview['on'], $preview['reason']]); + + $this->travelTo(CarbonImmutable::parse('2026-11-13 10:00')); + app(RequestReviews::class)->handle(); + $this->assertNull($booking->fresh()->review_requested_at); + } + + /** K09 */ + public function test_the_loyalty_variant_can_be_drafted_but_not_saved(): void + { + $website = Channel::websiteOf($this->property); + $configuration = app(ChannelProcessConfiguration::class); + + $preview = collect($configuration->preview($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'variant' => 'loyalty'])); + $this->assertTrue($preview->firstWhere('module', 'pricing.loyalty_discount')['tester_only']); + $this->assertSame([], $configuration->problems($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'variant' => 'loyalty'], sandbox: true)); + + $this->expectException(ValidationException::class); + app(ConfigureChannelProcess::class)->handle($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'variant' => 'loyalty']); + } + + /** K03: the preview lists exactly the steps that show up on a new case */ + public function test_the_preview_matches_the_course_of_a_new_case(): void + { + $website = Channel::websiteOf($this->property); + $draft = ['model' => 'a1.offer']; + app(ConfigureChannelProcess::class)->handle($website, IntakeKind::Inquiry, $draft); + $booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org']); + + $preview = collect(app(ChannelProcessConfiguration::class)->preview($website->fresh(), IntakeKind::Inquiry, $draft))->where('on', true)->pluck('module')->all(); + $this->assertSame(array_keys($booking->profile['plan']['modules']), collect(app(ChannelProcessConfiguration::class)->preview($website->fresh(), IntakeKind::Inquiry, $draft))->pluck('module')->all()); + foreach (['offer.binding', 'offer.acceptance', 'documents.send', 'stay', 'case.settlement'] as $module) { + $this->assertContains($module, $preview); + } + $this->assertNotContains('offer.information', $preview); + } + + /** K02, K06, K10: the page in the simple view, inherited and set values with their origin */ + public function test_the_page_shows_the_steps_with_their_settings_and_saves(): void + { + $this->actingAs(User::factory()->create()); + $website = Channel::websiteOf($this->property); + + Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()]) + ->assertSee('Wie wird eine Anfrage über') + ->assertSee('Angebot mit Vorreservierung') + ->assertSee('Fehlende Angaben beim Gast anfragen') + ->assertSee('Pflicht') + ->assertSee('Vorschau: ein neuer Vorgang') + ->set('drafts.inquiry.settings.hold_hours', '24') + ->assertSee('hier gesetzt') + ->call('save') + ->assertHasNoErrors(); + + $profile = app(ProcessSettings::class)->forWebsite($this->property); + $this->assertSame(24, $profile->holdHours()); + $this->assertSame(ProcessProfile::WEBSITE, $profile->source(ProcessSetting::HoldHours)); + $this->assertSame('a1.offer', $website->fresh()->process_overrides['inquiry']['model']); + } + + private function channel(string $name, string $model): Channel + { + return Channel::factory()->for($this->property)->create(['name' => $name, 'booking_model' => $model, 'import_enabled' => false, 'settings' => ['import_url' => 'https://portal.example/'.md5($name).'.ics']]); + } +}