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

241 lines
10 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\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();
}
/**
* 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->drafts[$this->intake]);
$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])),
];
}
}