Files
fewo-stommer/app/Filament/Resources/Channels/Pages/ChannelProcess.php
T

490 lines
23 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Resources\Channels\Pages;
use App\Actions\ConfigureChannelProcess;
use App\Communication\CommunicationRules;
use App\Enums\AdminMode;
use App\Enums\Execution;
use App\Enums\IntakeKind;
use App\Enums\Medium;
use App\Enums\MessageEffect;
use App\Enums\MessageIntent;
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\Capability;
use App\Process\ChannelCapabilities;
use App\Process\ChannelProcessConfiguration;
use App\Process\ConfigurationImpact;
use App\Process\Models\ProcessModel;
use App\Process\ProcessCatalogue;
use App\Process\ProcessLanes;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Process\Restriction;
use App\Process\Templates\FunctionTemplate;
use App\Process\Templates\TemplateArea;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
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>, templates: array<string, string>}> */
public array $drafts = [];
/** @var array<string, string> capability key => '1' | '0' | '' (unknown); saving confirms what is shown */
public array $capabilityDraft = [];
/** The landlord confirmed that stored settings the chosen model overrides are removed. */
public bool $acknowledge = false;
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] ?? []);
// The current (saved or derived) model stays selected even if it is not admissible: the page explains why instead of
// switching silently to another one.
$model = $current['model'];
$this->drafts[$intake->value] = [
'model' => $model,
'variant' => $current['variant'],
'steps' => (array) ($stored['steps'] ?? []),
'templates' => (array) ($stored['templates'] ?? []),
'settings' => array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, array_intersect_key($stored, array_flip(array_map(fn (ProcessSetting $setting): string => $setting->value, ProcessSetting::cases())))),
'derived' => $current['derived'],
];
}
$this->intake = (string) array_key_first($this->drafts);
$this->capabilityDraft = $this->record->isWebsite() ? [] : collect(app(ChannelCapabilities::class)->resolve($this->record))
->map(fn (Capability $capability): string => $capability->value === null ? '' : ($capability->value ? '1' : '0'))->all();
}
/**
* The draft of the current intake kind including the capabilities shown (they decide which models fit).
*
* @return array<string, mixed>
*/
private function draft(): array
{
return [...$this->drafts[$this->intake], 'capabilities' => $this->capabilityDraft];
}
/**
* @return array<string, Capability>
*/
public function capabilities(): array
{
return app(ChannelCapabilities::class)->resolve($this->record, $this->capabilityDraft);
}
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?';
}
/**
* Every model of this intake kind with whether the channel fits it and why not.
*
* @return array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}>
*/
public function models(): array
{
return app(ChannelProcessConfiguration::class)->modelOptions($this->record, IntakeKind::from($this->intake), $this->capabilityDraft);
}
/**
* Stored settings the chosen model would silently override.
*
* @return list<array{setting: ProcessSetting, stored: string, fixed: string, text: string}>
*/
public function conflicts(): array
{
return app(ChannelProcessConfiguration::class)->conflicts($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]['model'], $this->drafts[$this->intake]['templates']);
}
/**
* The models offered as a choice: the archetypes A3–A5 are presets of the base process, so they only appear while one
* of them is the current choice (then with the hint to move to the templates).
*
* @param array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}> $models
* @return array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}>
*/
public function visibleModels(array $models): array
{
return array_filter($models, fn (array $option, string $key): bool => ! $option['model']::isLegacy() || $key === $this->drafts[$this->intake]['model'], ARRAY_FILTER_USE_BOTH);
}
/**
* Whether the chosen model composes function templates (otherwise its course is fixed).
*/
public function composable(): bool
{
return $this->model()->slots() !== [];
}
/**
* The business decisions of the chosen base process: per slot the templates with fit, selection and what each stands
* for. The first view of the configurator; the single steps stay below.
*
* @return list<array{area: TemplateArea, selected: ?string, options: list<array{key: string, template: class-string<FunctionTemplate>, admissible: bool, selected: bool, restrictions: list<Restriction>, hints: list<string>, unconfirmed: list<string>, modules: list<string>}>}>
*/
public function decisions(): array
{
$model = $this->model();
if ($model->slots() === []) {
return [];
}
$configuration = app(ChannelProcessConfiguration::class);
$catalogue = app(ProcessCatalogue::class);
$resolved = $configuration->templatesOf($model, $this->draft());
$options = $configuration->templateOptions($this->record, $model, $this->capabilityDraft);
$decisions = [];
foreach ($model->slots() as $area) {
$selected = isset($resolved[$area->value]) ? explode('@', $resolved[$area->value])[0] : null;
$decisions[] = [
'area' => $area,
'selected' => $selected,
'options' => array_values(array_map(fn (array $option, string $key): array => [
...$option,
'key' => $key,
'selected' => $key === $selected,
'modules' => array_map(fn (string $module): string => $catalogue->modules()[$module]::definition()->label, $option['template']::modules()),
], $options[$area->value] ?? [], array_keys($options[$area->value] ?? []))),
];
}
return $decisions;
}
/**
* The archetypes as known combinations (presets) the landlord can start from.
*
* @return array<string, array{label: string, templates: array<string, string>}>
*/
public function presets(): array
{
$presets = [];
foreach (app(ProcessCatalogue::class)->models() as $key => $candidate) {
if ($candidate::isLegacy() && in_array(IntakeKind::from($this->intake), $candidate::intakes(), true)) {
$presets[$key] = ['label' => $candidate::label(), 'templates' => $candidate::presetTemplates()];
}
}
return $presets;
}
/**
* Chooses the template of an area. Switches of steps that drop out of the course are removed from the draft; the
* consequences are listed by templateImpacts() before anything is saved.
*/
public function chooseTemplate(string $area, string $key): void
{
$model = $this->model();
$option = app(ChannelProcessConfiguration::class)->templateOptions($this->record, $model, $this->capabilityDraft)[$area][$key] ?? null;
if ($option === null || ! $option['admissible']) {
return;
}
$this->acknowledge = false;
$this->drafts[$this->intake]['templates'] = [...app(ChannelProcessConfiguration::class)->templatesOf($model, $this->draft()), $area => $key];
$this->drafts[$this->intake]['templates'] = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->drafts[$this->intake]['templates']);
$modules = $model->modules($this->drafts[$this->intake]['variant'], $this->drafts[$this->intake]['templates']);
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($modules));
}
/**
* Moves from a fixed archetype to the base process with the combination the archetype stands for. Switches and settings
* stay as they are; what contradicts the templates shows as a conflict that has to be confirmed.
*/
public function applyPreset(string $archetype): void
{
$presets = $this->presets();
$composedBy = isset($presets[$archetype]) ? app(ProcessCatalogue::class)->model($archetype)::composedBy() : null;
if ($composedBy === null) {
return;
}
$base = app(ProcessCatalogue::class)->model($composedBy);
$this->acknowledge = false;
$this->drafts[$this->intake]['model'] = $base::key();
$this->drafts[$this->intake]['variant'] = 'standard';
$this->drafts[$this->intake]['templates'] = $presets[$archetype]['templates'];
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($base->modules('standard', $presets[$archetype]['templates'])));
}
/**
* The course as the runner executes it: parallel, waiting (with what for), event-driven, time-driven, not applying.
*
* @return array<string, list<array<string, mixed>>>
*/
public function lanes(): array
{
return app(ProcessLanes::class)->of($this->steps());
}
/**
* What arrives here and how binding it is (the start of the course).
*
* @return array{event: string, binding: string, media: list<string>}
*/
public function entry(): array
{
$rules = app(CommunicationRules::class);
$media = array_values(array_map(fn (Medium $medium): string => $medium->getLabel(), array_filter(Medium::cases(), fn (Medium $medium): bool => $rules->mediumActive($medium))));
$booking = $this->intake === IntakeKind::Booking->value;
return [
'event' => $booking ? 'Eine feste Buchung kommt über '.$this->record->name.' an (Portalmail, Kalender).' : ($this->record->isWebsite() ? 'Ein Gast fragt über die Webseite einen Aufenthalt an.' : 'Eine Anfrage kommt über '.$this->record->name.' an.'),
'binding' => $booking ? 'Beim Portal bereits verbindlich – wir übernehmen, wir verbinden nichts neu.' : 'Unverbindlich – verbindlich wird sie durch unser Angebot und die Annahme des Gastes.',
'media' => $media,
];
}
/**
* What a message does here, by its intent – the rules (not a process): a general question creates no case.
*
* @return list<array{intent: string, effects: list<string>, creates_case: bool}>
*/
public function messageRules(): array
{
$rules = app(CommunicationRules::class);
return array_map(fn (MessageIntent $intent): array => [
'intent' => $intent->getLabel(),
'effects' => array_map(fn (MessageEffect $effect): string => $effect->getLabel(), $rules->effects(Medium::Email, $intent)),
'creates_case' => false,
], MessageIntent::cases());
}
/**
* What the draft's change of templates means (modules, responsibilities, stored switches and settings).
*
* @return list<array<string, mixed>>
*/
public function templateImpacts(): array
{
return app(ConfigurationImpact::class)->ofTemplates($this->record, IntakeKind::from($this->intake), $this->draft());
}
public function chooseModel(string $model): void
{
if (! ($this->models()[$model]['admissible'] ?? false)) {
return;
}
$this->acknowledge = false;
// Leaving an archetype for a model with slots keeps its combination as the starting point of the templates.
$previous = app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']);
$this->drafts[$this->intake]['model'] = $model;
$this->drafts[$this->intake]['variant'] = 'standard';
$this->drafts[$this->intake]['templates'] = $this->model()->slots() === [] ? [] : $previous::presetTemplates();
// Switches of steps the new course still has stay; only those that have no counterpart there drop out.
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($this->model()->modules('standard', $this->drafts[$this->intake]['templates'])));
}
public function model(): ProcessModel
{
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->draft());
}
/**
* 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];
$rows = $configuration->preview($this->record, IntakeKind::from($this->intake), $this->draft());
$labels = collect($rows)->mapWithKeys(fn (array $row): array => [$row['module'] => $row['label']]);
$active = collect($rows)->where('on', true)->pluck('module')->all();
return array_map(function (array $row) use ($configuration, $catalogue, $model, $profile, $labels, $active): array {
$definition = $catalogue->modules()[$row['module']]::definition();
// The view of the order is derived from the same definitions the runner uses: only dependencies present in the plan count.
$needs = collect($definition->requires)->filter(fn ($dependency): bool => $dependency->hard && in_array($dependency->module, $active, true))->map(fn ($dependency): string => $labels[$dependency->module])->values()->all();
$after = collect($definition->requires)->filter(fn ($dependency): bool => ! $dependency->hard && in_array($dependency->module, $active, true))->map(fn ($dependency): string => $labels[$dependency->module])->values()->all();
$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, ProcessSetting::ContractDelivery, ProcessSetting::BookingNotice, ProcessSetting::AwaitPortalConfirmation, ProcessSetting::PortalConfirmationWaitHours], true))));
return [...$row,
'purpose' => $definition->purpose,
'needs' => $needs,
'after' => $after,
'condition' => $definition->condition,
'why' => $definition->why,
'executions' => array_map(fn (Execution $execution): string => $execution->getLabel(), $definition->executions),
'triggers' => $definition->triggers,
'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), 'options' => $configuration->settingOptions($setting)], $parameters),
];
}, $rows);
}
/**
* 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->draft());
}
/**
* What the switched-off steps of the draft mean for the others (suggestions only, nothing is changed).
*
* @return list<array<string, mixed>>
*/
public function impacts(): array
{
return app(ConfigurationImpact::class)->of($this->record, IntakeKind::from($this->intake), $this->draft());
}
/**
* 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->draft(), acknowledgeConflicts: $this->acknowledge);
} catch (ValidationException $exception) {
Notification::make()->title('Nicht gespeichert')->body(collect($exception->errors())->flatten()->implode(' '))->danger()->persistent()->send();
return;
}
$this->drafts[$this->intake]['derived'] = false;
$this->acknowledge = false;
$intake = $this->intake;
$this->mount($this->record->getKey());
$this->intake = $intake;
$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();
}
/**
* Opens the process tester with the current – also unsaved – draft of this intake kind.
*/
public function test(): void
{
session()->put('process-tester.draft.'.$this->record->id.'.'.$this->intake, $this->draft());
$this->redirect(ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake]));
}
/**
* 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])),
];
}
}