U-C: Kanalkonfigurator (Kanal › Ablauf): Modellwahl nach Kanalprofil (E2/O2), Schritte mit Schalter, Ausführung, Ausführenden und Fristen, Herkunft der Werte, Vorschau; ConfigureChannelProcess; Modell legt Einstellungen fest

Flache Prozessfelder im Kanalformular entfallen als Hauptansicht. Volle Suite 820/820.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 15:04:28 +01:00
1 parent d695566a7a
commit c255783cec
13 files changed
+981 -50

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Actions;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Channel;
use App\Process\ChannelProcessConfiguration;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
/**
* Saves the process of a channel for one intake kind (Kanal › Ablauf, docs/Prozessarchitektur/Architektur/03): the
* chosen model and variant, the step switches and the step settings – in channels.process_overrides[intake], next to
* the existing settings, so their inheritance stays as it is. Refuses everything the configuration does not admit
* (mandatory steps off, responsibilities the model does not allow, tester-only variants). Changes apply to new cases
* only (decision E3): running cases keep their frozen plan.
*/
class ConfigureChannelProcess
{
public function __construct(private ChannelProcessConfiguration $configuration) {}
/**
* @param array{model: string, variant?: string, steps?: array<string, array{on?: bool}>, settings?: array<string, mixed>} $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;
});
}
}
@@ -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'),
];
}
}
@@ -0,0 +1,231 @@
<?php
namespace App\Filament\Resources\Channels\Pages;
use App\Actions\ConfigureChannelProcess;
use App\Enums\AdminMode;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use App\Process\Models\ProcessModel;
use App\Process\ProcessCatalogue;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Illuminate\Validation\ValidationException;
/**
* Kanal › Ablauf (docs/Prozessarchitektur/Architektur/03): per intake kind of the channel the landlord chooses an
* admissible process model and sets up its steps right where they are – switch, mode, who carries it out, deadlines –
* with the inherited value and its origin, the consequences in a live preview and a test of the (unsaved) draft in the
* process tester. Saving goes through ConfigureChannelProcess; running cases keep their frozen plan (E3).
*
* @property Channel $record
*/
class ChannelProcess extends Page
{
use InteractsWithRecord;
protected static string $resource = ChannelResource::class;
protected static ?string $title = 'Ablauf';
protected string $view = 'filament.resources.channels.channel-process';
public string $intake = 'inquiry';
/** @var array<string, array{model: string, variant: string, steps: array<string, array{on?: bool}>, settings: array<string, mixed>}> */
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<string, string> 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<string, ProcessModel>
*/
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<array<string, mixed>>
*/
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<string>
*/
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])),
];
}
}
@@ -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;
}
@@ -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<Section>
* @return list<Component>
*/
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'),
];
}
}
+256
View File
@@ -0,0 +1,256 @@
<?php
namespace App\Process;
use App\Enums\ChannelBookingModel;
use App\Enums\DataRequestMode;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Channel;
use App\Process\Models\ProcessModel;
use App\Process\Models\Responsibilities;
/**
* What the channel configurator offers and checks (docs/Prozessarchitektur/Architektur/03): per channel and intake
* kind the admissible models (portal profile, E2/O2), and per step of the chosen model its switch, mode, performer
* and parameters – each control mapped to the existing process setting where one exists, so the inheritance landlord →
* property → channel stays the one mechanism. Pure: reads, never writes (ConfigureChannelProcess saves).
*/
final class ChannelProcessConfiguration
{
/**
* Controls of the steps: mode and performer stored as existing settings, parameters per module.
*
* @var array<string, array{mode?: ProcessSetting, performer?: array{field: string, setting: ProcessSetting}, parameters?: list<ProcessSetting>}>
*/
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<IntakeKind>
*/
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<string, ProcessModel>
*/
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<string, string> 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<string, string>
*/
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<string, mixed> $draft model, variant, steps, settings of channels.process_overrides[intake]
* @return list<array{module: string, label: string, phase: string, on: bool, reason: ?string, performer: ?string, mode: ?string, toggle: string, tester_only: bool, inserted: bool}>
*/
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<string, mixed> $draft
* @return list<string>
*/
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<string, mixed> $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);
}
}
+4
View File
@@ -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',
};
+27
View File
@@ -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).
+14
View File
@@ -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,
@@ -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
<x-filament::section heading="So lesen Sie diese Übersicht" collapsible collapsed>
@@ -0,0 +1,138 @@
<x-filament-panels::page>
@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)
<div style="display:flex;gap:.5rem">
@foreach ($this->tabs() as $key => $label)
<x-filament::button :color="$this->intake === $key ? 'primary' : 'gray'" wire:click="$set('intake', '{{ $key }}')">{{ $label }}</x-filament::button>
@endforeach
</div>
@endif
<x-filament::section :heading="$this->question()" :description="$draft['derived'] ? 'Noch nicht gewählt: abgeleitet aus Ihren bisherigen Einstellungen. Gespeichert wird erst, wenn Sie speichern.' : null">
@if ($models === [])
<p>Für diesen Kanal ist für diese Eingangsart kein Ablaufmodell freigegeben (Kanalprofil). Vorgänge folgen weiter dem aus den Einstellungen abgeleiteten Ablauf.</p>
@endif
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(16rem,1fr));gap:.6rem" role="radiogroup" aria-label="Ablaufmodell">
@foreach ($models as $key => $candidate)
<button type="button" role="radio" aria-checked="{{ $draft['model'] === $key ? 'true' : 'false' }}" wire:click="chooseModel('{{ $key }}')"
style="{{ $card }};text-align:left;{{ $draft['model'] === $key ? 'border-color:rgb(var(--primary-600));box-shadow:0 0 0 1px rgb(var(--primary-600))' : '' }}">
<strong>{{ $candidate::label() }}</strong>
<span style="{{ $muted }}"> · {{ implode('/', array_map(fn ($type) => strtoupper($type->value), $candidate::caseTypes())) }}</span>
<div style="font-size:.85rem;margin-top:.3rem">{{ $candidate::description() }}</div>
</button>
@endforeach
</div>
@if (count($model->variants()) > 1)
<div style="margin-top:.8rem">
<label style="font-size:.9rem">Variante
<select wire:model.live="drafts.{{ $this->intake }}.variant" style="{{ $input }};margin-left:.4rem">
@foreach ($model->variants() as $variant)
<option value="{{ $variant->key }}">{{ $variant->label }}</option>
@endforeach
</select>
</label>
@if ($model->variant($draft['variant'])?->isTesterOnly())
<p style="color:#b45309;font-size:.85rem;margin-top:.3rem">Nur im Prozess-Tester verwendbar (Architekturnachweis). Sie können diese Variante mit „Ablauf testen“ durchspielen, aber nicht speichern.</p>
@endif
</div>
@endif
</x-filament::section>
@if ($problems !== [])
<x-filament::section heading="Nicht zulässig">
<ul style="color:#b91c1c;font-size:.9rem;list-style:disc;padding-left:1.2rem">
@foreach ($problems as $problem)<li>{{ $problem }}</li>@endforeach
</ul>
</x-filament::section>
@endif
<div style="display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr);gap:1rem;align-items:start">
<div>
@foreach (collect($steps)->groupBy('phase') as $phase => $group)
<h3 style="font-weight:600;margin:.6rem 0 .3rem">{{ $phases[$phase] ?? $phase }}</h3>
@foreach ($group as $index => $step)
<div style="{{ $card }};{{ $step['on'] ? '' : 'opacity:.6' }}" wire:key="step-{{ $this->intake }}-{{ $step['module'] }}">
<div style="display:flex;justify-content:space-between;gap:.5rem;align-items:center">
<strong>{{ $step['label'] }}
@if ($step['tester_only'])<span style="color:#b45309;font-size:.75rem"> · nur im Prozess-Tester</span>@endif
@if ($step['inserted'])<span style="{{ $muted }}"> · Zusatzschritt der Variante</span>@endif
</strong>
@if ($step['optional'])
<x-filament::button size="xs" :color="($draft['steps'][$step['module']]['on'] ?? true) === false ? 'gray' : 'success'" wire:click="toggleStep('{{ $step['module'] }}')">
{{ ($draft['steps'][$step['module']]['on'] ?? true) === false ? 'aus' : 'an' }}
</x-filament::button>
@else
<span style="{{ $muted }}" title="Pflichtschritt – nicht abschaltbar">🔒 Pflicht</span>
@endif
</div>
<div style="font-size:.85rem;margin-top:.25rem">{{ $step['purpose'] }}</div>
<div style="{{ $muted }};margin-top:.25rem">
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']) · <em>übersprungen: {{ $step['reason'] }}</em>@endif
@if ($this->expert()) · <code>{{ $step['module'] }}</code> v{{ $step['version'] }}@endif
</div>
@if ($step['mode_setting'] && $step['mode_options'] !== [])
<label style="display:block;font-size:.85rem;margin-top:.4rem">Ausführung
<select wire:model.live="drafts.{{ $this->intake }}.settings.{{ $step['mode_setting']->value }}" style="{{ $input }};margin-left:.4rem">
<option value="">wie Standard</option>
@foreach ($step['mode_options'] as $value => $label)<option value="{{ $value }}">{{ $label }}</option>@endforeach
</select>
<span style="{{ $muted }}">{{ $this->setting($step['mode_setting'], $this->profile())['source'] }}</span>
</label>
@endif
@if ($step['performer_setting'] && count($step['performer_options']) > 1)
<label style="display:block;font-size:.85rem;margin-top:.4rem">Wer sendet
<select wire:model.live="drafts.{{ $this->intake }}.settings.{{ $step['performer_setting']->value }}" style="{{ $input }};margin-left:.4rem">
<option value="">wie Standard</option>
@foreach ($step['performer_options'] as $value => $label)<option value="{{ $value }}">{{ $label }}</option>@endforeach
</select>
<span style="{{ $muted }}">im Rahmen des Modells wählbar, ohne Modellwechsel</span>
</label>
@endif
@foreach ($step['parameters'] as $parameter)
<label style="display:block;font-size:.85rem;margin-top:.4rem">{{ $parameter['question'] }}
<input type="text" wire:model.live.debounce.600ms="drafts.{{ $this->intake }}.settings.{{ $parameter['key'] }}" placeholder="{{ $parameter['value'] }}" style="{{ $input }};width:8rem;margin-left:.4rem">
<span style="{{ $muted }}">wirksam: {{ $parameter['value'] }} ({{ $parameter['source'] }})</span>
@if ($parameter['set'])
<button type="button" wire:click="inherit('{{ $parameter['key'] }}')" style="{{ $muted }};text-decoration:underline">auf geerbten Wert zurücksetzen</button>
@endif
</label>
@endforeach
</div>
@endforeach
@endforeach
</div>
<x-filament::section heading="Vorschau: ein neuer Vorgang" description="Mit den aktuellen, auch ungespeicherten Einstellungen. Es wird nichts gespeichert und nichts ausgeführt.">
<ol style="font-size:.85rem;list-style:decimal;padding-left:1.2rem">
@foreach ($steps as $step)
<li style="{{ $step['on'] ? '' : 'color:#9ca3af;text-decoration:line-through' }}">
{{ $step['label'] }}
<span style="{{ $muted }}">– {{ $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'] }}</span>
</li>
@endforeach
</ol>
<p style="{{ $muted }};margin-top:.6rem">Gilt für neue Vorgänge. Laufende Vorgänge dieses Kanals ({{ $this->runningCases() }}) behalten ihren bisherigen Ablauf.</p>
@if (\Illuminate\Support\Facades\Route::has('filament.admin.resources.channels.test'))
<x-filament::button tag="a" color="gray" :href="\App\Filament\Resources\Channels\ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake])" style="margin-top:.6rem">Ablauf testen</x-filament::button>
@endif
</x-filament::section>
</div>
</x-filament-panels::page>
+7 -4
View File
@@ -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());
@@ -0,0 +1,214 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\ConfigureChannelProcess;
use App\Actions\CreateReservation;
use App\Actions\RequestReviews;
use App\Actions\TakeOverExternalBooking;
use App\Actions\TakeOverPortalInquiry;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Filament\Resources\Channels\Pages\ChannelProcess;
use App\Models\Channel;
use App\Models\Property;
use App\Models\User;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ChannelProcessConfiguration;
use App\Process\ProcessPlan;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Support\Content;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Package U-C: the channel configurator (docs/Prozessarchitektur/Architektur/03, criteria K01–K10, N4, N5).
*/
#[Group('configurator')]
class ChannelProcessConfiguratorTest extends TestCase
{
use RefreshDatabase;
private Property $property;
protected function setUp(): void
{
parent::setUp();
$this->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' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
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']]);
}
}