Compare commits

..
Author SHA1 Message Date
LarsandClaude 86965d6d45 Merge feature/prozess-konfigurator: visueller Prozesskonfigurator mit fachlichen Prozessblöcken
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m52s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-14 17:25:16 +01:00
LarsandClaude Sonnet 5.5 3cbca35fcb STATUS: visueller Prozesskonfigurator
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 15:55:14 +01:00
LarsandClaude Sonnet 5.5 664f00e510 Prozesskonfigurator: fachliche Prozessblöcke als Hauptansicht, Detailpanel je Block, Entwurf verwerfen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 15:55:04 +01:00
Lars 4554af8056 Merge feature/anfrage-basisprozess: Anfrage-Basisprozess, Schablonen für alle Geschäftsvorfälle
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m35s
2026-11-05 12:52:14 +01:00
LarsandClaude Sonnet 5.5 f2b6626f6a Doku: Katalog-Präzisierungen und Umsetzungsstand
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:45:59 +01:00
LarsandClaude Sonnet 5.5 b1b09a6db4 Konfigurator: Ablauf im Zusammenhang aus dem Plan, Nachrichtenregeln, einheitliche Anfrage-/Buchungsansicht; Abnahmetests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:45:46 +01:00
LarsandClaude Sonnet 5.5 221ce8ca81 Anfrage-Basisprozess inquiry.request mit Schablonen für Antwort und Gastkommunikation
Antwortart (Auskunft/Angebot) und Reservierung sind entkoppelt (neue Einstellung inquiry_answer;
pre_reservation bleibt die Reservierungsstrategie). Anlass-bezogene Absender für Anreise-Information
und Bewertungsbitte; Schablonen liefern Standardwerte unterhalb aller einstellbaren Ebenen.
A1/A2 bleiben Voreinstellungen und Altfassungen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:40:22 +01:00
LarsandClaude Sonnet 5.5 e40f8639b3 Schablonenkatalog für alle Geschäftsvorfälle; Modulmatrix mit external.booking neu erzeugt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:21:39 +01:00
LarsandClaude Sonnet 5.5 eba1a4d094 Test: Data-Provider-Signatur korrigiert (PHPUnit-Warnung brach die Pipeline ab)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 11:48:37 +01:00
Lars e1d0f6b023 Merge feature/schablonenkomposition: Funktionsschablonen für extern verbindliche Buchungen
Deploy FeWo mit PipelineManager / deploy (push) Failing after 5m14s
2026-11-05 11:03:36 +01:00
LarsandClaude Sonnet 5.5 6f14437855 Test: Zahlungsanforderungen nur bei eigenem Inkasso, nie doppelt; Doku der operativen Stellen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 11:03:36 +01:00
LarsandClaude Sonnet 5.5 c46f4a032b Kanalkonfigurator und Prozess-Tester auf Schablonenbasis
Geschäftsentscheidungen zuerst (Schablonen je Bereich, Voreinstellungen A3–A5), Einzelschritte
eingeklappt, Auswirkungsanalyse beim Schablonenwechsel, unbestätigte Portal-Fähigkeiten gekennzeichnet.
Tester-Bericht nennt Schablonen, unabhängig laufende Schritte und fehlende Nachweise; alle vier
Kombinationen sind als Szenario getestet. Doku: SCHABLONEN.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:56:51 +01:00
LarsandClaude Sonnet 5.5 e95ba4f986 Schablonenkomposition: Basisprozess external.booking mit Platz für Finanz- und Dokumentenschablonen
Vier Schablonen (Eigenes/Portal-Inkasso, Eigene/Externe Vertragsdokumentation) in
app/Process/Templates, TemplateComposer prüft Ergebnisse, Verantwortlichkeiten, Ausschlüsse
und harte Modulabhängigkeiten. Der Plan friert die Schablonenversionen ein. A3–A5 bleiben
als Voreinstellungen; die vierte Kombination (eigenes Inkasso + externe Unterlagen) ist
darstellbar. Konfigurator-Logik und ConfigureChannelProcess kennen die Schablonenwahl.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:48:49 +01:00
LarsandClaude Sonnet 5.5 381720763c Modul-Konfigurationsmatrix und Auswirkungs-Abgleich im Kanalkonfigurator
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m16s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 09:51:33 +01:00
LarsandClaude Sonnet 5.5 a3ab1b6657 Kanalkonfigurator: bestätigter Modellwechsel (A4→A3) speicherbar
Veraltete Altwerte (payments/guest_messages = portal), die das gewählte Modell überstimmt,
blockierten das Speichern trotz bestätigter Übernahme: problems() prüfte den Entwurf vor der
Entfernung, und nicht erlaubte variable Verantwortlichkeiten zählten nicht als Konflikt.
Jetzt: conflicts() listet auch nicht mehr erlaubte Verantwortlichkeiten, problems()/profileWith()
ignorieren die zu entfernenden Altwerte. Regressionstests A3/A4, Altwerte, Bestätigung, laufende Vorgänge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 09:41:31 +01:00
LarsandClaude Sonnet 5.5 8ad71c54d2 Merge feature/prozessarchitektur-v2-1: V2.1 fachliche Konfigurierbarkeit
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m22s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:18:10 +01:00
LarsandClaude Sonnet 5.5 e5cbc6faca Status: V2.1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:18:02 +01:00
LarsandClaude Sonnet 5.5 0d51c673eb V2.1: Erweiterungspunkt-Nachweis, Fälle G/H, Abnahmeprotokoll, Status
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:17:51 +01:00
LarsandClaude Sonnet 5.5 fdf226535b V2.1: nichtlineare Prozessansicht, Begründung der Pflichtschritte, Bedienelemente der neuen Einstellungen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:07:10 +01:00
LarsandClaude Sonnet 5.5 f8561fe0e5 V2.1: Tester-Szenarien Portalbestätigung, Nachricht über anderes Medium, allgemeine Frage
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 08:02:52 +01:00
LarsandClaude Sonnet 5.5 8026eceab4 V2.1: Kommunikation nach Medium, Absicht und Wirkung (Fälle E/F)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:57:54 +01:00
LarsandClaude Sonnet 5.5 8442d0a3d8 V2.1: Kanalfähigkeiten, Ausführungsvarianten, Dokumentenentkopplung, Portalbestätigung
Modellwahl über Kanalfähigkeiten mit erklärten Einschränkungen, Abgleich alter Werte,
Ausführungsvarianten je Modul, getrennte Vertrags-/Buchungsinformation, Warten auf
die Portalbestätigung mit Eskalation und Wiederaufnahme (Fälle C und D getestet).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:54:11 +01:00
LarsandClaude Sonnet 5.5 ef1635e59a V2.1 Phase 1: Konfigurationslücken (Matrix gegen ursprüngliche Beschlüsse und V2) und fachliches Zielbild
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:37:32 +01:00
LarsandClaude Opus 5.5 4410fb3ee0 Abschlussbericht: Bereitstellung auf stommer.info und technische Prüfung
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:09:34 +01:00
LarsandClaude Opus 5.5 9f63059461 Merge feature/prozessarchitektur-v2 (Bereitstellungsstand)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 6m30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:42:06 +01:00
LarsandClaude Opus 5.5 ee4911029e Abschlussbericht: Stand der Bereitstellung (Push nach Gitea mangels Anmeldung nicht möglich)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:42:05 +01:00
LarsandClaude Opus 5.5 79f3344568 Merge feature/prozessarchitektur-v2: kontrolliert modulare Prozessarchitektur V2 (Prozesskern, Kanalkonfigurator, Prozess-Tester, Kanalereignisse)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:41:39 +01:00
LarsandClaude Opus 5.5 dba6292cd4 Dokumentation V2: Entscheidungen O1–O5, T1–T3, Umsetzungsstand, Abschlussbericht, Abnahmeprotokoll, Betrieb, Löschkonzept, Status, Modulmatrix
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:41:24 +01:00
LarsandClaude Opus 5.5 0689c0a591 U-D/U-E/O5: Prozess-Tester im eigenen Prozess (standardmäßig gesperrt, 15 Negativtests, statischer Wächter), Szenarien und Bericht, Kanalereignisse (API-Eingang ohne Umbau von iCal/Mail), Abschluss nach finanzieller Klärung, Löschfrist 30 Tage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:34:40 +01:00
LarsandClaude Opus 5.5 c255783cec 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>
2026-11-04 15:04:28 +01:00
LarsandClaude Opus 5.5 d695566a7a U-A: process:check/impact/fingerprint, Modulmatrix, Modul-Vertragstest, O4-Aussetzung der Außenwirkungen (I-002), Bewertungsbitte je Kanal abschaltbar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:53:08 +01:00
LarsandClaude Opus 5.5 7e22e12cac U-A/U-B: Prozesskern mit Fachmodulen, versionierten Modellen, eingefrorenem Prozessplan, ProcessRunner (harte/weiche Abhängigkeiten), CasePricing, Loyalty nur im Tester
CaseActivities/CaseAutomation sind Fassaden über ProcessRunner. Verhaltensvergleich v0.11:
11 Abläufe und 198 Konstellationen gleich, beabsichtigte Abweichungen I-004/I-005 (F-001/F-002).
Volle Suite vor U-B: 785/785.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:49:44 +01:00
LarsandClaude Opus 5.5 98df5e9e3b U-0: Bestandsaufnahme, Verhaltensreferenz v0.11 (11 Abläufe, 198 Konstellationen), Bestandsfälle, Fehlerregister
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:28:35 +01:00
LarsandClaude Opus 5.5 750c1ed1d9 Architekturplan Review V2: Runner, Modulgrenzen, Versionierung, Kanalereignisse, Sandbox-Anfrage (Planung)
Korrekturen K1-K10 in die Dokumente 00-06 eingearbeitet: abhaengigkeitsbasierter
ProcessRunner mit Nachweisszenario, Kriterien fuer Modulgrenzen, vier
Versionierungsebenen mit Bestandsfall-Tests, Stufen M1-M4 und Ereignisvertraege,
Prozess-Tester in eigener Sandbox-Anfrage mit Negativtests, Verantwortungsmatrix
A1-A6, Deploymentweg ueber develop/stommer.info, Loyalty nur im Tester,
Verhaltensvergleich in acht Dimensionen, Kanalereignisse als Ergaenzung.
E1-E9 als entschieden gekennzeichnet; offen nur O1-O5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:37:45 +01:00
LarsandClaude Opus 5.5 86f2d0aa07 Architekturplan: kontrolliert modulare Prozessarchitektur, Kanalkonfigurator, Prozess-Tester (Planung)
Bewertung, Fachmodulkatalog mit Verträgen, Prozessmodelle und Erweiterungspunkte
(Loyalty-Nachweis), Kanalkonfigurator, isolierter Prozess-Tester, Änderungsanalyse,
Migrations- und Umsetzungsplan sowie Management-Zusammenfassung. Keine Codeänderung.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:59:14 +01:00
LarsandClaude Opus 5.5 ef2783ecfb Ergänzungsvorschlag Kanalkonfigurator: Schablonen, Schritte, Nachweise, Vorschau (nicht normativ)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:58:51 +01:00
266 changed files with 48573 additions and 526 deletions

No files matched your search

+4
View File
@@ -5,6 +5,7 @@
use App\Models\Booking; use App\Models\Booking;
use App\Models\Guest; use App\Models\Guest;
use App\Models\PortalEmail; use App\Models\PortalEmail;
use App\Models\ProcessTestRun;
/** /**
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and * GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
@@ -44,6 +45,9 @@ public function handle(): int
private function purgeOperationalData(): void private function purgeOperationalData(): void
{ {
// Process tester reports (synthetic data only, decision O3).
ProcessTestRun::query()->where('created_at', '<', now()->subDays(config('fewo.retention.process_test_run_days')))->delete();
PortalEmail::query() PortalEmail::query()
->whereNotNull('excerpt') ->whereNotNull('excerpt')
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days'))) ->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
+7 -4
View File
@@ -8,6 +8,7 @@
use App\Documents\DocumentFinding; use App\Documents\DocumentFinding;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\InquiryAnswer;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
use App\Models\Booking; use App\Models\Booking;
@@ -49,14 +50,16 @@ public function blockers(Booking $booking): array
{ {
$property = $booking->property; $property = $booking->property;
$reasons = []; $reasons = [];
$information = ! $booking->process()->preReservation(); $information = $booking->process()->inquiryAnswer() === InquiryAnswer::Information;
if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) { if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) {
$reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.'; $reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.';
} }
// A request after its clarification hold (v0.11) only needs free dates, which are checked below. // A request after its clarification hold (v0.11) only needs free dates, which are checked below.
$clarified = $booking->hold_purpose === Booking::HOLD_CLARIFICATION; $clarified = $booking->hold_purpose === Booking::HOLD_CLARIFICATION;
if (! $information && ($booking->status !== BookingStatus::Reserved || (! $clarified && ! $booking->isHoldActive()))) { // Without a reservation at the request (offer without early hold) the offer itself creates the hold; availability is checked below.
$holdRequired = $booking->process()->preReservation();
if (! $information && ($booking->status !== BookingStatus::Reserved || ($holdRequired && ! $clarified && ! $booking->isHoldActive()))) {
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).'; $reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
} }
if (blank($booking->guest?->email)) { if (blank($booking->guest?->email)) {
@@ -87,7 +90,7 @@ public function handle(Booking $booking): array
{ {
$booking->loadMissing(['property', 'guest']); $booking->loadMissing(['property', 'guest']);
if ($booking->process()->preReservation()) { if ($booking->process()->inquiryAnswer() === InquiryAnswer::Offer) {
$this->clearance->refresh($booking->property); $this->clearance->refresh($booking->property);
} }
@@ -97,7 +100,7 @@ public function handle(Booking $booking): array
} }
try { try {
if (! $booking->process()->preReservation()) { if ($booking->process()->inquiryAnswer() === InquiryAnswer::Information) {
$this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]); $this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]);
} else { } else {
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]); $this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace App\Actions;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Channel;
use App\Process\ChannelCapabilities;
use App\Process\ChannelProcessConfiguration;
use App\Process\ProcessCatalogue;
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 and V2.1/02):
* the confirmed capabilities of the portal, the chosen model and variant, the step switches and the step settings – in
* channels.settings and 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, a model the capabilities do not fit, tester-only variants). Stored settings that the chosen model overrides are
* removed only after the landlord confirmed that, and the change is kept in the channel's history. Changes apply to new
* cases only (decision E3): running cases keep their frozen plan.
*/
class ConfigureChannelProcess
{
public const HISTORY_LIMIT = 20;
public function __construct(private ChannelProcessConfiguration $configuration, private ChannelCapabilities $capabilities, private ProcessCatalogue $catalogue) {}
/**
* @param array{model: string, variant?: string, steps?: array<string, array{on?: bool}>, settings?: array<string, mixed>, templates?: array<string, string>, capabilities?: array<string, bool|string|null>} $draft
* @param bool $acknowledgeConflicts the landlord confirmed that stored settings the model overrides are removed
*
* @throws ValidationException
*/
public function handle(Channel $channel, IntakeKind $intake, array $draft, ?string $by = null, bool $acknowledgeConflicts = false): Channel
{
$problems = $this->configuration->problems($channel, $intake, $draft);
if ($problems !== []) {
throw ValidationException::withMessages(['process' => $problems]);
}
$conflicts = $this->configuration->conflicts($channel, $intake, (string) $draft['model'], (array) ($draft['templates'] ?? []));
if ($conflicts !== [] && ! $acknowledgeConflicts) {
throw ValidationException::withMessages(['process' => [
'Bisherige Einstellungen widersprechen dem gewählten Modell und würden still überstimmt. Bitte ausdrücklich bestätigen, dass sie entfernt werden:',
...array_column($conflicts, 'text'),
]]);
}
return DB::transaction(function () use ($channel, $intake, $draft, $by, $conflicts): Channel {
$channel = Channel::query()->lockForUpdate()->findOrFail($channel->id);
$by ??= auth()->user()?->name;
$overrides = (array) ($channel->process_overrides ?? []);
$current = (array) ($overrides[$intake->value] ?? []);
$removed = array_map(fn (array $conflict): string => $conflict['setting']->value, $conflicts);
$settings = [];
foreach (ProcessSetting::cases() as $setting) {
if (in_array($setting->value, $removed, true)) {
continue;
}
$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];
}
}
// A model with slots always stores its explicit template choice (keys; the version is frozen with each new case).
$model = $this->catalogue->model((string) $draft['model']);
$templates = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->configuration->templatesOf($model, $draft));
if ($model->slots() === []) {
$templates = [];
}
$overrides[$intake->value] = [
...$settings,
'model' => $draft['model'],
'variant' => $draft['variant'] ?? 'standard',
'steps' => $steps,
'templates' => $templates,
'configured_at' => now()->toIso8601String(),
'configured_by' => $by,
];
$channelSettings = (array) ($channel->settings ?? []);
$changes = [];
if (! $channel->isWebsite() && filled($draft['capabilities'] ?? null)) {
$confirmed = $this->capabilities->confirm($channel, (array) $draft['capabilities'], $by);
$channelSettings['capabilities'] = $confirmed['capabilities'];
$changes = $confirmed['changes'];
}
$channelSettings['process_history'] = array_slice([...(array) ($channelSettings['process_history'] ?? []), [
'at' => now()->toIso8601String(), 'by' => $by, 'intake' => $intake->value, 'model' => $draft['model'], 'variant' => $draft['variant'] ?? 'standard', 'templates' => $templates,
'capabilities' => $changes, 'removed_settings' => array_map(fn (array $conflict): string => $conflict['text'], $conflicts),
]], -self::HISTORY_LIMIT);
$channel->update(['process_overrides' => $overrides, 'settings' => $channelSettings]);
return $channel;
});
}
}
+14 -20
View File
@@ -6,6 +6,7 @@
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\FactSource; use App\Enums\FactSource;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
use App\Mail\NewReservation; use App\Mail\NewReservation;
use App\Mail\ReservationReceived; use App\Mail\ReservationReceived;
@@ -16,6 +17,7 @@
use App\Pricing\PriceCalculator; use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException; use App\Pricing\QuoteException;
use App\Pricing\StayRequest; use App\Pricing\StayRequest;
use App\Process\ProcessRunner;
use App\Process\ProcessSettings; use App\Process\ProcessSettings;
use App\Process\RequestHold; use App\Process\RequestHold;
use App\Support\Settings; use App\Support\Settings;
@@ -174,35 +176,27 @@ private function sendMails(Booking $booking): void
{ {
$blockers = []; $blockers = [];
$offerSent = false; $offerSent = false;
$asked = false;
// The process core answers the request as far as its data allows (Architektur V2, trigger request.created):
// automatic mode sends the offer or information; if details are missing, the data request asks for them
// (and then replaces the receipt) – independently of the offer, which waits for the details.
try { try {
$auto = app(AutoOffer::class); $result = app(ProcessRunner::class)->advance($booking, 'request.created');
if ($auto->applies($booking)) { $offerSent = $result->ran('offer.binding') || $result->ran('offer.information');
$blockers = $auto->handle($booking); $booking->refresh();
$offerSent = $blockers === []; if (! $offerSent && $booking->processingMode() === ProcessingMode::Automatic) {
if (! $offerSent) { $blockers = [...$result->reasons('offer.binding'), ...$result->reasons('offer.information')];
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]); $booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
}
$booking->refresh();
} }
$asked = $result->ran('guest.data_request') && $booking->openDataRequest()?->last_sent_at !== null;
$booking->refresh();
} catch (Throwable $exception) { } catch (Throwable $exception) {
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]); Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.']; $blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
$offerSent = false; $offerSent = false;
} }
// v0.11: details for the offer are missing – the data request asks for them (and then replaces the receipt).
$asked = false;
if (! $offerSent) {
try {
$request = app(RequestCaseData::class)->forNextStep($booking);
$asked = $request?->last_sent_at !== null;
$booking->refresh();
} catch (Throwable $exception) {
Log::warning('Rückfrage fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
try { try {
if (! $offerSent && ! $asked && filled($booking->guest?->email)) { if (! $offerSent && ! $asked && filled($booking->guest?->email)) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking)); Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
+19
View File
@@ -12,9 +12,11 @@
use App\Enums\TenantServiceKey; use App\Enums\TenantServiceKey;
use App\Mail\PortalMailNotification; use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod; use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel; use App\Models\Channel;
use App\Models\IntakeObservation; use App\Models\IntakeObservation;
use App\Models\PortalEmail; use App\Models\PortalEmail;
use App\Process\ProcessRunner;
use App\Support\Settings; use App\Support\Settings;
use App\Tenancy\TenantFeatures; use App\Tenancy\TenantFeatures;
use Carbon\CarbonInterface; use Carbon\CarbonInterface;
@@ -79,6 +81,7 @@ public function handle(PortalMail $mail): ?PortalEmail
// One intake for all channels (package 4): bookings, requests and cancellations reach their case. // One intake for all channels (package 4): bookings, requests and cancellations reach their case.
rescue(fn () => $this->intake($channel, $parsed, $record)); rescue(fn () => $this->intake($channel, $parsed, $record));
rescue(fn () => $this->resume($channel, $parsed, $record));
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) { if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record))); rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
@@ -91,6 +94,22 @@ public function handle(PortalMail $mail): ?PortalEmail
return $record; return $record;
} }
/**
* A booking mail of the portal can be the confirmation a case waits for (V2.1, docs/Prozessarchitektur/V2.1/02 §5): the
* case is evaluated again. Only cases whose channel makes them wait are touched – everything else stays as it was.
*/
private function resume(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{
if ($parsed->type !== PortalEmailType::Booking) {
return;
}
$case = $record->blocked_period_id !== null ? Booking::query()->find(BlockedPeriod::withTrashed()->whereKey($record->blocked_period_id)->value('linked_booking_id')) : null;
$case ??= $parsed->reference !== null ? app(PortalIntake::class)->caseByReference($channel, $parsed->reference) : null;
if ($case !== null && $case->isBinding() && $case->process()->awaitsPortalConfirmation()) {
app(ProcessRunner::class)->advance($case, 'portal.mail');
}
}
private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{ {
$intake = app(PortalIntake::class); $intake = app(PortalIntake::class);
+2 -1
View File
@@ -9,6 +9,7 @@
use App\Enums\DataRequestMode; use App\Enums\DataRequestMode;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\FactSource; use App\Enums\FactSource;
use App\Enums\InquiryAnswer;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Mail\DataRequested; use App\Mail\DataRequested;
use App\Models\Booking; use App\Models\Booking;
@@ -70,7 +71,7 @@ public static function needs(Booking $booking): ?array
} }
$purpose = match (true) { $purpose = match (true) {
$booking->process()->preReservation() => self::FOR_OFFER, $booking->process()->inquiryAnswer() === InquiryAnswer::Offer => self::FOR_OFFER,
$booking->wish_at !== null => self::FOR_WISH, $booking->wish_at !== null => self::FOR_WISH,
default => null, default => null,
}; };
+6 -1
View File
@@ -6,6 +6,8 @@
use App\Enums\Responsibility; use App\Enums\Responsibility;
use App\Mail\ReviewRequest; use App\Mail\ReviewRequest;
use App\Models\Booking; use App\Models\Booking;
use App\Process\OutwardSuspension;
use App\Process\ProcessPlan;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
/** /**
@@ -27,7 +29,10 @@ public function handle(): int
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', '')) ->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->with('guest') ->with('guest')
->get() ->get()
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord); ->filter(fn (Booking $booking): bool => $booking->process()->reviewRequestSender() === Responsibility::Landlord
// The step can be switched off per channel (Kanal › Ablauf); an open portal report holds it back (O4).
&& ProcessPlan::of($booking)->enabled('review.request')
&& OutwardSuspension::reason($booking) === null);
foreach ($bookings as $booking) { foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking)); Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
+35
View File
@@ -49,6 +49,41 @@ public function automatically(Booking $booking): array
return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).']; return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
} }
/**
* Creates the contract document and files it internally – without sending anything to the guest (delivery „internal“,
* docs/Prozessarchitektur/V2.1/02 §4). Same gate as the automatic dispatch: the composition must be clean.
*
* @return list<string> reasons why it was not created (empty: filed or already there)
*/
public function storeInternally(Booking $booking): array
{
if ($booking->contract_path !== null) {
return [];
}
$composition = $this->compose($booking);
if (! $composition->canSendAutomatically()) {
return [...$composition->blockers(), ...array_map(fn (string $point): string => 'Bitte prüfen: '.$point, $composition->toConfirm())];
}
$lock = Cache::lock('booking-documents-'.$booking->id, 120);
if (! $lock->get()) {
return ['Die Unterlagen werden gerade bearbeitet.'];
}
try {
$booking->refresh();
if (! $composition->termsFrozen && $composition->terms !== null) {
$booking->update(['offer_terms' => $composition->terms]);
}
return CaseLog::context(fn (): bool => $this->confirm->deliver($booking, notifyGuest: false, kind: $composition->kind), actor: CaseLog::SYSTEM.' (automatisch)')
? [] : ['Das Vertragsdokument konnte nicht erstellt werden (siehe Postfach).'];
} finally {
$lock->release();
}
}
/** /**
* Sending by hand after the landlord saw the composition. * Sending by hand after the landlord saw the composition.
* *
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace App\Actions;
use App\Enums\BookingNoticeMode;
use App\Exceptions\ReservationException;
use App\Mail\BookingNotice;
use App\Models\Booking;
use App\Process\CaseLog;
use App\Process\ChannelCapabilities;
use App\Process\PortalConfirmation;
use Illuminate\Support\Facades\Mail;
/**
* Sends the guest of a binding booking a short booking information (V2.1, docs/Prozessarchitektur/V2.1/02 §4) – separate
* from the contract documentation, which has its own step. Once only (the history entry `booking_notice` is the record).
* Where the landlord chose „unless the portal confirmed“, it is not sent when the portal informs the guest itself (confirmed
* capability of the channel) and its booking confirmation for this case is on record; the reason is kept in the history.
*/
class SendBookingNotice
{
public const EVENT = 'booking_notice';
public static function sent(Booking $booking): bool
{
return $booking->events()->where('type', self::EVENT)->where('summary', 'not like', 'Keine eigene%')->exists();
}
/**
* Why no own notice is needed, or null when it is.
*/
public static function suppression(Booking $booking): ?string
{
if ($booking->process()->bookingNotice() !== BookingNoticeMode::AutomaticUnlessPortalConfirmed) {
return null;
}
$channel = $booking->processChannel();
if ($channel === null || app(ChannelCapabilities::class)->value($channel, ChannelCapabilities::MESSAGES_GUEST) !== true) {
return null;
}
$evidence = PortalConfirmation::evidence($booking);
return $evidence === null ? null : 'Das Portal informiert den Gast selbst und hat die Buchung bestätigt ('.$evidence['label'].').';
}
/**
* @throws ReservationException
*/
public function handle(Booking $booking, bool $automatic = false): bool
{
$booking->loadMissing(['guest', 'property']);
if (! $booking->isBinding()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'mit einer Buchungsinformation bedacht');
}
if (self::sent($booking)) {
return true;
}
if (blank($booking->guest?->email)) {
throw new ReservationException('Vor dem Versand bitte die E-Mail-Adresse des Gastes ergänzen.');
}
if ($automatic && ($reason = self::suppression($booking)) !== null) {
if (! $booking->events()->where('type', self::EVENT)->exists()) {
CaseLog::record($booking, self::EVENT, 'Keine eigene Buchungsinformation nötig', reason: $reason, data: ['level' => 'stated_by_portal']);
}
return false;
}
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingNotice($booking));
CaseLog::record($booking, self::EVENT, 'Buchungsinformation an den Gast gesendet', actor: $automatic ? CaseLog::SYSTEM.' (automatisch)' : null);
return true;
}
}
+5 -2
View File
@@ -9,6 +9,7 @@
use App\Mail\ArrivalInformation; use App\Mail\ArrivalInformation;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask; use App\Models\BookingTask;
use App\Process\OutwardSuspension;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
@@ -62,8 +63,10 @@ public function handle(): array
->whereNull('arrival_info_sent_at') ->whereNull('arrival_info_sent_at')
->whereDate('arrival', '>=', $today) ->whereDate('arrival', '>=', $today)
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE))) ->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord ->filter(fn (Booking $booking): bool => $booking->process()->arrivalInfoSender() === Responsibility::Landlord
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore()))); && $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore()))
// Decision O4: an open portal report of a cancellation or change holds the message back until clarified.
&& OutwardSuspension::reason($booking) === null);
foreach ($arrivals as $booking) { foreach ($arrivals as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking)); Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
$booking->update(['arrival_info_sent_at' => now()]); $booking->update(['arrival_info_sent_at' => now()]);
+3 -1
View File
@@ -14,6 +14,7 @@
use App\Filament\Resources\Bookings\BookingResource; use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\OfferMade; use App\Mail\OfferMade;
use App\Models\Booking; use App\Models\Booking;
use App\Pricing\CasePricing;
use App\Pricing\PriceCalculator; use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote; use App\Pricing\PriceQuote;
use App\Pricing\QuoteException; use App\Pricing\QuoteException;
@@ -189,7 +190,8 @@ public function offerUrl(Booking $booking): string
*/ */
public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
{ {
$quote = $this->calculator->calculate($booking->property, $stay); // Extension point BeforePriceFixing (Architektur V2): PriceCalculator plus the lines of contributing modules.
$quote = app(CasePricing::class)->quote($booking, $stay);
if ($adjustment === 0) { if ($adjustment === 0) {
return $quote; return $quote;
} }
+2 -1
View File
@@ -21,6 +21,7 @@
use App\Process\CaseAutomation; use App\Process\CaseAutomation;
use App\Process\CaseLog; use App\Process\CaseLog;
use App\Process\CaseRequirements; use App\Process\CaseRequirements;
use App\Process\ProcessRunner;
use App\Support\Inbox; use App\Support\Inbox;
use App\Support\Money; use App\Support\Money;
use App\Support\Settings; use App\Support\Settings;
@@ -148,7 +149,7 @@ public function handle(Booking $booking, int $version, ?string $ip = null): stri
// v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing. // v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing.
if ($outcome === self::PENDING) { if ($outcome === self::PENDING) {
rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); app(ProcessRunner::class)->advance($booking->fresh(), 'wish');
} }
return $outcome; return $outcome;
+5 -5
View File
@@ -13,7 +13,7 @@
use App\Models\Guest; use App\Models\Guest;
use App\Models\Property; use App\Models\Property;
use App\Pricing\PortalPrice; use App\Pricing\PortalPrice;
use App\Process\CaseAutomation; use App\Process\ProcessRunner;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -96,9 +96,9 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
return $booking->refresh(); return $booking->refresh();
}); });
app(CaseAutomation::class)->advance($booking); // The process core sends the documents when everything is there (automatic mode); v0.11 (E-036): the booking
// v0.11 (E-036): the booking stays binding; only missing administrative details of a reachable guest are asked for. // stays binding, only missing administrative details of a reachable guest are asked for.
rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); app(ProcessRunner::class)->advance($booking, 'booking.taken_over');
return $booking->refresh(); return $booking->refresh();
} }
@@ -111,7 +111,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
*/ */
private function checkEvidence(BlockedPeriod $evidence): ?Booking private function checkEvidence(BlockedPeriod $evidence): ?Booking
{ {
if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) { if (! in_array($evidence->source, ['channel', 'email', 'api'], true) || $evidence->channel_id === null) {
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.'); throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
} }
if ($evidence->occupationKind() === OccupationKind::Block) { if ($evidence->occupationKind() === OccupationKind::Block) {
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\Events\ChannelEvent;
use App\Models\Channel;
use Carbon\CarbonImmutable;
/**
* Capability of a connector whose portal offers an interface for bookings, cancellations, changes and amounts
* (Architektur V2, 02 §8.4). The events go to ChannelEventHandler; the connector itself decides nothing. Network access
* only through the Http facade (SideEffectPathsTest), so the process tester can replace it.
*/
interface DeliversEvents
{
/**
* @return list<ChannelEvent>
*/
public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\Events\ChannelEvent;
use App\Models\Channel;
use Illuminate\Http\Request;
/**
* Capability of a connector whose portal pushes events (webhook). The connector verifies the signature (authenticity
* of the origin) and translates the payload; the business decision stays with ChannelEventHandler.
*/
interface ReceivesWebhooks
{
/**
* @return list<ChannelEvent> empty when the signature is not valid
*/
public function receive(Channel $channel, Request $request): array;
}
@@ -0,0 +1,14 @@
<?php
namespace App\Channels\Events;
/**
* The portal reports a cancellation of a known booking: a task on the case, never a cancellation, refund or fee (E-019).
*/
final readonly class BookingCancelledByChannel extends ChannelEvent
{
public function __construct(Provenance $provenance, public ?string $note = null)
{
parent::__construct($provenance);
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal reports other dates or guests of a known booking: a task with the comparison, never a change of the booking.
*/
final readonly class BookingChangedByChannel extends ChannelEvent
{
public function __construct(Provenance $provenance, public ?CarbonImmutable $arrival = null, public ?CarbonImmutable $departure = null, public ?int $guests = null)
{
parent::__construct($provenance);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Channels\Events;
/**
* A normalised business event of a portal, independent of its transport (Architektur V2, K4/K10). Future API or
* webhook adapters deliver these; ChannelEventHandler maps them onto the existing intake, so duplicates, origin and the
* external binding are judged in one place for every transport.
*/
abstract readonly class ChannelEvent
{
public function __construct(public Provenance $provenance) {}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Channels\Events;
use App\Actions\RecordPortalAmounts;
use App\Channels\Intake\IntakeDecision;
use App\Channels\Intake\PortalIntake;
use App\Enums\IntakeOutcome;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\IntakeObservation;
use App\Process\CaseLog;
use App\Support\Money;
use App\Tenancy\TenantContext;
use InvalidArgumentException;
/**
* The one entry of channel events (docs/Prozessarchitektur/Architektur/02 §8.3–8.4): maps each normalised event onto
* the existing intake, so iCal, mail and future APIs are judged by the same rules – duplicates and certainty in
* PortalIntake, amounts in RecordPortalAmounts, reports about known cases as tasks. Contains no decision rules of its
* own and never changes a binding booking (stage M4 needs the landlord's action).
*/
final class ChannelEventHandler
{
public function __construct(private PortalIntake $intake, private RecordPortalAmounts $amounts) {}
public function handle(ChannelEvent $event): ?IntakeDecision
{
$channel = $event->provenance->channel;
if (! $channel->isPortal() || $channel->tenant_id === null) {
throw new InvalidArgumentException('Kanalereignisse kommen nur von Portalen.');
}
return app(TenantContext::class)->run($channel->tenant, fn (): ?IntakeDecision => match (true) {
$event instanceof IncomingBooking => $this->booking($event),
$event instanceof BookingCancelledByChannel => $this->report($event, IntakeOutcome::CancellationSignal, $channel->name.' meldet über die Schnittstelle eine Stornierung'.($event->note ? ' ('.$event->note.')' : '').'. Bitte prüfen Sie die Buchung und die nächsten Schritte.'),
$event instanceof BookingChangedByChannel => $this->report($event, IntakeOutcome::ChangeSignal, $channel->name.' meldet über die Schnittstelle eine Änderung'.($event->arrival && $event->departure ? ': '.$event->arrival->format('d.m.').'–'.$event->departure->format('d.m.Y') : '').($event->guests ? ', '.$event->guests.' Personen' : '').'. Die Buchung bleibt unverändert, bis Sie entscheiden.'),
$event instanceof PaymentReported => $this->payment($event),
$event instanceof PayoutReported => $this->payout($event),
default => throw new InvalidArgumentException('Unbekanntes Kanalereignis '.$event::class.'.'),
});
}
/**
* A booking binding at the portal: blocked like a booking e-mail – source api, reference in the identifier – and judged
* by PortalIntake – the same case, never a second one; a case only when certain.
*/
private function booking(IncomingBooking $event): IntakeDecision
{
$provenance = $event->provenance;
$reference = $provenance->externalReference;
// The reference is the identity of the block (as for booking mails); without one it is never taken as a reference.
$uid = $reference !== null ? 'api:'.$reference : 'api-event:'.$provenance->evidenceRef;
$block = $provenance->channel->blockedPeriods()->withTrashed()->where('source', 'api')->where('external_uid', $uid)->first()
?? new BlockedPeriod(['property_id' => $provenance->channel->property_id, 'source' => 'api', 'reason' => $provenance->channel->name, 'external_uid' => $uid]);
$block->fill(['starts_on' => $event->arrival->toDateString(), 'ends_on' => $event->departure->toDateString()]);
if ($block->trashed()) {
$block->restore();
}
$provenance->channel->blockedPeriods()->save($block);
return $this->intake->process($block->fresh(), IntakeObservation::SOURCE_API);
}
private function report(BookingCancelledByChannel|BookingChangedByChannel $event, IntakeOutcome $outcome, string $message): ?IntakeDecision
{
$case = $this->case($event);
if ($case === null) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
}
$this->intake->reportToCase($event->provenance->channel, $case, $outcome, $message, 'api:'.$event->provenance->evidenceRef, IntakeObservation::SOURCE_API);
return new IntakeDecision($outcome, [$message], $case, reference: $event->provenance->externalReference);
}
private function payment(PaymentReported $event): ?IntakeDecision
{
$case = $this->case($event);
if ($case === null) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Zahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
}
$this->amounts->handle($case, null, [], [['amount' => $event->amount, 'paid_on' => $event->paidOn->toDateString()]], $event->provenance->channel->name);
return new IntakeDecision(IntakeOutcome::Link, ['Zahlung des Gastes laut Portal erfasst (kein Eingang auf unserem Konto).'], $case);
}
private function payout(PayoutReported $event): ?IntakeDecision
{
$case = $this->case($event);
if ($case === null) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Auszahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
}
if ($event->executed) {
// Evidence level "laut Portal erledigt" – the receipt on our account is recorded by the landlord (O5).
CaseLog::record($case, 'evidence', 'Auszahlung laut '.$event->provenance->channel->name.' ausgeführt: '.Money::format($event->amount).' am '.$event->paidOn->format('d.m.Y').' – Eingang auf unserem Konto noch nicht erfasst.', data: ['module' => 'portal.payout', 'level' => 'stated_by_portal', 'source' => $event->provenance->transport, 'ref' => $event->provenance->evidenceRef], actor: $event->provenance->channel->name);
} else {
$this->amounts->handle($case, null, [['kind' => 'payout_announced', 'amount' => $event->amount, 'due_on' => $event->paidOn->toDateString()]], [], $event->provenance->channel->name);
}
return new IntakeDecision(IntakeOutcome::Link, ['Auszahlung laut Portal vermerkt.'], $case);
}
/**
* The binding case of the event: by the portal's booking reference only (no merging by dates for reports).
*/
private function case(ChannelEvent $event): ?Booking
{
$reference = $event->provenance->externalReference;
$case = $reference === null ? null : $this->intake->caseByReference($event->provenance->channel, $reference);
return $case !== null && $case->isBinding() ? $case : null;
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* A booking binding at the portal (M1/M2): its dates and reference; becomes a case only through PortalIntake's certainty rules.
*/
final readonly class IncomingBooking extends ChannelEvent
{
public function __construct(Provenance $provenance, public CarbonImmutable $arrival, public CarbonImmutable $departure, public ?int $guests = null, public ?int $total = null)
{
parent::__construct($provenance);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal reports a payment of the guest to the portal: recorded "laut Portal" (GuestViaPortal), never as money on our account.
*/
final readonly class PaymentReported extends ChannelEvent
{
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn)
{
parent::__construct($provenance);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal announces or reports a payout to us: "laut Portal" only – a received payout is recorded by the landlord (decision O5).
*/
final readonly class PayoutReported extends ChannelEvent
{
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn, public bool $executed = false)
{
parent::__construct($provenance);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Channels\Events;
use App\Models\Channel;
use Carbon\CarbonImmutable;
/**
* Where a channel event came from (docs/Prozessarchitektur/Architektur/02 §8.2): channel, transport and whether its
* origin is technically authenticated (a signed webhook, an API call with credentials). It says nothing about whether a
* business action really happened – that is evidence, which only the landlord or a checked receipt provides (M3).
*/
final readonly class Provenance
{
public const AUTHENTICATED = 'authenticated';
public const UNAUTHENTICATED = 'unauthenticated';
public function __construct(
public Channel $channel,
public string $transport,
public string $authenticity,
public ?string $externalReference,
public string $evidenceRef,
public CarbonImmutable $receivedAt,
) {}
public function isAuthenticated(): bool
{
return $this->authenticity === self::AUTHENTICATED;
}
}
+19 -2
View File
@@ -65,7 +65,7 @@ public function evaluate(BlockedPeriod $block): IntakeDecision
$channel = $block->channel; $channel = $block->channel;
$reference = self::reference($block); $reference = self::reference($block);
if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) { if ($channel === null || ! in_array($block->source, ['channel', 'email', 'api'], true)) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference); return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
} }
if ($block->trashed()) { if ($block->trashed()) {
@@ -246,6 +246,15 @@ public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, Por
return $case; return $case;
} }
/**
* A report of the portal about a known case (channel events, Architektur V2: cancellation or change via an API):
* the case gets a task and a history entry, nothing about the booking changes (E-019, stage M2 of 02 §8.2).
*/
public function reportToCase(Channel $channel, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source): void
{
$this->report($channel, $channel->case_intake ?? CaseIntakeMode::Off, $case, $outcome, $message, $key, $source);
}
/** /**
* A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates * A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates
* cases; otherwise only recorded. * cases; otherwise only recorded.
@@ -292,6 +301,11 @@ public static function reference(BlockedPeriod $block): ?string
return trim((string) $fromRules); return trim((string) $fromRules);
} }
// A block of a portal's API (channel events, Architektur V2) carries the reference like a booking mail.
if ($block->source === 'api' && str_starts_with((string) $block->external_uid, 'api:')) {
return substr((string) $block->external_uid, 4);
}
if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) { if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) {
$reference = substr((string) $block->external_uid, 6); $reference = substr((string) $block->external_uid, 6);
@@ -315,7 +329,7 @@ public function caseByReference(Channel $channel, string $reference): ?Booking
} }
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id') $linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id'); ->whereIn('external_uid', [$reference, 'email:'.$reference, 'api:'.$reference])->value('linked_booking_id');
return $linked !== null ? Booking::query()->find($linked) : null; return $linked !== null ? Booking::query()->find($linked) : null;
} }
@@ -346,6 +360,9 @@ private function certainty(BlockedPeriod $block, ?string $reference): ?string
if ($block->source === 'email') { if ($block->source === 'email') {
return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null; return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null;
} }
if ($block->source === 'api') {
return $reference === null ? 'Portalmeldung ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : null;
}
// Classified by the landlord as a reservation booked at this portal. // Classified by the landlord as a reservation booked at this portal.
if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) { if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) {
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Communication;
use App\Enums\Medium;
use App\Enums\MessageEffect;
use App\Enums\MessageIntent;
use App\Support\Settings;
/**
* The medium × intent policy (V2.1): `config/communication.php` is the ceiling, the landlord's `communication_rules`
* (tenants) may only narrow it: switch a medium off, withdraw effects. Widening is ignored.
*/
class CommunicationRules
{
public function mediumActive(Medium $medium): bool
{
$ceiling = (bool) config("communication.media.{$medium->value}.active", false);
return $ceiling && ($this->narrowing()['media'][$medium->value]['active'] ?? true) !== false;
}
public function consentRequired(Medium $medium): bool
{
return (bool) config("communication.media.{$medium->value}.consent_required", false);
}
/**
* @return list<MessageEffect> the effects the rules allow for the intent on the medium (never empty: review at least)
*/
public function effects(Medium $medium, MessageIntent $intent): array
{
/** @var list<MessageEffect> $ceiling */
$ceiling = config('communication.effects.'.$intent->value, [MessageEffect::Review]);
$withdrawn = (array) ($this->narrowing()['effects'][$medium->value][$intent->value] ?? []);
$allowed = array_values(array_filter($ceiling, fn (MessageEffect $effect): bool => ! in_array($effect->value, $withdrawn, true)));
return $allowed === [] ? [MessageEffect::Review] : $allowed;
}
/**
* @return array<string, mixed>
*/
private function narrowing(): array
{
return (array) (Settings::tenant()?->communication_rules ?? []);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Communication;
use App\Enums\Medium;
use Carbon\CarbonImmutable;
/**
* A message as the medium adapters hand it over (V2.1): raw data only. {@see $verifiedBookingId} is set by the adapter
* itself from a reference it issued and can verify (signed token, reply to one of our mails) – a claim in the text is
* never enough. {@see $consentGiven} is likewise the adapter's statement.
*/
final readonly class IncomingMessage
{
public function __construct(
public Medium $medium,
public string $sender,
public string $text,
public CarbonImmutable $receivedAt,
public string $externalId,
public ?int $verifiedBookingId = null,
public bool $consentGiven = false,
public ?string $senderName = null,
) {}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Communication;
use App\Enums\MessageIntent;
/**
* Rule-based intent of a message (V2.1). Deterministic and medium-independent; an AI classifier can later implement the
* same interface of work (E-035). Whatever the rules do not clearly recognise is {@see MessageIntent::Unclear}.
*/
class IntentClassifier
{
public function classify(string $text, bool $assignedToCase): MessageIntent
{
$text = mb_strtolower($text);
$has = fn (array $words): bool => (bool) preg_match('/('.implode('|', $words).')/u', $text);
if ($assignedToCase && $has(['umbuchen', 'verschieb', 'stornieren', 'stornierung', 'später anreisen', 'früher anreisen', 'ändern'])) {
return MessageIntent::ChangeRequest;
}
if ($assignedToCase && $has(['ankunft', 'uhr', 'personen', 'kennzeichen', 'adresse', 'telefon', 'handynummer'])) {
return MessageIntent::ProvideData;
}
if ($assignedToCase) {
return MessageIntent::CaseReply;
}
if ($has(['frei', 'verfügbar', 'buchen', 'reservieren', 'anreise', 'zeitraum', 'vom \d'])) {
return MessageIntent::StayInquiry;
}
if ($has(['\?', 'hund', 'haustier', 'parkplatz', 'wlan', 'preis', 'kosten', 'wie weit', 'strand', 'ausstattung'])) {
return MessageIntent::GeneralQuestion;
}
return MessageIntent::Unclear;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Communication;
use App\Enums\Medium;
use App\Enums\MessageEffect;
use App\Enums\MessageIntent;
use App\Models\Booking;
/**
* What the process core decided about a message (V2.1): intent, case (only if verified), the effects that apply and why.
*/
final readonly class MessageDecision
{
/**
* @param list<MessageEffect> $effects applied effects, in order
* @param list<string> $reasons plain-language explanation
*/
public function __construct(
public Medium $medium,
public MessageIntent $intent,
public ?Booking $booking,
public array $effects,
public array $reasons,
) {}
public function has(MessageEffect $effect): bool
{
return in_array($effect, $this->effects, true);
}
/**
* @return array{medium: string, intent: string, booking_id: ?int, effects: list<string>, reasons: list<string>}
*/
public function toArray(): array
{
return ['medium' => $this->medium->value, 'intent' => $this->intent->value, 'booking_id' => $this->booking?->id,
'effects' => array_map(fn (MessageEffect $effect): string => $effect->value, $this->effects), 'reasons' => $this->reasons];
}
}
+150
View File
@@ -0,0 +1,150 @@
<?php
namespace App\Communication;
use App\Actions\ReceiveInboundMessage;
use App\Enums\BookingTaskKind;
use App\Enums\MessageEffect;
use App\Enums\MessageIntent;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Process\CaseLog;
use App\Support\Settings;
use Illuminate\Database\UniqueConstraintViolationException;
/**
* Entry of messages from every medium except the e-mail inbox, which keeps its own path (V2.1, docs/…/02 §6):
* store once → assign deterministically (only a reference verified by the adapter, and not contradicted by the text) →
* classify → apply the effects the rules allow. A message never creates a case, reservation, offer or booking; what is
* unclear or contradictory goes to review. No answer is sent here.
*/
class MessageIntake
{
public function __construct(private CommunicationRules $rules, private IntentClassifier $classifier) {}
public function handle(IncomingMessage $incoming): MessageDecision
{
$key = $incoming->medium->value.':'.$incoming->externalId;
$existing = InboundMessage::query()->where('message_id', $key)->first();
if ($existing !== null) {
return $this->fromStored($existing, $incoming);
}
$reasons = [];
$booking = $this->assignedCase($incoming, $reasons);
$intent = $this->classifier->classify($incoming->text, $booking !== null);
$effects = $this->effectsFor($incoming, $intent, $booking, $reasons);
$decision = new MessageDecision($incoming->medium, $intent, $booking, $effects, $reasons);
try {
$message = InboundMessage::query()->create([
'message_id' => $key,
'medium' => $incoming->medium->value,
'from_address' => mb_substr($incoming->sender, 0, 255),
'from_name' => $incoming->senderName,
'subject' => mb_substr(strtok($incoming->text, "\n") ?: '', 0, 120),
'body' => $incoming->text,
'received_at' => $incoming->receivedAt,
'test_mode' => ! Settings::isLive(),
'status' => $booking !== null && ! $decision->has(MessageEffect::Review) ? InboundMessage::ASSIGNED : InboundMessage::NEEDS_REVIEW,
'booking_id' => $booking?->id,
'match_reason' => $booking !== null ? 'verified_reference' : null,
'intent' => $intent->value,
'decision' => $decision->toArray(),
]);
} catch (UniqueConstraintViolationException) {
return $this->fromStored(InboundMessage::query()->where('message_id', $key)->firstOrFail(), $incoming);
}
$this->apply($message, $decision);
return $decision;
}
/**
* @param list<string> $reasons
*/
private function assignedCase(IncomingMessage $incoming, array &$reasons): ?Booking
{
if ($incoming->verifiedBookingId === null) {
$reasons[] = 'Kein überprüfter Bezug zu einem Vorgang – Absender, Rufnummer, Name oder Zeitraum allein ordnen nicht zu.';
return null;
}
$booking = Booking::query()->find($incoming->verifiedBookingId);
if ($booking === null) {
$reasons[] = 'Der überprüfte Bezug verweist auf keinen Vorgang dieses Vermieters.';
return null;
}
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $incoming->text, $numbers) && array_diff($numbers[1], [$booking->reference]) !== []) {
$reasons[] = 'Die Nachricht nennt eine andere Vorgangsnummer als der überprüfte Bezug – widersprüchlich.';
return null;
}
$reasons[] = 'Dem Vorgang '.$booking->reference.' zugeordnet (überprüfter Bezug).';
return $booking;
}
/**
* @param list<string> $reasons
* @return list<MessageEffect>
*/
private function effectsFor(IncomingMessage $incoming, MessageIntent $intent, ?Booking $booking, array &$reasons): array
{
if (! $this->rules->mediumActive($incoming->medium)) {
$reasons[] = $incoming->medium->getLabel().' ist für diesen Vermieter nicht eingeschaltet – die Nachricht liegt zur Klärung vor.';
return [MessageEffect::Review];
}
if ($this->rules->consentRequired($incoming->medium) && ! $incoming->consentGiven) {
$reasons[] = 'Für '.$incoming->medium->getLabel().' liegt keine Einwilligung vor – nur Klärung durch den Vermieter.';
return [MessageEffect::Review];
}
$effects = array_values(array_filter(
$this->rules->effects($incoming->medium, $intent),
fn (MessageEffect $effect): bool => ! $effect->needsCase() || $booking !== null,
));
// The review fallback only stands alone: where a real effect applies it is not added.
$real = array_values(array_filter($effects, fn (MessageEffect $effect): bool => $effect !== MessageEffect::Review));
if ($real === [] || $intent === MessageIntent::Unclear) {
$reasons[] = 'Nicht eindeutig oder nicht zulässig – zur Klärung vorgelegt, nichts wird übernommen.';
return [MessageEffect::Review];
}
return $real;
}
private function apply(InboundMessage $message, MessageDecision $decision): void
{
$booking = $decision->booking;
if ($booking === null || $decision->has(MessageEffect::Review)) {
return;
}
CaseLog::record($booking, 'message_in', $decision->medium->getLabel().'-Nachricht eingegangen ('.$decision->intent->getLabel().')', actor: CaseLog::GUEST, at: $message->received_at);
if ($decision->has(MessageEffect::ReportToCase) || $decision->has(MessageEffect::ContributeFacts)) {
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => $decision->medium->getLabel().'-Nachricht („'.mb_substr((string) $message->subject, 0, 100).'“) – im Posteingang ansehen; es wird nichts automatisch übernommen.']);
}
if ($decision->has(MessageEffect::ContributeFacts)) {
app(ReceiveInboundMessage::class)->evaluate($message);
}
}
private function fromStored(InboundMessage $stored, IncomingMessage $incoming): MessageDecision
{
$data = (array) $stored->decision;
return new MessageDecision(
$incoming->medium,
MessageIntent::tryFrom((string) $stored->intent) ?? MessageIntent::Unclear,
$stored->booking,
array_values(array_filter(array_map(fn (string $effect): ?MessageEffect => MessageEffect::tryFrom($effect), (array) ($data['effects'] ?? [])))),
(array) ($data['reasons'] ?? []),
);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Models\Booking;
use App\Models\Tenant;
use App\Process\ProcessRunner;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
/**
* Evaluates binding bookings that wait for an event again (V2.1, docs/Prozessarchitektur/V2.1/02 §5): the portal's
* confirmation mail did not come in time (escalate once), came meanwhile (close the escalation, go on) – without this nothing
* would resume or time out, because no scheduler looks at binding cases. Only cases whose channel makes them wait are
* touched; once per landlord.
*/
#[Signature('bookings:advance-waiting')]
#[Description('Re-evaluate binding bookings that wait for a portal confirmation (deadline, escalation, resume) – once per landlord')]
class AdvanceWaitingCases extends Command
{
public function handle(TenantRunner $tenants, ProcessRunner $runner): int
{
$tenants->each(function (Tenant $tenant) use ($runner): void {
$evaluated = 0;
Booking::query()->occupying()->where('intake', 'booking')->where('created_at', '>', now()->subDays(90))
->with(['property', 'guest', 'importChannel', 'originChannel'])
->each(function (Booking $booking) use ($runner, &$evaluated): void {
if (! $booking->process()->awaitsPortalConfirmation()) {
return;
}
try {
$runner->advance($booking, 'schedule:waiting');
$evaluated++;
} catch (Throwable $exception) {
report($exception);
}
});
$this->info("{$tenant->name}: {$evaluated} wartende Vorgang/Vorgänge bewertet.");
});
return self::SUCCESS;
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
namespace App\Console\Commands;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
/**
* Checks the process catalogue (docs/Prozessarchitektur/Architektur/05 §2.2) and, with --cases, that every frozen plan
* of every case (open or finished, every landlord) can still be read: model versions and module versions registered or
* declared compatible (requirement T3). With --matrix it writes MODULMATRIX.md.
*/
#[Signature('process:check {--cases : also check the frozen plans of all cases} {--matrix : write docs/Prozessarchitektur/Architektur/MODULMATRIX.md}')]
#[Description('Check the process catalogue (modules, models, dependencies, tester-only parts) and the frozen plans of the cases')]
class ProcessCheck extends Command
{
public function handle(ProcessCatalogue $catalogue): int
{
$problems = $catalogue->problems();
if ($this->option('cases')) {
$problems = [...$problems, ...$this->cases($catalogue)];
}
if ($this->option('matrix')) {
$path = base_path('docs/Prozessarchitektur/Architektur/MODULMATRIX.md');
file_put_contents($path, $this->matrix($catalogue));
$this->info('Modulmatrix geschrieben: '.$path);
}
foreach ($problems as $problem) {
$this->error($problem);
}
if ($problems === []) {
$this->info(count($catalogue->modules()).' Module, '.count($catalogue->modelVersions()).' Modelle: ohne Befund.');
}
return $problems === [] ? self::SUCCESS : self::FAILURE;
}
/**
* @return list<string>
*/
private function cases(ProcessCatalogue $catalogue): array
{
$problems = [];
Booking::withoutGlobalScopes()->select(['id', 'reference', 'profile', 'status'])->whereNotNull('profile')->lazyById()->each(function (Booking $booking) use ($catalogue, &$problems): void {
$plan = (array) (($booking->profile ?? [])['plan'] ?? []);
if ($plan === []) {
return;
}
$frozen = ProcessPlan::fromArray($plan);
if (! $catalogue->hasModel($frozen->model)) {
$problems[] = "Vorgang {$booking->reference}: Modell {$frozen->model} ist nicht mehr registriert.";
} elseif (! $catalogue->hasModel($frozen->model, $frozen->modelVersion)) {
$problems[] = "Vorgang {$booking->reference}: Modellversion {$frozen->reference()} fehlt im Register (T3: Versionen nicht entfernen, solange Vorgänge sie tragen).";
}
foreach ($frozen->modules as $key => $version) {
if (! $catalogue->serves($key, $version) && ! in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
$problems[] = "Offener Vorgang {$booking->reference}: Modul {$key}@{$version} wird nicht mehr bedient.";
}
}
});
return $problems;
}
private function matrix(ProcessCatalogue $catalogue): string
{
$models = $catalogue->models();
$lines = [
'# Modulmatrix (erzeugt)',
'',
'Erzeugt von `php artisan process:check --matrix` aus `config/process.php` – nicht von Hand ändern. Spalten: Modelle (Standardablauf; `V` = nur in einer Variante).',
'',
'| Modul | Version | Phase | Aktivierung | Verfügbarkeit | hart abhängig von | '.implode(' | ', array_keys($models)).' | Testgruppe |',
'|'.str_repeat('---|', 7 + count($models)),
];
foreach ($catalogue->modules() as $key => $class) {
$definition = $class::definition();
$cells = array_map(function ($model) use ($key): string {
if (in_array($key, $model->modules('standard'), true)) {
return '●';
}
foreach ($model->variants() as $variant) {
if (in_array($key, $model->modules($variant->key), true)) {
return 'V';
}
}
return '';
}, $models);
$hard = implode(', ', array_map(fn ($dependency): string => $dependency->module, array_filter($definition->requires, fn ($dependency): bool => $dependency->hard)));
$lines[] = "| `{$key}` | {$class::version()} | {$definition->phase} | {$definition->toggle} | {$definition->availability} | {$hard} | ".implode(' | ', $cells)." | `module:{$key}` |";
}
return implode("\n", $lines)."\n";
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Checksums of what an update must never change by itself (docs/Prozessarchitektur/Architektur/06 U-F, step 6):
* the cases with their contract data and frozen profile, the channels' process configuration and the calendar blocks.
* Run before and after a deployment and compare. Only reads; prints no personal data.
*/
#[Signature('process:fingerprint')]
#[Description('Print checksums of cases, channel configurations and calendar blocks (compare before/after a deployment)')]
class ProcessFingerprint extends Command
{
public function handle(): int
{
$hash = fn ($query): string => md5($query->get()->map(fn (object $row): string => (string) json_encode($row))->implode("\n"));
$this->line((string) json_encode([
'bookings' => DB::table('bookings')->count(),
'channels' => DB::table('channels')->count(),
'blocked_periods' => DB::table('blocked_periods')->count(),
'h_bookings' => $hash(DB::table('bookings')->orderBy('id')->select('id', 'status', 'profile', 'total', 'quote', 'offer_terms', 'acceptance', 'arrival', 'departure', 'hold_expires_at', 'deposit_due_on', 'balance_due_on')),
'h_overrides' => $hash(DB::table('channels')->orderBy('id')->select('id', 'process_overrides', 'booking_model', 'case_intake')),
'h_blocks' => $hash(DB::table('blocked_periods')->orderBy('id')->select('id', 'starts_on', 'ends_on', 'source', 'channel_id', 'linked_booking_id', 'deleted_at')),
], JSON_PRETTY_PRINT));
return self::SUCCESS;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Console\Commands;
use App\Models\Channel;
use App\Process\Modules\ContributesToPrice;
use App\Process\Modules\RunsAutomatically;
use App\Process\ProcessCatalogue;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
/**
* Change impact of a module (docs/Prozessarchitektur/Architektur/05 §2): models and variants with their case types,
* extension points, dependent modules, parameters, whether it reads frozen contract data, the number of channels that
* chose an affected model (count only) and the test groups to run.
*/
#[Signature('process:impact {module : key of the module, e.g. offer.binding}')]
#[Description('Show which models, case types, dependent modules, channels and test groups a change of a process module affects')]
class ProcessImpact extends Command
{
public function handle(ProcessCatalogue $catalogue): int
{
$key = (string) $this->argument('module');
if (! $catalogue->hasModule($key)) {
$this->error("Unbekanntes Modul {$key}. Registriert: ".implode(', ', array_keys($catalogue->modules())));
return self::FAILURE;
}
$class = $catalogue->modules()[$key];
$definition = $class::definition();
$uses = [];
foreach ($catalogue->models() as $modelKey => $model) {
foreach ($model->variants() as $variant) {
if (in_array($key, $model->modules($variant->key), true)) {
$uses[] = $modelKey.($variant->key === 'standard' ? '' : ':'.$variant->key).' ('.implode('/', array_map(fn ($type): string => strtoupper($type->value), $model::caseTypes())).')';
}
}
}
$dependents = array_keys(array_filter($catalogue->modules(), fn (string $other): bool => collect($other::definition()->requires)->contains(fn ($dependency): bool => $dependency->module === $key)));
$modelKeys = array_map(fn (string $use): string => explode(' ', explode(':', $use)[0])[0], $uses);
$channels = Channel::withoutGlobalScopes()->get(['process_overrides'])->filter(fn (Channel $channel): bool => collect((array) $channel->process_overrides)->contains(fn ($config): bool => in_array($config['model'] ?? null, $modelKeys, true)))->count();
$this->table(['', $key.' v'.$class::version()], [
['Aufgabe', $definition->purpose],
['Phase / Aktivierung', $definition->phase.' / '.$definition->toggle.' / '.$definition->availability],
['Modelle', implode(', ', $uses) ?: '–'],
['Erweiterungspunkte', implode(', ', $definition->points) ?: 'fester Platz im Modell'],
['Benötigt', implode(', ', array_map(fn ($dependency): string => $dependency->module.($dependency->hard ? ' (hart)' : ' (weich)'), $definition->requires)) ?: '–'],
['Benötigt von', implode(', ', $dependents) ?: '–'],
['Läuft automatisch', is_subclass_of($class, RunsAutomatically::class) ? 'ja, Auslöser: '.implode(', ', $definition->triggers) : 'nein'],
['Preisbeitrag', is_subclass_of($class, ContributesToPrice::class) ? 'ja (CasePricing, nur vor Verbindlichkeit)' : 'nein'],
['Wertet Vertragsdaten aus', $definition->readsContractData ? 'ja – Bestandsfall-Test Pflicht (--group=ongoing)' : 'nein'],
['Parameter', implode(', ', array_map(fn ($parameter): string => is_string($parameter) ? $parameter : $parameter->value, $definition->parameters)) ?: '–'],
['Kanäle mit gewähltem Modell', (string) $channels],
['Tests', "--group=module:{$key} --group=golden --group=ongoing --group=runner"],
]);
return self::SUCCESS;
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Process\Tester\EffectLedger;
use App\Process\Tester\ProcessSandboxDriver;
use App\Process\Tester\SandboxBootstrapper;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
/**
* Entry of a tester run – only inside the process ProcessSandbox starts for it (environment FEWO_SANDBOX_RUN, so the
* SandboxBootstrapper has turned the process into a sandbox before anything was resolved). Reads input.json of the run
* and writes report.json; never touches anything outside the run's directory.
*/
#[Signature('process:sandbox-run {run : id of the prepared run}')]
#[Description('Play a process tester scenario inside its isolated process (started by the process tester only)')]
class ProcessSandboxRun extends Command
{
public function handle(ProcessSandboxDriver $driver): int
{
if (! SandboxBootstrapper::active() || (string) getenv(SandboxBootstrapper::ENV) !== (string) $this->argument('run') || config('sandbox.run') !== $this->argument('run')) {
$this->error('Nur innerhalb eines vom Prozess-Tester gestarteten Laufs.');
return self::FAILURE;
}
$directory = (string) config('sandbox.directory');
try {
$report = $driver->run((array) json_decode((string) file_get_contents($directory.'/input.json'), true));
} catch (Throwable $exception) {
$report = ['aborted' => 'Lauf abgebrochen: '.class_basename($exception).': '.$exception->getMessage(), 'timeline' => [], 'violations' => EffectLedger::violations()];
}
file_put_contents($directory.'/report.json', json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::SUCCESS;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
/**
* Builds the migrated, empty SQLite template of the process tester's databases (storage/app/sandbox/template.sqlite).
* Run at every deployment after the migrations; a run copies it instead of migrating. Touches only that file.
*/
#[Signature('process:sandbox-template')]
#[Description('Build the empty, migrated SQLite template for process tester runs')]
class ProcessSandboxTemplate extends Command
{
public function handle(): int
{
if (! extension_loaded('pdo_sqlite')) {
$this->warn('pdo_sqlite fehlt – der Prozess-Tester bleibt gesperrt.');
return self::SUCCESS;
}
$directory = storage_path('app/sandbox');
@mkdir($directory.'/runs', 0775, true);
$file = $directory.'/template.building.sqlite';
@unlink($file);
touch($file);
config(['database.connections.sandbox_template' => ['driver' => 'sqlite', 'database' => $file, 'prefix' => '', 'foreign_key_constraints' => true]]);
// `migrate --database` switches the default connection of this process and does not switch it back.
$default = DB::getDefaultConnection();
try {
Artisan::call('migrate', ['--database' => 'sandbox_template', '--force' => true, '--no-interaction' => true]);
} finally {
DB::setDefaultConnection($default);
DB::purge('sandbox_template');
config(['database.connections.sandbox_template' => null]);
}
rename($file, $directory.'/template.sqlite');
$this->info('Vorlage erstellt: '.$directory.'/template.sqlite');
return self::SUCCESS;
}
}
@@ -6,6 +6,7 @@
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Models\Booking; use App\Models\Booking;
use App\Models\Tenant; use App\Models\Tenant;
use App\Process\ProcessRunner;
use App\Tenancy\TenantRunner; use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Attributes\Signature;
@@ -19,9 +20,9 @@ class SendPendingAutoOffers extends Command
/** /**
* Execute the console command. * Execute the console command.
*/ */
public function handle(AutoOffer $autoOffer, TenantRunner $runner): int public function handle(AutoOffer $autoOffer, TenantRunner $tenants, ProcessRunner $runner): int
{ {
$runner->each(function (Tenant $tenant) use ($autoOffer): void { $tenants->each(function (Tenant $tenant) use ($autoOffer, $runner): void {
$pending = Booking::query() $pending = Booking::query()
->where('status', BookingStatus::Reserved) ->where('status', BookingStatus::Reserved)
->where('offer_version', 0) ->where('offer_version', 0)
@@ -36,7 +37,8 @@ public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
$sent = 0; $sent = 0;
foreach ($pending as $booking) { foreach ($pending as $booking) {
try { try {
$sent += $autoOffer->handle($booking) === [] ? 1 : 0; $result = $runner->advance($booking, 'schedule:bookings:auto-offers');
$sent += $result->ran('offer.binding') || $result->ran('offer.information') ? 1 : 0;
} catch (Throwable) { } catch (Throwable) {
// The request stays pending for the landlord; the next run tries again. // The request stays pending for the landlord; the next run tries again.
} }
+2 -1
View File
@@ -7,6 +7,7 @@
use App\Availability\AvailabilityChecker; use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\InquiryAnswer;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\ProcessSetting; use App\Enums\ProcessSetting;
use App\Enums\Responsibility; use App\Enums\Responsibility;
@@ -167,7 +168,7 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes,
'offer_message' => $changes['offer_message'] ?? $booking->offer_message, 'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
]); ]);
if (! $booking->process()->preReservation()) { if ($booking->process()->inquiryAnswer() === InquiryAnswer::Information) {
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht; vorgesehen ist eine unverbindliche Auskunft. Ein Angebot mit Annahmelink reserviert den Zeitraum für diesen Vorgang trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen.', DocumentFinding::HOLD_ZERO); $findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht; vorgesehen ist eine unverbindliche Auskunft. Ein Angebot mit Annahmelink reserviert den Zeitraum für diesen Vorgang trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen.', DocumentFinding::HOLD_ZERO);
} }
if ($booking->offer_version > 0) { if ($booking->offer_version > 0) {
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Whether the guest of a binding booking gets a short booking information (without contract) from us (docs/
* Prozessarchitektur/V2.1/02 §4) – independent of the contract documentation, which stays with its own step.
*/
enum BookingNoticeMode: string implements HasLabel
{
case Off = 'off';
case Automatic = 'automatic';
case AutomaticUnlessPortalConfirmed = 'automatic_unless_portal_confirmed';
case Manual = 'manual';
public function getLabel(): string
{
return match ($this) {
self::Off => 'keine eigene Buchungsinformation',
self::Automatic => 'automatisch senden',
self::AutomaticUnlessPortalConfirmed => 'automatisch senden – außer das Portal hat nachweislich bestätigt',
self::Manual => 'von Hand senden',
};
}
public function isAutomatic(): bool
{
return in_array($this, [self::Automatic, self::AutomaticUnlessPortalConfirmed], true);
}
}
+2
View File
@@ -23,6 +23,7 @@ enum BookingTaskKind: string implements HasLabel
case PortalCancellation = 'portal_cancellation'; case PortalCancellation = 'portal_cancellation';
case PortalCancellationReported = 'portal_cancel_reported'; case PortalCancellationReported = 'portal_cancel_reported';
case PortalChangeReported = 'portal_change_reported'; case PortalChangeReported = 'portal_change_reported';
case PortalConfirmationMissing = 'portal_confirmation_missing';
case RefundCheck = 'refund_check'; case RefundCheck = 'refund_check';
case BookingWish = 'booking_wish'; case BookingWish = 'booking_wish';
case ArrivalDetails = 'arrival_details'; case ArrivalDetails = 'arrival_details';
@@ -47,6 +48,7 @@ public function getLabel(): string
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen', self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen', self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen', self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen',
self::PortalConfirmationMissing => 'Bestätigungsmail des Portals fehlt – bitte beim Portal prüfen',
self::RefundCheck => 'Erstattung an den Gast prüfen', self::RefundCheck => 'Erstattung an den Gast prüfen',
self::BookingWish => 'Buchungswunsch bestätigen?', self::BookingWish => 'Buchungswunsch bestätigen?',
self::ArrivalDetails => 'Anreisedaten beim Gast erfragen', self::ArrivalDetails => 'Anreisedaten beim Gast erfragen',
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* What happens with the contract document of a booking that is binding (docs/Prozessarchitektur/V2.1/02 §4): creating
* and filing it is separate from sending it to the guest. `Follow` keeps the behaviour of V2: it goes out the way the case
* is processed (automatically or by the landlord's hand).
*/
enum ContractDelivery: string implements HasLabel
{
case Follow = 'follow';
case Automatic = 'automatic';
case Manual = 'manual';
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Follow => 'wie die übrige Bearbeitung',
self::Automatic => 'automatisch erstellen und an den Gast senden',
self::Manual => 'von Hand prüfen und senden',
self::Internal => 'erstellen und nur intern ablegen (nicht senden)',
};
}
/** The mode as the document step sees it: automatic when the case is processed automatically or the delivery says so. */
public function sendsAutomatically(ProcessingMode $processing): bool
{
return match ($this) {
self::Follow => $processing === ProcessingMode::Automatic,
self::Automatic => true,
self::Manual, self::Internal => false,
};
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ public static function forCase(Booking $booking): ?self
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal, $booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord, $booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation, $booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
! $profile->preReservation() => self::Information, $profile->inquiryAnswer() === InquiryAnswer::Information => self::Information,
default => self::Offer, default => self::Offer,
}; };
} }
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* The ways a task of the process may be fulfilled (docs/Prozessarchitektur/V2.1/02 §2). What is business-mandatory stays
* mandatory; the question is not „can I switch it off?“ but „which admissible ways do I have?“. A module names its ways,
* the process model narrows them for its archetype.
*/
enum Execution: string implements HasLabel
{
case Automatic = 'automatic';
case Approval = 'approval';
case Manual = 'manual';
case Portal = 'portal';
case ServiceProvider = 'service_provider';
case External = 'external';
case NotRequired = 'not_required';
public function getLabel(): string
{
return match ($this) {
self::Automatic => 'automatisch durch FewoPortal',
self::Approval => 'vorbereitet, nach Ihrer Freigabe',
self::Manual => 'von Ihnen von Hand',
self::Portal => 'durch das Portal',
self::ServiceProvider => 'durch einen Dienstleister',
self::External => 'bereits extern erledigt (mit Nachweis)',
self::NotRequired => 'nicht erforderlich',
};
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How a request is answered first: a non-binding information or a binding offer the guest can accept. Independent of the
* reservation strategy (ProcessSetting::PreReservation) – except that an information reserves nothing by definition.
*/
enum InquiryAnswer: string implements HasLabel
{
case Information = 'information';
case Offer = 'offer';
public function getLabel(): string
{
return match ($this) {
self::Information => 'Unverbindliche Auskunft',
self::Offer => 'Verbindliches Angebot',
};
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* The communication medium a message came through (V2.1). It says nothing about bindingness or business meaning.
* WhatsApp and Chat exist as test cases of the architecture; no provider is connected.
*/
enum Medium: string implements HasLabel
{
case Email = 'email';
case Form = 'form';
case WhatsApp = 'whatsapp';
case Chat = 'chat';
public function getLabel(): string
{
return match ($this) {
self::Email => 'E-Mail',
self::Form => 'Formular',
self::WhatsApp => 'WhatsApp',
self::Chat => 'Chat',
};
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* What a message may cause (V2.1). No effect creates a case, a reservation, an offer or a booking.
*/
enum MessageEffect: string implements HasLabel
{
case AnswerInformation = 'answer_information';
case ContributeFacts = 'contribute_facts';
case ReportToCase = 'report_to_case';
case HandoffInquiry = 'handoff_inquiry';
case Review = 'review';
public function getLabel(): string
{
return match ($this) {
self::AnswerInformation => 'allgemeine Auskunft geben',
self::ContributeFacts => 'Angaben für den Vorgang vorschlagen',
self::ReportToCase => 'Aufgabe am Vorgang anlegen',
self::HandoffInquiry => 'auf den Anfrageweg verweisen',
self::Review => 'zur Klärung vorlegen',
};
}
/** Effects that act on an existing case and therefore need a verified assignment. */
public function needsCase(): bool
{
return $this === self::ContributeFacts || $this === self::ReportToCase;
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use App\Communication\IntentClassifier;
use Filament\Support\Contracts\HasLabel;
/**
* What a message wants (V2.1) – decided by the rules of {@see IntentClassifier}, independent of the medium.
*/
enum MessageIntent: string implements HasLabel
{
case GeneralQuestion = 'general_question';
case StayInquiry = 'stay_inquiry';
case CaseReply = 'case_reply';
case ProvideData = 'provide_data';
case ChangeRequest = 'change_request';
case Unclear = 'unclear';
public function getLabel(): string
{
return match ($this) {
self::GeneralQuestion => 'allgemeine Frage',
self::StayInquiry => 'Anfrage zu einem Aufenthalt',
self::CaseReply => 'Antwort in einem Vorgang',
self::ProvideData => 'Angaben zu einem Vorgang',
self::ChangeRequest => 'Änderungswunsch',
self::Unclear => 'unklar',
};
}
}
+36 -7
View File
@@ -25,6 +25,13 @@ enum ProcessSetting: string
case DataRequestReminderHours = 'data_request_reminder_hours'; case DataRequestReminderHours = 'data_request_reminder_hours';
case GuestLinkValidDays = 'guest_link_valid_days'; case GuestLinkValidDays = 'guest_link_valid_days';
case FormRequiresAddress = 'form_requires_address'; case FormRequiresAddress = 'form_requires_address';
case ContractDelivery = 'contract_delivery';
case BookingNotice = 'booking_notice';
case AwaitPortalConfirmation = 'await_portal_confirmation';
case PortalConfirmationWaitHours = 'portal_confirmation_wait_hours';
case InquiryAnswer = 'inquiry_answer';
case ArrivalInfoSender = 'arrival_info_sender';
case ReviewRequestSender = 'review_request_sender';
/** /**
* Built-in default (the behaviour before any landlord setting existed). * Built-in default (the behaviour before any landlord setting existed).
@@ -46,6 +53,12 @@ public function default(): string|int|bool|null
self::DataRequestReminderHours => 24, self::DataRequestReminderHours => 24,
self::GuestLinkValidDays => 14, self::GuestLinkValidDays => 14,
self::FormRequiresAddress => false, self::FormRequiresAddress => false,
self::ContractDelivery => ContractDelivery::Follow->value,
self::BookingNotice => BookingNoticeMode::Off->value,
self::AwaitPortalConfirmation => false,
self::PortalConfirmationWaitHours => 48,
// Not set: derived (ProcessSettings) – the answer from the reservation, the senders from guest_messages.
self::InquiryAnswer, self::ArrivalInfoSender, self::ReviewRequestSender => null,
}; };
} }
@@ -71,6 +84,13 @@ public function question(): string
self::DataRequestReminderHours => 'Nach wie vielen Stunden ohne Antwort wird erinnert?', self::DataRequestReminderHours => 'Nach wie vielen Stunden ohne Antwort wird erinnert?',
self::GuestLinkValidDays => 'Wie lange gilt der Link, über den der Gast Angaben ergänzt?', self::GuestLinkValidDays => 'Wie lange gilt der Link, über den der Gast Angaben ergänzt?',
self::FormRequiresAddress => 'Muss die vollständige Anschrift schon im Anfrageformular der Webseite angegeben werden?', self::FormRequiresAddress => 'Muss die vollständige Anschrift schon im Anfrageformular der Webseite angegeben werden?',
self::ContractDelivery => 'Was geschieht mit dem Vertragsdokument einer verbindlichen Buchung?',
self::BookingNotice => 'Bekommt der Gast von uns eine Buchungsinformation (ohne Vertrag)?',
self::AwaitPortalConfirmation => 'Sollen Unterlagen und Nachrichten erst nach der Bestätigungsmail des Portals gehen?',
self::PortalConfirmationWaitHours => 'Wie lange wird auf die Bestätigungsmail des Portals gewartet, bevor Sie benachrichtigt werden?',
self::InquiryAnswer => 'Womit wird eine Anfrage zuerst beantwortet?',
self::ArrivalInfoSender => 'Wer schickt dem Gast die Anreise-Informationen?',
self::ReviewRequestSender => 'Wer bittet den Gast nach dem Aufenthalt um eine Bewertung?',
}; };
} }
@@ -82,9 +102,10 @@ public function question(): string
public function channelIntakes(): array public function channelIntakes(): array
{ {
return match ($this) { return match ($this) {
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate => [IntakeKind::Inquiry, IntakeKind::Booking], self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate, self::ArrivalInfoSender, self::ReviewRequestSender => [IntakeKind::Inquiry, IntakeKind::Booking],
self::InquiryAnswer => [IntakeKind::Inquiry],
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry], self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
self::Documents => [IntakeKind::Booking], self::Documents, self::ContractDelivery, self::BookingNotice, self::AwaitPortalConfirmation, self::PortalConfirmationWaitHours => [IntakeKind::Booking],
self::ArrivalInfoDaysBefore, self::GuestLinkValidDays => [], self::ArrivalInfoDaysBefore, self::GuestLinkValidDays => [],
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::FormRequiresAddress => [IntakeKind::Inquiry], self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::FormRequiresAddress => [IntakeKind::Inquiry],
self::DataRequest, self::DataRequestRemindersMax, self::DataRequestFollowupsMax, self::DataRequestReminderHours => [IntakeKind::Inquiry, IntakeKind::Booking], self::DataRequest, self::DataRequestRemindersMax, self::DataRequestFollowupsMax, self::DataRequestReminderHours => [IntakeKind::Inquiry, IntakeKind::Booking],
@@ -96,7 +117,7 @@ public function channelIntakes(): array
*/ */
public function isLandlordSetting(): bool public function isLandlordSetting(): bool
{ {
return $this !== self::ContractTemplate; return ! in_array($this, [self::ContractTemplate, self::InquiryAnswer], true);
} }
/** /**
@@ -110,13 +131,16 @@ public function normalize(mixed $value): string|int|bool|null
return match ($this) { return match ($this) {
self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value, self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value,
self::Documents, self::Payments, self::GuestMessages => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value, self::Documents, self::Payments, self::GuestMessages, self::ArrivalInfoSender, self::ReviewRequestSender => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value,
self::PreReservation, self::FormRequiresAddress => is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), self::InquiryAnswer => ($value instanceof InquiryAnswer ? $value : InquiryAnswer::tryFrom((string) $value))?->value,
self::PreReservation, self::FormRequiresAddress, self::AwaitPortalConfirmation => is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null, self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
self::DataRequest => ($value instanceof DataRequestMode ? $value : DataRequestMode::tryFrom((string) $value))?->value, self::DataRequest => ($value instanceof DataRequestMode ? $value : DataRequestMode::tryFrom((string) $value))?->value,
self::ContractDelivery => ($value instanceof ContractDelivery ? $value : ContractDelivery::tryFrom((string) $value))?->value,
self::BookingNotice => ($value instanceof BookingNoticeMode ? $value : BookingNoticeMode::tryFrom((string) $value))?->value,
// 0 is a value of its own: no clarification hold, no reminder, no follow-up question. // 0 is a value of its own: no clarification hold, no reminder, no follow-up question.
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::DataRequestRemindersMax, self::DataRequestFollowupsMax => is_numeric($value) ? max(0, (int) $value) : null, self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::DataRequestRemindersMax, self::DataRequestFollowupsMax => is_numeric($value) ? max(0, (int) $value) : null,
self::DataRequestReminderHours, self::GuestLinkValidDays => is_numeric($value) ? max(1, (int) $value) : null, self::DataRequestReminderHours, self::GuestLinkValidDays, self::PortalConfirmationWaitHours => is_numeric($value) ? max(1, (int) $value) : null,
}; };
} }
@@ -127,7 +151,8 @@ public function describe(string|int|bool|null $value): string
{ {
return match ($this) { return match ($this) {
self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–', self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–',
self::Documents, self::Payments, self::GuestMessages => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–', self::Documents, self::Payments, self::GuestMessages, self::ArrivalInfoSender, self::ReviewRequestSender => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–',
self::InquiryAnswer => InquiryAnswer::tryFrom((string) $value)?->getLabel() ?? '–',
self::PreReservation => $value ? 'ja' : 'nein', self::PreReservation => $value ? 'ja' : 'nein',
self::HoldHours => $value.' Stunden', self::HoldHours => $value.' Stunden',
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise', self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
@@ -139,6 +164,10 @@ public function describe(string|int|bool|null $value): string
self::DataRequestReminderHours => 'nach '.$value.' Stunden', self::DataRequestReminderHours => 'nach '.$value.' Stunden',
self::GuestLinkValidDays => $value.' Tage', self::GuestLinkValidDays => $value.' Tage',
self::FormRequiresAddress => $value ? 'ja, Pflichtangabe' : 'nein, kann nachgefragt werden', self::FormRequiresAddress => $value ? 'ja, Pflichtangabe' : 'nein, kann nachgefragt werden',
self::ContractDelivery => ContractDelivery::tryFrom((string) $value)?->getLabel() ?? '–',
self::BookingNotice => BookingNoticeMode::tryFrom((string) $value)?->getLabel() ?? '–',
self::AwaitPortalConfirmation => $value ? 'ja, erst nach der Bestätigungsmail' : 'nein',
self::PortalConfirmationWaitHours => $value.' Stunden',
}; };
} }
} }
+12 -1
View File
@@ -2,7 +2,10 @@
namespace App\Filament\Forms; namespace App\Filament\Forms;
use App\Enums\BookingNoticeMode;
use App\Enums\ContractDelivery;
use App\Enums\DataRequestMode; use App\Enums\DataRequestMode;
use App\Enums\InquiryAnswer;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting; use App\Enums\ProcessSetting;
use App\Enums\Responsibility; use App\Enums\Responsibility;
@@ -37,7 +40,8 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'), ->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – der Gast erhält eine unverbindliche Auskunft und kann daraus die Buchung anfragen (erneute Prüfung vor der Bestätigung)'])->placeholder($placeholder), ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – der Gast erhält eine unverbindliche Auskunft und kann daraus die Buchung anfragen (erneute Prüfung vor der Bestätigung)'])->placeholder($placeholder),
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder), ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder), ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoSender, ProcessSetting::ReviewRequestSender => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder),
ProcessSetting::InquiryAnswer => Select::make($name)->options(InquiryAnswer::class)->placeholder($placeholder),
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder), ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
ProcessSetting::ContractTemplate => Select::make($name) ProcessSetting::ContractTemplate => Select::make($name)
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
@@ -49,6 +53,13 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax => TextInput::make($name)->integer()->minValue(0)->maxValue(5)->placeholder($placeholder), ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax => TextInput::make($name)->integer()->minValue(0)->maxValue(5)->placeholder($placeholder),
ProcessSetting::DataRequestReminderHours => TextInput::make($name)->integer()->minValue(1)->maxValue(336)->suffix('Stunden')->placeholder($placeholder), ProcessSetting::DataRequestReminderHours => TextInput::make($name)->integer()->minValue(1)->maxValue(336)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::GuestLinkValidDays => TextInput::make($name)->integer()->minValue(1)->maxValue(60)->suffix('Tage')->placeholder($placeholder), ProcessSetting::GuestLinkValidDays => TextInput::make($name)->integer()->minValue(1)->maxValue(60)->suffix('Tage')->placeholder($placeholder),
ProcessSetting::ContractDelivery => Select::make($name)->options(ContractDelivery::class)->placeholder($placeholder)
->helperText('Erstellen und Ablegen sind vom Versand getrennt. Ein nur intern abgelegter Vertrag gilt nicht als gesendet. Gilt für extern verbindliche Buchungen, bei denen wir die Vertragsunterlagen übernehmen.'),
ProcessSetting::BookingNotice => Select::make($name)->options(BookingNoticeMode::class)->placeholder($placeholder)
->helperText('Eine kurze Information über die Buchung – unabhängig vom Vertrag. Das Portal bleibt für seine eigenen Nachrichten zuständig.'),
ProcessSetting::AwaitPortalConfirmation => Select::make($name)->options(['1' => 'Ja – Unterlagen und Nachrichten warten auf die Bestätigungsmail des Portals', '0' => 'Nein – sofort bearbeiten'])->placeholder($placeholder)
->helperText('Die Belegung ist von Anfang an gesichert; es wartet nur, was Sie hier einstellen. Bleibt die Mail aus, erhalten Sie eine Aufgabe.'),
ProcessSetting::PortalConfirmationWaitHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::FormRequiresAddress => Select::make($name)->options(['1' => 'Ja – ohne vollständige Anschrift kann nicht angefragt werden', '0' => 'Nein – fehlt sie, wird beim Gast nachgefragt'])->placeholder($placeholder), ProcessSetting::FormRequiresAddress => Select::make($name)->options(['1' => 'Ja – ohne vollständige Anschrift kann nicht angefragt werden', '0' => 'Nein – fehlt sie, wird beim Gast nachgefragt'])->placeholder($placeholder),
})->label($setting->question()); })->label($setting->question());
} }
+4 -1
View File
@@ -2,6 +2,7 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use App\Enums\InquiryAnswer;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\ProcessSetting; use App\Enums\ProcessSetting;
use App\Enums\UserRole; use App\Enums\UserRole;
@@ -112,7 +113,9 @@ public static function where(ProcessSetting $setting): string
public static function answer(ProcessProfile $profile): string public static function answer(ProcessProfile $profile): string
{ {
return match ($profile->intake) { return match ($profile->intake) {
IntakeKind::Inquiry => $profile->preReservation() ? 'Angebot mit Annahmelink, Zeitraum reserviert' : 'Unverbindliche Auskunft, „Buchung anfragen“, erneute Prüfung', IntakeKind::Inquiry => $profile->inquiryAnswer() === InquiryAnswer::Offer
? 'Angebot mit Annahmelink'.($profile->preReservation() ? ', Zeitraum schon bei der Anfrage reserviert' : ', Zeitraum erst mit dem Angebot reserviert')
: 'Unverbindliche Auskunft, „Buchung anfragen“, erneute Prüfung',
IntakeKind::Booking => 'keine – beim Portal bereits verbindlich', IntakeKind::Booking => 'keine – beim Portal bereits verbindlich',
IntakeKind::Internal => 'keine – eigene Belegung', IntakeKind::Internal => 'keine – eigene Belegung',
}; };
@@ -12,10 +12,14 @@
use App\Enums\BookingTaskKind; use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\InquiryAnswer;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Filament\Forms\DocumentCompositionFields; use App\Filament\Forms\DocumentCompositionFields;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask; use App\Models\BookingTask;
use App\Pricing\CaseMoney;
use App\Pricing\StayRequest; use App\Pricing\StayRequest;
use App\Process\CaseClosure; use App\Process\CaseClosure;
use App\Process\CaseLog; use App\Process\CaseLog;
@@ -49,7 +53,7 @@ private function sendInformationAction(): Action
->label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden') ->label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane) ->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking
&& ! $this->record->process()->preReservation() && $this->record->offer_version === 0 && ! $this->record->isHoldActive()) && $this->record->process()->inquiryAnswer() === InquiryAnswer::Information && $this->record->offer_version === 0 && ! $this->record->isHoldActive())
->modalHeading('Unverbindliche Auskunft an den Gast') ->modalHeading('Unverbindliche Auskunft an den Gast')
->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.') ->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.')
->modalSubmitActionLabel('Senden') ->modalSubmitActionLabel('Senden')
@@ -230,14 +234,37 @@ private function settleAction(): Action
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null) ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null)
->modalHeading('Kaufmännisch abschließen') ->modalHeading('Kaufmännisch abschließen')
->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).') ->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).')
->schema([Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500)]) ->schema([
// Decision O5: with portal collection an open payout needs its financial clarification, not only a reason.
Select::make('clarification')->label('Wie ist die Auszahlung geklärt?')
->options(CaseClosure::PAYOUT_CLARIFICATIONS)
->visible(fn (): bool => $this->payoutOpen())
->required(fn (): bool => $this->payoutOpen())
->helperText('Eine Meldung des Portals über die Auszahlung ist kein Nachweis des Geldeingangs. „Als offene Forderung weiterführen“ legt eine Aufgabe an; der Vorgang bleibt kaufmännisch offen.'),
Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500),
])
->action(function (array $data): void { ->action(function (array $data): void {
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor()); try {
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor(), $data['clarification'] ?? null);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht abgeschlossen')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh(); $this->record->refresh();
Notification::make()->title('Kaufmännisch abgeschlossen')->success()->send(); Notification::make()->title($this->record->settled_at !== null ? 'Kaufmännisch abgeschlossen' : 'Als offene Forderung weitergeführt')->success()->send();
}); });
} }
/**
* Whether the portal's payout is open or deviating (decision O5).
*/
private function payoutOpen(): bool
{
return CaseMoney::of($this->record)->collector() === Responsibility::Portal
&& collect(CaseClosure::commercialPoints($this->record))->contains(fn (string $point): bool => str_contains($point, 'Auszahlung'));
}
/** /**
* Open tasks the landlord can settle on the page (not the ones with an action of their own). * Open tasks the landlord can settle on the page (not the ones with an action of their own).
* *
@@ -11,6 +11,7 @@
use App\Actions\RecordPortalAmounts; use App\Actions\RecordPortalAmounts;
use App\Actions\RequestCaseData; use App\Actions\RequestCaseData;
use App\Actions\SendBookingDocuments; use App\Actions\SendBookingDocuments;
use App\Actions\SendBookingNotice;
use App\Actions\SendOffer; use App\Actions\SendOffer;
use App\Actions\SetBookingStatus; use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms; use App\Documents\OfferTerms;
@@ -18,12 +19,14 @@
use App\Enums\ActivityState; use App\Enums\ActivityState;
use App\Enums\AdminMode; use App\Enums\AdminMode;
use App\Enums\AmountKind; use App\Enums\AmountKind;
use App\Enums\BookingNoticeMode;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind; use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis; use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus; use App\Enums\ChangeStatus;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\InquiryAnswer;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\InternalKind; use App\Enums\InternalKind;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
@@ -50,6 +53,8 @@
use App\Process\CaseAutomation; use App\Process\CaseAutomation;
use App\Process\CaseLog; use App\Process\CaseLog;
use App\Process\CaseRequirements; use App\Process\CaseRequirements;
use App\Process\PortalConfirmation;
use App\Process\ProcessRunner;
use App\Support\Countries; use App\Support\Countries;
use App\Support\Money; use App\Support\Money;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
@@ -141,6 +146,8 @@ protected function getHeaderActions(): array
$this->confirmAction(), $this->confirmAction(),
$this->sendDocumentsAction(), $this->sendDocumentsAction(),
$this->resendConfirmationAction(), $this->resendConfirmationAction(),
$this->confirmPortalAction(),
$this->sendBookingNoticeAction(),
$this->portalPriceAction(), $this->portalPriceAction(),
$this->changeAction(), $this->changeAction(),
$this->confirmPortalCancellationAction(), $this->confirmPortalCancellationAction(),
@@ -184,7 +191,7 @@ private function sendOfferAction(): Action
return Action::make('sendOffer') return Action::make('sendOffer')
->label(fn (): string => match (true) { ->label(fn (): string => match (true) {
$this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden', $this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden',
! $this->record->process()->preReservation() => 'Stattdessen verbindliches Angebot mit Reservierung senden', $this->record->process()->inquiryAnswer() === InquiryAnswer::Information => 'Stattdessen verbindliches Angebot mit Reservierung senden',
default => 'Angebot prüfen und senden', default => 'Angebot prüfen und senden',
}) })
->icon(Heroicon::OutlinedPaperAirplane) ->icon(Heroicon::OutlinedPaperAirplane)
@@ -492,6 +499,50 @@ private function confirmAction(): Action
}); });
} }
/**
* V2.1: the landlord states that the portal confirmed the booking (e.g. seen in the portal's own interface). The steps that
* wait for it go on; the booking itself was binding from the start.
*/
private function confirmPortalAction(): Action
{
return Action::make('confirmPortal')
->label('Bestätigung des Portals festhalten')
->icon(Heroicon::OutlinedCheckBadge)
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->awaitsPortalConfirmation() && PortalConfirmation::evidence($this->record) === null)
->modalDescription('Das Portal hat die Buchung bestätigt (z. B. in seiner Oberfläche gesehen). Unterlagen und Nachrichten, die darauf warten, gehen dann weiter. Die Buchung bleibt wie sie ist.')
->schema([Textarea::make('note')->label('Woran haben Sie das gesehen?')->rows(2)->maxLength(500)])
->action(function (array $data): void {
PortalConfirmation::confirm($this->record, CaseLog::actor(), $data['note'] ?? null);
app(ProcessRunner::class)->advance($this->record->fresh(), 'portal.mail');
$this->record->refresh();
Notification::make()->title('Bestätigung festgehalten')->success()->send();
});
}
/**
* V2.1: the short booking information to the guest, sent by hand (also where the automatic dispatch is off).
*/
private function sendBookingNoticeAction(): Action
{
return Action::make('sendBookingNotice')
->label('Buchungsinformation an den Gast senden')
->icon(Heroicon::OutlinedEnvelope)
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->bookingNotice() !== BookingNoticeMode::Off && ! SendBookingNotice::sent($this->record) && filled($this->record->guest?->email))
->requiresConfirmation()
->modalDescription('Der Gast erhält eine kurze Information über seine Buchung – ohne Vertrag.')
->action(function (SendBookingNotice $notice): void {
try {
$notice->handle($this->record->fresh());
} catch (ReservationException $exception) {
Notification::make()->title('Nicht gesendet')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
Notification::make()->title('Buchungsinformation gesendet')->success()->send();
});
}
private function resendConfirmationAction(): Action private function resendConfirmationAction(): Action
{ {
return Action::make('resendConfirmation') return Action::make('resendConfirmation')
@@ -16,6 +16,8 @@
use App\Pricing\CaseMoney; use App\Pricing\CaseMoney;
use App\Process\CaseActivities; use App\Process\CaseActivities;
use App\Process\CaseAutomation; use App\Process\CaseAutomation;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use App\Process\ProcessProfile; use App\Process\ProcessProfile;
use App\Support\Money; use App\Support\Money;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
@@ -121,6 +123,7 @@ public static function configure(Schema $schema): Schema
->schema([ ->schema([
TextEntry::make('status')->label('Status')->badge(), TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()), TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
TextEntry::make('templates')->label('Funktionsschablonen')->state(fn (Booking $record): ?string => self::templates($record))->placeholder('– (fester Ablauf)'),
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'), TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(), TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(),
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(), TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
@@ -238,6 +241,17 @@ private static function history(Booking $booking): HtmlString
return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>'); return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
} }
/**
* The function templates the case was composed with, as frozen in its plan (null for the fixed models).
*/
private static function templates(Booking $record): ?string
{
$catalogue = app(ProcessCatalogue::class);
$labels = array_map(fn (string $reference): string => ($class = $catalogue->templateClass($reference)) !== null ? $class::label().' ('.$reference.')' : $reference, ProcessPlan::of($record)->templates);
return $labels === [] ? null : implode(' · ', $labels);
}
private static function profile(Booking $booking): HtmlString private static function profile(Booking $booking): HtmlString
{ {
$profile = $booking->process(); $profile = $booking->process();
@@ -4,6 +4,8 @@
use App\Filament\Concerns\FollowsAdminMode; use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Concerns\SelectsRecordProperty; use App\Filament\Concerns\SelectsRecordProperty;
use App\Filament\Resources\Channels\Pages\ChannelProcess;
use App\Filament\Resources\Channels\Pages\ChannelProcessTest;
use App\Filament\Resources\Channels\Pages\ChannelRules; use App\Filament\Resources\Channels\Pages\ChannelRules;
use App\Filament\Resources\Channels\Pages\CreateChannel; use App\Filament\Resources\Channels\Pages\CreateChannel;
use App\Filament\Resources\Channels\Pages\EditChannel; use App\Filament\Resources\Channels\Pages\EditChannel;
@@ -61,6 +63,8 @@ public static function getPages(): array
'create' => CreateChannel::route('/create'), 'create' => CreateChannel::route('/create'),
'edit' => EditChannel::route('/{record}/edit'), 'edit' => EditChannel::route('/{record}/edit'),
'rules' => ChannelRules::route('/{record}/rules'), 'rules' => ChannelRules::route('/{record}/rules'),
'process' => ChannelProcess::route('/{record}/process'),
'test' => ChannelProcessTest::route('/{record}/test'),
]; ];
} }
} }
@@ -0,0 +1,619 @@
<?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\ProcessBlocks;
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 App\Process\Templates\TemplateComposer;
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;
/** The business block opened in the detail panel ('' = none). */
public string $block = '';
public function mount(int|string $record): void
{
$this->record = $this->resolveRecord($record);
$configuration = app(ChannelProcessConfiguration::class);
foreach ($configuration->intakes($this->record) as $intake) {
$this->drafts[$intake->value] = $this->storedDraft($intake);
}
$this->intake = (string) array_key_first($this->drafts);
$this->block = '';
$this->capabilityDraft = $this->storedCapabilities();
}
/**
* The draft as it is stored (or derived) now – the reference for "unsaved changes" and for discarding them.
* 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.
*
* @return array<string, mixed>
*/
private function storedDraft(IntakeKind $intake): array
{
$current = app(ChannelProcessConfiguration::class)->current($this->record, $intake);
$stored = (array) (($this->record->process_overrides ?? [])[$intake->value] ?? []);
return [
'model' => $current['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'],
];
}
/**
* @return array<string, string>
*/
private function storedCapabilities(): array
{
return $this->record->isWebsite() ? [] : collect(app(ChannelCapabilities::class)->resolve($this->record))
->map(fn (Capability $capability): string => $capability->value === null ? '' : ($capability->value ? '1' : '0'))->all();
}
/**
* Whether the draft of the current intake kind differs from what is stored (nothing is saved by looking or selecting).
*/
public function dirty(): bool
{
$normalise = fn (array $draft): array => [
'model' => $draft['model'],
'variant' => $draft['variant'],
'steps' => array_filter((array) $draft['steps']),
'templates' => (array) $draft['templates'],
'settings' => array_filter((array) $draft['settings'], fn (mixed $value): bool => $value !== null && $value !== ''),
];
return $normalise($this->drafts[$this->intake]) != $normalise($this->storedDraft(IntakeKind::from($this->intake)))
|| $this->capabilityDraft != $this->storedCapabilities();
}
/**
* Throws the unsaved changes away and shows the stored configuration again.
*/
public function discard(): void
{
$intake = $this->intake;
$this->acknowledge = false;
$this->mount($this->record->getKey());
$this->intake = $intake;
}
public function selectBlock(string $block): void
{
$this->block = $this->block === $block ? '' : $block;
}
public function updatedIntake(): void
{
$this->block = '';
}
/**
* 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 business blocks of the course with what is effective in each: values and their origin, the template chosen for
* its decision, what depends on what (derived from the resolved plan, see {@see ProcessBlocks}), the steps that can
* be configured here and the fixed ones (no controls, shown as one line), gaps the template names, open problems.
*
* @return array<string, array<string, mixed>>
*/
public function blocks(): array
{
$intake = IntakeKind::from($this->intake);
$configuration = app(ChannelProcessConfiguration::class);
$profile = $this->profile();
$model = $this->model();
$rows = $configuration->preview($this->record, $intake, $this->draft());
$templates = app(TemplateComposer::class)->classes($configuration->templatesOf($model, $this->draft()));
$steps = collect($this->steps())->keyBy('module');
$conflicts = collect($this->conflicts())->map(fn (array $conflict): string => $conflict['setting']->value)->all();
$problems = $this->problems();
$blocks = [];
foreach (app(ProcessBlocks::class)->of($rows) as $key => $block) {
$template = $block['area'] === null ? null : ($templates[$block['area']->value] ?? null);
$settings = array_values(array_filter($block['settings'], fn (ProcessSetting $setting): bool => in_array($intake, $setting->channelIntakes(), true)));
$blockSteps = array_values(array_filter(array_map(fn (array $row): ?array => $steps[$row['module']] ?? null, $block['modules'])));
$configurable = array_values(array_filter($blockSteps, fn (array $step): bool => $step['on'] && ($step['optional'] || $step['mode_setting'] || ($step['performer_setting'] && count($step['performer_options']) > 1) || $step['parameters'] !== [])
|| (! $step['on'] && $step['optional'])));
$fixed = array_values(array_filter($blockSteps, fn (array $step): bool => $step['on'] && ! in_array($step, $configurable, true)));
$blocks[$key] = [...$block,
'facts' => array_map(fn (ProcessSetting $setting): array => $this->setting($setting, $profile), $settings),
'template' => $template,
'extensions' => $template === null ? [] : $template::extensions(),
'configurable' => $configurable,
'fixed' => $fixed,
'off' => array_values(array_filter($blockSteps, fn (array $step): bool => ! $step['on'])),
'attention' => count(array_filter($settings, fn (ProcessSetting $setting): bool => in_array($setting->value, $conflicts, true))),
'problems' => $this->blockProblems($problems, $block['label'], $template, $settings),
];
}
return $blocks;
}
/**
* The problems of the draft that concern a block: they name its template or one of its settings.
*
* @param list<string> $problems
* @param class-string<FunctionTemplate>|null $template
* @param list<ProcessSetting> $settings
* @return list<string>
*/
private function blockProblems(array $problems, string $label, ?string $template, array $settings): array
{
return array_values(array_filter($problems, fn (string $problem): bool => ($template !== null && str_contains($problem, $template::label()))
|| collect($settings)->contains(fn (ProcessSetting $setting): bool => str_contains($problem, $setting->question()))));
}
/**
* Problems of the draft that belong to no block (shown above the blocks).
*
* @return list<string>
*/
public function problemsOutsideBlocks(): array
{
$inBlocks = collect($this->blocks())->flatMap(fn (array $block): array => $block['problems'])->all();
return array_values(array_diff($this->problems(), $inBlocks));
}
/**
* 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])),
];
}
}
@@ -0,0 +1,151 @@
<?php
namespace App\Filament\Resources\Channels\Pages;
use App\Enums\IntakeKind;
use App\Enums\UserRole;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use App\Process\Tester\ProcessSandbox;
use App\Process\Tester\ScenarioCatalogue;
use App\Process\Tester\Scenarios\Scenario;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Throwable;
/**
* Ablauf testen (docs/Prozessarchitektur/Architektur/04): plays a predefined scenario with the channel's current – also
* unsaved – process configuration in an isolated run and shows the report step by step. Nothing of a run reaches the
* real data, mails, calendars or portals; on a server where the isolation cannot be established the tester is locked
* and says why. Landlord administrators only (decision E8).
*
* @property Channel $record
*/
class ChannelProcessTest extends Page
{
use InteractsWithRecord;
protected static string $resource = ChannelResource::class;
protected static ?string $title = 'Ablauf testen';
protected string $view = 'filament.resources.channels.channel-process-test';
public string $intake = 'inquiry';
public string $scenario = '';
/** @var array<string, mixed> */
public array $inputs = [];
/** @var array<string, mixed> */
public array $draft = [];
public int $steps = 1;
public ?int $runId = null;
public static function canAccess(array $parameters = []): bool
{
$user = auth()->user();
return $user instanceof User && $user->hasRole(UserRole::Admin);
}
public function mount(int|string $record): void
{
$this->record = $this->resolveRecord($record);
$intakes = array_map(fn (IntakeKind $intake): string => $intake->value, app(ChannelProcessConfiguration::class)->intakes($this->record));
$requested = (string) request()->query('intake', '');
$this->intake = in_array($requested, $intakes, true) ? $requested : ($intakes[0] ?? 'inquiry');
$this->draft = (array) session()->get($this->draftKey(), []);
if ($this->draft === []) {
$current = app(ChannelProcessConfiguration::class)->current($this->record, IntakeKind::from($this->intake));
$stored = (array) (($this->record->process_overrides ?? [])[$this->intake] ?? []);
$this->draft = ['model' => $current['model'], 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), 'templates' => $current['templates'], 'settings' => []];
}
$this->scenario = (string) array_key_first($this->scenarios());
$this->resetInputs();
}
public function draftKey(): string
{
return 'process-tester.draft.'.$this->record->id.'.'.$this->intake;
}
/**
* @return array<string, class-string<Scenario>>
*/
public function scenarios(): array
{
return ScenarioCatalogue::for(IntakeKind::from($this->intake), $this->record->isWebsite());
}
public function updatedScenario(): void
{
$this->resetInputs();
$this->runId = null;
$this->steps = 1;
}
private function resetInputs(): void
{
$class = $this->scenarios()[$this->scenario] ?? null;
$this->inputs = $class === null ? [] : array_map(fn (array $input): mixed => $input['type'] === 'date' ? now()->modify((string) $input['default'])->toDateString() : $input['default'], $class::inputs());
}
/**
* @return list<string>
*/
public function requirements(): array
{
return ProcessSandbox::requirements();
}
public function start(): void
{
$this->steps = 1;
$this->play();
}
public function next(): void
{
$this->steps++;
$this->play();
}
private function play(): void
{
try {
$run = app(ProcessSandbox::class)->run($this->record, IntakeKind::from($this->intake), $this->draft, $this->scenario, $this->inputs, $this->steps, auth()->user());
$this->runId = $run->id;
} catch (Throwable $exception) {
Notification::make()->title('Test nicht möglich')->body($exception->getMessage())->danger()->persistent()->send();
}
}
public function run(): ?ProcessTestRun
{
return $this->runId === null ? null : ProcessTestRun::query()->find($this->runId);
}
/**
* @return iterable<ProcessTestRun>
*/
public function recent(): iterable
{
return ProcessTestRun::query()->where('channel_id', $this->record->id)->latest()->limit(5)->get();
}
protected function getHeaderActions(): array
{
return [
Action::make('back')->label('Zurück zum Ablauf')->color('gray')->url(fn (): string => ChannelResource::getUrl('process', ['record' => $this->record])),
];
}
}
@@ -19,6 +19,7 @@ class EditChannel extends EditRecord
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
return [ 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('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 { Action::make('analyze')->label('Kalender analysieren')->visible(fn (): bool => $this->record->isPortal())->action(function (AnalyzeChannelCalendar $analyze): void {
try { try {
@@ -38,10 +39,8 @@ protected function mutateFormDataBeforeFill(array $data): array
protected function handleRecordUpdate(Model $record, array $data): Model 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()) { if ($record instanceof Channel && $record->isWebsite()) {
$record->update(['process_overrides' => $data['process_overrides'] ?? []]);
return $record; return $record;
} }
@@ -8,9 +8,7 @@
use App\Enums\ChannelEchoBehavior; use App\Enums\ChannelEchoBehavior;
use App\Enums\ChannelExportMode; use App\Enums\ChannelExportMode;
use App\Enums\ChannelStatus; use App\Enums\ChannelStatus;
use App\Enums\IntakeKind; use App\Filament\Resources\Channels\ChannelResource;
use App\Enums\ProcessSetting;
use App\Filament\Forms\ProcessSettingFields;
use App\Models\Channel; use App\Models\Channel;
use App\Models\Property; use App\Models\Property;
use App\Support\CurrentProperty; use App\Support\CurrentProperty;
@@ -21,6 +19,7 @@
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\TextEntry; use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Group; use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Components\Utilities\Get;
@@ -68,7 +67,12 @@ public static function configure(Schema $schema, bool $selectProperty = false):
->required() ->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.') ->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(), ->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') Select::make('connector')
->label('Kalenderanbindung') ->label('Kalenderanbindung')
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.') ->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 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 [ return [
Section::make('Anfragen über die eigene Webseite') 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.') ->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).')
->columns(2)
->columnSpanFull() ->columnSpanFull()
->visible(fn (?Channel $record): bool => $record?->isWebsite() ?? false) ->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. * The process of a channel is set up step by step on its own page (Kanal › Ablauf), no longer as a flat list here.
*/
/**
* 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).
* *
* @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 [ return [
Section::make('Anfragen über dieses Portal') TextEntry::make('process_link')->hiddenLabel()->columnSpanFull()
->description('Nur ausfüllen, was bei diesem Portal anders ist als in Ihren Standardeinstellungen.') ->state(fn (?Channel $record): string => $record === null ? 'Den Ablauf richten Sie nach dem Anlegen unter „Ablauf“ ein.' : $label.': Ablaufmodell wählen und Schritte einstellen.')
->columns(2) ->url(fn (?Channel $record): ?string => $record === null ? null : ChannelResource::getUrl('process', ['record' => $record]))
->columnSpanFull() ->color('primary'),
->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)),
]; ];
} }
} }
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* A short booking information for the guest of a binding booking – without contract and without attachment
* (V2.1 „Buchungsinformation“, independent of the contract documentation). Working draft like the other guest texts:
* it only goes out automatically where the landlord chose that for the channel.
*/
class BookingNotice extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Buchung '.($this->booking->portal_reference ?? $this->booking->reference),
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-notice');
}
}
+2 -1
View File
@@ -12,7 +12,7 @@
* to a case only by a reliable reference (CH-13); otherwise it waits in the inbox for the landlord. Being assigned is * to a case only by a reliable reference (CH-13); otherwise it waits in the inbox for the landlord. Being assigned is
* not yet permission to take anything over. * not yet permission to take anything over.
*/ */
#[Fillable(['mailbox_id', 'message_id', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])] #[Fillable(['mailbox_id', 'message_id', 'medium', 'intent', 'decision', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])]
class InboundMessage extends Model class InboundMessage extends Model
{ {
use BelongsToTenant; use BelongsToTenant;
@@ -44,6 +44,7 @@ protected function casts(): array
'to_addresses' => 'array', 'to_addresses' => 'array',
'hints' => 'array', 'hints' => 'array',
'extraction' => 'array', 'extraction' => 'array',
'decision' => 'array',
'test_mode' => 'boolean', 'test_mode' => 'boolean',
'received_at' => 'immutable_datetime', 'received_at' => 'immutable_datetime',
'processed_at' => 'immutable_datetime', 'processed_at' => 'immutable_datetime',
+3
View File
@@ -24,6 +24,9 @@ class IntakeObservation extends Model
public const SOURCE_ADOPTION = 'adoption'; public const SOURCE_ADOPTION = 'adoption';
/** A normalised channel event of a portal's interface (Architektur V2, App\Channels\Events). */
public const SOURCE_API = 'api';
/** /**
* Get the attributes that should be cast. * Get the attributes that should be cast.
* *
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A stored report of the process tester: scenario, configuration (also unsaved), inputs, the report of the isolated
* run. Contains only synthetic case data; deleted after the retention period (decision O3).
*/
#[Fillable(['tenant_id', 'channel_id', 'user_id', 'intake', 'scenario', 'configuration', 'inputs', 'steps', 'report', 'outcome', 'release'])]
class ProcessTestRun extends Model
{
use BelongsToTenant;
public const COMPLETED = 'completed';
public const ABORTED = 'aborted';
protected function casts(): array
{
return [
'configuration' => 'array',
'inputs' => 'array',
'report' => 'array',
];
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
}
+2 -1
View File
@@ -28,7 +28,7 @@
'channel_stale_after_minutes', 'channel_task_reminder_after_minutes', 'channel_stale_after_minutes', 'channel_task_reminder_after_minutes',
'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections', 'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections',
'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on', 'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on',
'process_defaults', 'document_releases', 'process_defaults', 'document_releases', 'communication_rules',
])] ])]
class Tenant extends Model class Tenant extends Model
{ {
@@ -77,6 +77,7 @@ protected function casts(): array
'digest_sections' => 'array', 'digest_sections' => 'array',
'process_defaults' => 'array', 'process_defaults' => 'array',
'document_releases' => 'array', 'document_releases' => 'array',
'communication_rules' => 'array',
'digest_when_empty' => 'boolean', 'digest_when_empty' => 'boolean',
'digest_daily_sent_on' => 'immutable_date', 'digest_daily_sent_on' => 'immutable_date',
'digest_weekly_sent_on' => 'immutable_date', 'digest_weekly_sent_on' => 'immutable_date',
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Pricing;
use App\Models\Booking;
use App\Process\CaseContext;
use App\Process\Modules\ContributesToPrice;
use App\Process\ProcessCatalogue;
/**
* The price of a case before it is fixed (extension point BeforePriceFixing, docs/Prozessarchitektur/Architektur/02
* §6.4): PriceCalculator unchanged, plus the lines of the modules of the case's plan that contribute to the price.
* Without contributing modules the result is exactly PriceCalculator's. Never adds anything to a binding case – its
* price is fixed (rule R5). Pure: reads, never writes (also used for previews).
*/
final class CasePricing
{
public function __construct(private PriceCalculator $calculator, private ProcessCatalogue $catalogue) {}
public function quote(Booking $booking, StayRequest $stay): PriceQuote
{
$quote = $this->calculator->calculate($booking->property, $stay);
if ($booking->isBinding() || ! $booking->exists) {
return $quote;
}
$context = CaseContext::of($booking);
foreach ($context->plan->moduleKeys() as $key) {
if (! $this->catalogue->hasModule($key) || ! $context->plan->enabled($key)) {
continue;
}
$module = $this->catalogue->module($key);
if (! $module instanceof ContributesToPrice || ! $module->applies($context)) {
continue;
}
foreach ($module->priceLines($context, $quote) as $line) {
$quote = $quote->withLine($line);
}
}
return $quote;
}
}
+2
View File
@@ -28,6 +28,8 @@ final class ActivityDetails
'binding' => ['status', 'portal_signal'], 'binding' => ['status', 'portal_signal'],
'price' => ['price', 'amount'], 'price' => ['price', 'amount'],
'documents' => ['document', 'mail'], 'documents' => ['document', 'mail'],
'booking_notice' => ['booking_notice', 'mail'],
'portal_confirmation' => ['portal_confirmation', 'evidence', 'task', 'mail'],
'arrival_info' => ['document', 'mail'], 'arrival_info' => ['document', 'mail'],
'review' => ['mail'], 'review' => ['mail'],
'payment' => ['payment', 'amount'], 'payment' => ['payment', 'amount'],
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Process;
/**
* What one automatic advance of a case did: the steps that ran, and per step that was due but held back the reasons
* (shown to the landlord as tasks and notes, as before).
*/
final class AdvanceResult
{
/** @var list<string> */
public array $ran = [];
/** @var array<string, list<string>> module key => reasons */
public array $held = [];
public function ran(string $module): bool
{
return in_array($module, $this->ran, true);
}
/**
* Reasons of one step, or of all steps that were held back.
*
* @return list<string>
*/
public function reasons(?string $module = null): array
{
if ($module !== null) {
return $this->held[$module] ?? [];
}
return array_values(array_unique(array_merge(...array_values($this->held ?: [[]]))));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Process;
/**
* One capability of a channel with the value in force and where it comes from (docs/Prozessarchitektur/V2.1/02 §3.1).
*/
final readonly class Capability
{
public const CONFIRMED = 'confirmed';
public const DERIVED = 'derived';
public const SUGGESTED = 'suggested';
public const UNKNOWN = 'unknown';
public function __construct(
public string $key,
public ?bool $value,
public string $source,
public ?string $note = null,
public ?string $confirmedAt = null,
public ?string $confirmedBy = null,
) {}
public function isKnown(): bool
{
return $this->value !== null;
}
public function sourceLabel(): string
{
return match ($this->source) {
self::CONFIRMED => 'bestätigt'.($this->confirmedBy ? ' von '.$this->confirmedBy : '').($this->confirmedAt ? ' am '.substr($this->confirmedAt, 8, 2).'.'.substr($this->confirmedAt, 5, 2).'.'.substr($this->confirmedAt, 0, 4) : ''),
self::DERIVED => 'abgeleitet aus Ihrer bisherigen Einstellung'.($this->note ? ' („'.$this->note.'“)' : '').' – bitte bestätigen oder korrigieren',
self::SUGGESTED => 'Vorschlag des Kanalprofils – bitte bestätigen',
default => 'noch nicht bekannt – bitte bestätigen',
};
}
}
+3 -365
View File
@@ -3,26 +3,9 @@
namespace App\Process; namespace App\Process;
use App\Actions\EndInternalCase; use App\Actions\EndInternalCase;
use App\Actions\PrepareStays;
use App\Actions\SendBookingDocuments;
use App\Availability\AvailabilityChecker;
use App\Enums\ActivityState;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeStatus;
use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\ChannelTask;
use App\Models\DataRequest;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
/** /**
@@ -39,341 +22,13 @@ class CaseActivities
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation']; private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation'];
/** /**
* The activities of the case in the order of its frozen process plan (ProcessRunner, Architektur V2).
*
* @return list<Activity> * @return list<Activity>
*/ */
public static function for(Booking $booking): array public static function for(Booking $booking): array
{ {
$booking->loadMissing(['guest', 'property', 'payments']); return app(ProcessRunner::class)->activities($booking);
$profile = $booking->process();
$closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
$binding = $booking->isBinding();
$inquiry = $booking->intake !== IntakeKind::Booking;
$today = CarbonImmutable::today();
// After the end of a case (or of its stay) what was not done before is no longer to do; open money and other
// follow-ups are tasks and the commercial closing of their own (package 9).
// A stay whose departure has passed counts as over for the steps before it, too.
$over = $closed || $booking->status === BookingStatus::Completed || ($binding && $booking->departure->isBefore($today));
$later = fn (ActivityState $state): ActivityState => $over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
$activities = [];
if ($booking->isInternal()) {
return self::internal($booking, $closed, $later);
}
$activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel());
$needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
if ($needsContact) {
$hasEmail = filled($booking->guest?->email);
// v0.11 (G2a): before the own binding offer – or the binding confirmation of a wish – every required detail.
$action = $profile->preReservation() || $booking->offer_version > 0 ? CaseRequirements::OFFER : CaseRequirements::WISH_CONFIRMATION;
$needsDetails = $inquiry && ! $binding && $booking->offer_version === 0 && ($action === CaseRequirements::OFFER || $booking->wish_at !== null);
$missing = $hasEmail && $needsDetails ? CaseRequirements::missing($booking, $action) : [];
$request = $booking->openDataRequest();
$asked = $booking->contact_requested_at !== null || $request?->status === DataRequest::OPEN;
$state = match (true) {
$hasEmail && $missing === [] => ActivityState::Done,
$asked => ActivityState::Waiting,
default => ActivityState::Open,
};
$title = match (true) {
$booking->guest === null => 'Name und Kontaktdaten des Gastes eintragen',
! $hasEmail => 'E-Mail-Adresse des Gastes eintragen',
$missing !== [] => $action === CaseRequirements::OFFER ? 'Angaben für das Angebot vervollständigen' : 'Angaben für die Bestätigung vervollständigen',
default => 'Kontaktdaten des Gastes',
};
$detail = match (true) {
$state === ActivityState::Done => $booking->guestName(),
$missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($request !== null ? ' · '.$request->statusLabel() : ($asked ? ' · beim Gast angefragt' : '')),
$booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'),
default => 'fehlt noch',
};
// A prepared data request waits for the landlord's release: that is the next step, otherwise entering the details.
$draft = $needsDetails && $request?->status === DataRequest::DRAFT;
$activities[] = new Activity('contact', $title, $later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact'));
}
if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) {
// Package 7: a request without a hold is answered with an information "unter Vorbehalt"; the guest asks for the booking.
$informed = $booking->information_version > 0 || $binding;
$activities[] = new Activity('information', $booking->processingMode() === ProcessingMode::Automatic ? 'Unverbindliche Auskunft senden (automatisch)' : 'Unverbindliche Auskunft prüfen und senden', $later(match (true) {
$booking->information_version > 0 => ActivityState::Done,
$binding => ActivityState::NotApplicable,
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
default => ActivityState::Later,
}), $booking->information_version > 0 ? 'Version '.$booking->information_version.' vom '.$booking->information_sent_at?->format('d.m.Y').' · ohne Reservierung' : 'der Zeitraum wird nicht reserviert', $informed ? null : 'sendInformation');
$activities[] = new Activity('wish', 'Gast fragt die Buchung an', $later(match (true) {
$booking->wish_at !== null => ActivityState::Done,
$binding => ActivityState::NotApplicable,
$booking->information_version > 0 && $booking->information_valid_until?->isFuture() => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->wish_at !== null => 'angefragt am '.$booking->wish_at->format('d.m.Y, H:i').' Uhr',
$booking->information_version > 0 => 'möglich bis '.$booking->information_valid_until?->format('d.m.Y, H:i').' Uhr',
default => null,
});
$activities[] = new Activity('wish_check', 'Erneut prüfen und verbindlich bestätigen', $later(match (true) {
$binding => ActivityState::Done,
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->accepted_at !== null && ($booking->acceptance['via'] ?? null) === 'booking_wish' => 'bestätigt am '.$booking->confirmed_at?->format('d.m.Y').' ('.($booking->acceptance['confirmed_by'] ?? '').')',
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => 'siehe Aufgabe „Buchungswunsch bestätigen?“',
$binding => 'direkt verbindlich bestätigt (ohne Buchungswunsch)',
default => $booking->processingMode() === ProcessingMode::Automatic ? 'automatisch, wenn alles passt' : 'durch Sie',
});
} elseif ($inquiry) {
$offerDone = $booking->offer_version > 0 || $binding;
// G2a (v0.11): without every required detail there is no offer – the step waits for the guest's answer
// (mail, link or the landlord's entry) instead of being offered as the next step.
$offerMissing = $offerDone ? [] : CaseRequirements::missing($booking, CaseRequirements::OFFER);
$activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) {
$offerDone => ActivityState::Done,
$offerMissing !== [] => ActivityState::Later,
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
default => ActivityState::Later,
}), match (true) {
$booking->offer_version > 0 => 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y'),
$offerMissing !== [] => 'erst wenn alle Angaben da sind',
$booking->hold_expires_at !== null => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr',
default => null,
}, $offerDone || $offerMissing !== [] ? null : 'sendOffer');
$activities[] = new Activity('acceptance', 'Gast nimmt das Angebot an', $later(match (true) {
$binding => ActivityState::Done,
$booking->status === BookingStatus::OfferSent => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->accepted_at !== null => 'angenommen am '.$booking->accepted_at->format('d.m.Y'),
$binding => 'direkt bestätigt',
$booking->status === BookingStatus::OfferSent => 'Angebot gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr',
default => null,
});
} else {
$activities[] = new Activity('binding', 'Beim Portal fest gebucht', $binding || $closed ? ActivityState::External : ActivityState::Open, $booking->portal_reference ? 'Buchungsnummer '.$booking->portal_reference : null, $binding ? null : 'confirm');
$activities[] = new Activity('price', 'Gesamtpreis laut Portal eintragen', $later($booking->total === null ? ActivityState::Open : ActivityState::Done), $booking->total === null ? 'noch nicht bekannt' : Money::format($booking->total), $booking->total === null ? 'portalPrice' : null);
}
if ($profile->documents() === Responsibility::Portal) {
$activities[] = new Activity('documents', 'Buchungsunterlagen an den Gast', ActivityState::External);
} else {
$state = match (true) {
$booking->confirmation_sent_at !== null => ActivityState::Done,
! $binding => ActivityState::Later,
$booking->confirmation_failed_at !== null => ActivityState::Problem,
default => ActivityState::Open,
};
$missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : [];
// What the landlord still has to confirm (unreleased texts, terms not shown to be agreed on the portal).
$toConfirm = $binding && $state === ActivityState::Open && $missing === [] ? app(SendBookingDocuments::class)->compose($booking)->toConfirm() : [];
$activities[] = new Activity('documents', match (true) {
$state !== ActivityState::Open => $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden',
$inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden',
default => 'Buchungsunterlagen prüfen und senden',
}, $later($missing !== [] ? ActivityState::Waiting : $state),
match (true) {
$booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'),
$state === ActivityState::Problem => 'Versand fehlgeschlagen',
$missing !== [] => 'wartet: '.implode(' ', $missing),
$toConfirm !== [] => 'vor dem Versand zu prüfen: '.implode(' ', $toConfirm),
default => null,
}, match (true) {
$state === ActivityState::Problem => 'resendConfirmation',
$binding && $missing === [] && $booking->confirmation_sent_at === null => 'sendDocuments',
default => null,
});
}
foreach (self::channelTasks($booking) as $task) {
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
}
if ($profile->payments() === Responsibility::Portal) {
$portal = $booking->processChannel()?->name ?? 'das Portal';
$viaPortal = $booking->paidViaPortal();
$activities[] = new Activity('payment', 'Zahlung des Gastes an '.$portal, ActivityState::External, match (true) {
$booking->total === null => 'zieht das Portal ein',
$viaPortal > 0 => 'laut Portal bezahlt: '.Money::format($viaPortal).' von '.Money::format($booking->total).' (Angabe des Portals, kein Geld bei uns)',
default => 'zieht das Portal ein; noch keine Zahlungsangabe',
});
$payout = CaseMoney::of($booking)->payout();
$activities[] = new Activity('payout', 'Auszahlung von '.$portal.' auf unser Konto', $later(match (true) {
! $binding => ActivityState::Later,
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) === 0 && $payout['difference'] === 0 => ActivityState::Done,
default => ActivityState::Waiting,
}), trim(($payout['values'] !== [] ? 'angekündigt '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).' · ' : '').'eingegangen '.Money::format($payout['received']).($payout['difference'] > 0 ? ' · Angaben weichen um '.Money::format($payout['difference']).' ab' : '')));
} elseif ($booking->total === null) {
$activities[] = new Activity('payment', 'Zahlungen überwachen', $later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist');
} else {
$paid = $booking->paidAmount();
$activities[] = new Activity('deposit', 'Anzahlung erhalten', $later(match (true) {
$binding && $paid >= (int) $booking->deposit => ActivityState::Done,
$binding => ActivityState::Waiting,
default => ActivityState::Later,
}), Money::format((int) $booking->deposit).($booking->deposit_due_on ? ', fällig '.$booking->deposit_due_on->format('d.m.Y') : ''));
$activities[] = new Activity('balance', 'Restzahlung erhalten', $later(match (true) {
$binding && $paid >= $booking->total => ActivityState::Done,
$binding && $paid >= (int) $booking->deposit => ActivityState::Waiting,
default => ActivityState::Later,
}), Money::format(max(0, $booking->total - (int) $booking->deposit)).($booking->balance_due_on ? ', fällig '.$booking->balance_due_on->format('d.m.Y') : ''));
}
foreach (self::tasks($booking) as $task) {
$activities[] = self::task($task);
}
foreach ($booking->changes()->where('status', ChangeStatus::Proposed)->get() as $change) {
$activities[] = new Activity('change_proposed', 'Änderungsvorschlag liegt beim Gast', ActivityState::Waiting, $change->summary().($change->expires_at ? ' · bis '.$change->expires_at->format('d.m.Y') : ''));
}
$arrived = $binding && $booking->arrival <= $today;
$left = $binding && $booking->departure <= $today;
$missing = PrepareStays::missingArrivalDetails($booking);
$detailsTask = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->exists();
if ($binding && ! $detailsTask) {
$activities[] = new Activity('arrival_details', 'Anreisedaten', $later(match (true) {
$missing === [] => ActivityState::Done,
$left => ActivityState::NotApplicable,
default => ActivityState::Later,
}), $missing === [] ? implode(' · ', array_filter([$booking->guest?->phone ?: $booking->guest?->email, $booking->arrival_time ? 'Anreise '.$booking->arrival_time : null])) : 'es fehlt: '.implode(', ', $missing).' – wird rechtzeitig als Aufgabe gemeldet');
}
$activities[] = $profile->guestMessages() === Responsibility::Portal
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen')
: new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise');
// v0.11: a binding booking (also from a portal) stays binding; missing administrative details are asked for
// alongside, after the steps of the booking itself.
if ($binding && ($bookingRequest = $booking->openDataRequest()) !== null) {
$activities[] = new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $later($bookingRequest->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open),
implode(', ', CaseRequirements::labels($bookingRequest->fields)).' · '.$bookingRequest->statusLabel(), $bookingRequest->status === DataRequest::OPEN ? null : 'approveDataRequest');
}
$activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) {
$left => ActivityState::Done,
$arrived => ActivityState::Waiting,
default => ActivityState::Later,
}), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
if ($profile->guestMessages() === Responsibility::Landlord) {
$activities[] = new Activity('review', 'Bitte um eine Bewertung (automatisch)', $later($booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later));
}
return [...$activities, ...self::closing($booking, $closed)];
}
/**
* The two closings of a case (package 9): the stay, and the money.
*
* @return list<Activity>
*/
private static function closing(Booking $booking, bool $closed): array
{
$today = CarbonImmutable::today();
$completed = $booking->status === BookingStatus::Completed;
$activities = [];
if (! $closed && ($booking->isBinding() || $completed)) {
$blockers = $booking->isBinding() && ! $completed ? CaseClosure::stayBlockers($booking) : collect();
$activities[] = new Activity('closure', $booking->isInternal() && $booking->internal_kind === InternalKind::Block ? 'Sperrzeit abschließen' : 'Aufenthalt abschließen', match (true) {
$completed => ActivityState::Done,
! $booking->isBinding() || $booking->departure > $today => ActivityState::Later,
default => ActivityState::Waiting,
}, match (true) {
$completed => 'abgeschlossen am '.($booking->completed_at ?? $booking->updated_at)?->format('d.m.Y'),
$blockers->isNotEmpty() => 'wartet auf: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', '),
$booking->isBinding() && $booking->departure <= $today => 'geschieht automatisch über Nacht – oder jetzt von Hand',
default => 'nach der Abreise, sobald nichts mehr für den Aufenthalt offen ist',
}, $booking->isBinding() && ! $completed && $booking->departure <= $today ? 'closeStay' : null);
}
$settlementApplies = $completed || $booking->status === BookingStatus::Cancelled;
if ($settlementApplies || ($booking->isBinding() && ! $booking->isInternal()) || ($booking->isInternal() && (int) $booking->total > 0)) {
$points = $settlementApplies && $booking->settled_at === null ? CaseClosure::commercialPoints($booking) : [];
$activities[] = new Activity('settlement', 'Kaufmännisch abschließen', match (true) {
$booking->settled_at !== null => ActivityState::Done,
! $settlementApplies => ActivityState::Later,
default => ActivityState::Waiting,
}, match (true) {
$booking->settled_at !== null => 'abgeschlossen am '.$booking->settled_at->format('d.m.Y').($booking->settled_by && $booking->settled_by !== CaseClosure::AUTOMATIC ? ' von '.$booking->settled_by : '').($booking->settled_note ? ' · '.$booking->settled_note : ''),
! $settlementApplies => 'nach dem Aufenthalt, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind',
default => 'offen: '.implode(' ', $points),
}, $settlementApplies && $booking->settled_at === null && $points !== [] ? 'settle' : null);
}
return $activities;
}
/**
* The tasks shown on the case: every open one, and the done ones of the stay (services, issues, follow-ups) as its record.
*
* @return iterable<BookingTask>
*/
private static function tasks(Booking $booking): iterable
{
return BookingTask::query()->where('booking_id', $booking->id)
->where(fn ($query) => $query->where('status', BookingTaskStatus::Open)
->orWhere(fn ($done) => $done->where('status', BookingTaskStatus::Done)->whereIn('kind', [BookingTaskKind::Service, BookingTaskKind::Issue, BookingTaskKind::FollowUp, BookingTaskKind::PayoutCheck, BookingTaskKind::OpenClaim])))
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get();
}
/**
* Own use, private stay or block (A6): only what such a case has – no contract, no reminders, no reviews.
*
* @param callable(ActivityState): ActivityState $later
* @return list<Activity>
*/
private static function internal(Booking $booking, bool $closed, callable $later): array
{
$kind = $booking->internal_kind;
$activities = [new Activity('intake', ($kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
foreach (self::channelTasks($booking) as $task) {
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
}
if ($kind !== InternalKind::Block && filled($booking->guest?->email)) {
$activities[] = new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $later($booking->confirmation_sent_at !== null ? ActivityState::Done : ActivityState::Later),
$booking->confirmation_sent_at ? 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : 'nur bei Bedarf', $booking->confirmation_sent_at === null && ! $closed ? 'sendDocuments' : null);
}
if ($booking->total !== null && $booking->total > 0) {
$paid = $booking->paidAmount();
$activities[] = new Activity('payment', 'Zahlung (ohne Erinnerungen)', $later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt');
}
foreach (self::tasks($booking) as $task) {
$activities[] = self::task($task);
}
$activities[] = new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $closed ? ActivityState::NotApplicable : ($booking->departure <= CarbonImmutable::today() ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
return [...$activities, ...self::closing($booking, $closed)];
}
/**
* An open task of the case and the action that settles it.
*/
private static function task(BookingTask $task): Activity
{
$action = match ($task->kind) {
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
BookingTaskKind::PortalChangeReported => 'change',
BookingTaskKind::BookingWish => 'decideWish',
BookingTaskKind::ArrivalDetails => 'arrivalDetails',
BookingTaskKind::CancellationRequest => 'end',
BookingTaskKind::FactConflict => 'provideContact',
default => $task->kind->isPayment() ? null : 'completeTask',
};
$today = CarbonImmutable::today();
$state = match (true) {
$task->status === BookingTaskStatus::Done => ActivityState::Done,
$task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting,
$task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later,
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem,
// v0.11 (B3): the binding confirmation waits for the missing details as well.
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && CaseRequirements::missing($task->booking, CaseRequirements::WISH_CONFIRMATION) !== [] => ActivityState::Waiting,
default => ActivityState::Open,
};
$detail = $task->status === BookingTaskStatus::Done
? 'erledigt am '.$task->completed_at?->format('d.m.Y').($task->completed_by ? ' von '.$task->completed_by : '').($task->note ? ' · '.$task->note : '')
: trim(($state === ActivityState::Problem ? 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. · ' : '').($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->responsible ? ' · zuständig: '.$task->responsible : '').($task->note ? ' · '.$task->note : ''), ' ·');
return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action);
} }
/** /**
@@ -439,21 +94,4 @@ public static function situation(Booking $booking): string
return implode(' · ', array_filter([$kind, $state, $when])); return implode(' · ', array_filter([$kind, $state, $when]));
} }
/**
* Portal tasks for the dates of this case (block when it starts occupying, unblock when it ends).
*
* @return iterable<ChannelTask>
*/
private static function channelTasks(Booking $booking): iterable
{
return ChannelTask::query()
->with('channel')
->whereHas('channel', fn ($query) => $query->where('property_id', $booking->property_id))
->whereDate('starts_on', $booking->arrival)
->whereDate('ends_on', $booking->departure)
->where('status', '!=', ChannelTaskStatus::Dismissed)
->orderBy('id')
->get();
}
} }
+6 -43
View File
@@ -2,61 +2,24 @@
namespace App\Process; namespace App\Process;
use App\Actions\AutoOffer;
use App\Actions\SendBookingDocuments;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Models\Booking; use App\Models\Booking;
use Throwable;
/** /**
* Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do * Facade of the process core (ProcessRunner, trigger 'automation') for the places that carry a case on after new
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a binding booking * facts, portal amounts or the landlord's "continue automatically": only what the landlord would do next anyway and
* once their composition is complete and needs no confirmation (template released and, for portal bookings, confirmed * only when the case is handled automatically – the offer or information of a request, the documents of a binding
* as the portal's terms). Whatever stops it is returned in plain * booking (never for cases taken over from the old data). Whatever stops it is returned in plain words.
* words; the case then shows it as a task. Never touches a case whose profile was taken over from the old data (the
* automation did not exist for those cases before).
*/ */
class CaseAutomation class CaseAutomation
{ {
public function __construct(private AutoOffer $autoOffer, private SendBookingDocuments $documents) {} public function __construct(private ProcessRunner $runner) {}
/** /**
* @return list<string> what keeps the case from going on automatically (empty: nothing to do or done) * @return list<string> what keeps the case from going on automatically (empty: nothing to do or done)
*/ */
public function advance(Booking $booking): array public function advance(Booking $booking): array
{ {
$booking->loadMissing(['guest', 'property']); return $this->runner->advance($booking, ProcessRunner::AUTOMATION)->reasons();
if ($booking->processingMode() !== ProcessingMode::Automatic) {
return [];
}
try {
return CaseLog::context(fn (): array => $this->step($booking), actor: CaseLog::SYSTEM.' (automatisch)');
} catch (Throwable $exception) {
report($exception);
return ['Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.'];
}
}
/**
* @return list<string>
*/
private function step(Booking $booking): array
{
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0 && $booking->intake !== IntakeKind::Booking) {
return $this->autoOffer->handle($booking);
}
if ($booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord && $booking->process()->origin !== 'migration') {
return $this->documents->automatically($booking);
}
return [];
} }
/** /**
+31 -1
View File
@@ -3,8 +3,10 @@
namespace App\Process; namespace App\Process;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility; use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask; use App\Models\BookingTask;
use App\Pricing\CaseMoney; use App\Pricing\CaseMoney;
@@ -21,6 +23,16 @@
*/ */
final class CaseClosure final class CaseClosure
{ {
/** Kinds of financial clarification that allow settling an open portal payout (decision O5). */
public const PAYOUT_CLARIFICATIONS = [
'offset' => 'Verrechnung dokumentiert',
'difference_booked' => 'Differenz geklärt und verbucht',
'written_off' => 'Forderung ausgebucht',
self::CLAIM_OPEN => 'Als offene Forderung weiterführen',
];
public const CLAIM_OPEN = 'open_claim';
public const AUTOMATIC = 'automatisch'; public const AUTOMATIC = 'automatisch';
/** /**
@@ -92,8 +104,26 @@ public static function refresh(Booking $booking): void
* The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial * The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial
* tasks are closed with the same note. The reason is required and kept. * tasks are closed with the same note. The reason is required and kept.
*/ */
public static function settle(Booking $booking, string $note, string $by): void public static function settle(Booking $booking, string $note, string $by, ?string $clarification = null): void
{ {
// Decision O5: with portal collection, an open or deviating payout is settled only after its financial
// clarification – a reason alone is not enough, and a portal's report of a payout is no proof of the receipt.
$payoutPoints = $booking->status !== BookingStatus::Cancelled && CaseMoney::of($booking)->collector() === Responsibility::Portal
? self::portalMoney($booking, CaseMoney::of($booking)) : [];
if ($payoutPoints !== [] && ! array_key_exists((string) $clarification, self::PAYOUT_CLARIFICATIONS)) {
throw new ReservationException('Bei Inkasso durch das Portal ist der kaufmännische Abschluss erst nach finanzieller Klärung möglich: Auszahlung eingegangen, Verrechnung, verbuchte Differenz oder ausgebuchte Forderung. Offen: '.implode(' ', $payoutPoints));
}
if ($clarification === self::CLAIM_OPEN) {
// The claim stays traceable: an open task of its own, the case stays commercially open.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::OpenClaim, 'status' => BookingTaskStatus::Open], ['tenant_id' => $booking->tenant_id, 'due_on' => today()->addDays(14), 'note' => mb_substr($note, 0, 1000)]);
CaseLog::record($booking, 'settled', 'Als offene Forderung weitergeführt', reason: $note, data: ['open_points' => $payoutPoints, 'clarification' => $clarification], actor: $by);
return;
}
if ($clarification !== null && isset(self::PAYOUT_CLARIFICATIONS[$clarification])) {
$note = self::PAYOUT_CLARIFICATIONS[$clarification].': '.$note;
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) { foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
if ($task->kind->isCommercial()) { if ($task->kind->isCommercial()) {
$task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note); $task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note);
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Process;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Models\Booking;
use Carbon\CarbonImmutable;
/**
* Everything a process module reads about one case at one moment: the case, its frozen profile and plan, the
* parameters of the module and the time. Built fresh for every evaluation – modules keep no state of their own; the
* state of a case stays in its data (bookings, case_facts, booking_tasks, data_requests, booking_events).
*/
final class CaseContext
{
public readonly ProcessProfile $profile;
public readonly bool $closed;
public readonly bool $binding;
public readonly bool $inquiry;
public readonly CarbonImmutable $today;
/** After the end of the case or of its stay: what was not done before is no longer to do. */
public readonly bool $over;
public function __construct(public readonly Booking $booking, public readonly ProcessPlan $plan)
{
$booking->loadMissing(['guest', 'property', 'payments']);
$this->profile = $booking->process();
$this->closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
$this->binding = $booking->isBinding();
$this->inquiry = $booking->intake !== IntakeKind::Booking;
$this->today = CarbonImmutable::today();
$this->over = $this->closed || $booking->status === BookingStatus::Completed || ($this->binding && $booking->departure->isBefore($this->today));
}
public static function of(Booking $booking): self
{
return new self($booking, ProcessPlan::of($booking));
}
/**
* The central rule of the case's end (package 9): after it, an open step is no longer to do – unless it is done
* (by us or externally). Modules apply it where the step belongs to the case's own course.
*/
public function later(ActivityState $state): ActivityState
{
return $this->over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
}
/**
* A parameter of a module as frozen in the plan (null when the plan does not set it).
*/
public function parameter(string $module, string $name): mixed
{
return $this->plan->parameter($module, $name);
}
}
+26 -1
View File
@@ -4,9 +4,12 @@
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Models\Booking; use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest; use App\Models\Guest;
use App\Models\Property;
use App\Models\Tenant; use App\Models\Tenant;
use App\Support\Settings; use App\Support\Settings;
use DomainException;
/** /**
* Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake * Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake
@@ -30,10 +33,32 @@ public static function freeze(Booking $booking): void
$booking->intake ??= ProcessSettings::intakeFor($booking); $booking->intake ??= ProcessSettings::intakeFor($booking);
$profile = app(ProcessSettings::class)->forBooking($booking)->withOrigin($booking->exists ? 'changed' : 'intake'); $profile = app(ProcessSettings::class)->forBooking($booking)->withOrigin($booking->exists ? 'changed' : 'intake');
$booking->profile = $profile->toArray(); // Architektur V2: the process plan (model, variant, module versions, step settings) is frozen with the profile.
try {
$plan = ProcessPlan::freeze($profile, ProcessPlan::configurationOf(self::configurationChannel($booking), $profile->intake));
} catch (DomainException $exception) {
// Never lose an incoming case over its configuration (e.g. a tester-only variant): it follows the derived plan.
report($exception);
$plan = ProcessPlan::derive($profile);
}
$booking->profile = [...$profile->toArray(), 'plan' => $plan->toArray()];
$booking->case_type = $profile->caseType; $booking->case_type = $profile->caseType;
} }
/**
* The channel whose configuration (Kanal › Ablauf) applies to the case: its portal, or the own website's entry.
*/
private static function configurationChannel(Booking $booking): ?Channel
{
$channel = $booking->processChannel();
if ($channel === null && $booking->source === 'website' && $booking->property_id !== null) {
$property = $booking->property ?? Property::withoutGlobalScope('tenant')->find($booking->property_id);
$channel = $property === null ? null : Channel::existingWebsiteOf($property);
}
return $channel;
}
public static function created(Booking $booking): void public static function created(Booking $booking): void
{ {
CaseLog::record($booking, 'created', 'Vorgang angelegt: '.$booking->caseType()->getLabel().' ('.$booking->bookingChannelLabel().')', data: [ CaseLog::record($booking, 'created', 'Vorgang angelegt: '.$booking->caseType()->getLabel().' ('.$booking->bookingChannelLabel().')', data: [
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace App\Process;
use App\Models\Channel;
/**
* What a portal actually does for the landlord's account (K00 „Kanal-Fähigkeit“, docs/Prozessarchitektur/V2.1/02 §3). The
* admissible process models follow from it; the profile of the portal only suggests values. The value in force is, in
* this order: confirmed by an administrator · derived from an explicitly stored setting of the channel · suggested by the
* channel profile · unknown (blocks nothing, is shown as „please confirm“).
*/
final class ChannelCapabilities
{
public const COLLECTS_PAYMENT = 'collects_payment';
public const PROVIDES_CONTRACT_DOCUMENTS = 'provides_contract_documents';
public const MESSAGES_GUEST = 'messages_guest';
public const SENDS_CONFIRMATION_MAIL = 'sends_confirmation_mail';
/** Older stored settings that imply a capability: capability => [setting, value that means yes, value that means no]. */
private const LEGACY = [
self::COLLECTS_PAYMENT => ['payments', 'portal', 'landlord'],
self::PROVIDES_CONTRACT_DOCUMENTS => ['documents', 'portal', 'landlord'],
self::MESSAGES_GUEST => ['guest_messages', 'portal', 'landlord'],
];
/**
* @return array<string, array{label: string, question: string}>
*/
public static function definitions(): array
{
return [
self::COLLECTS_PAYMENT => ['label' => 'Inkasso', 'question' => 'Zieht das Portal das Geld des Gastes ein?'],
self::PROVIDES_CONTRACT_DOCUMENTS => ['label' => 'Vertragsunterlagen', 'question' => 'Stellt das Portal dem Gast die verbindlichen Vertragsunterlagen bereit?'],
self::MESSAGES_GUEST => ['label' => 'Gastkommunikation', 'question' => 'Schreibt das Portal den Gast an (Anreise-Information, Erinnerungen)?'],
self::SENDS_CONFIRMATION_MAIL => ['label' => 'Bestätigungsmail', 'question' => 'Schickt das Portal Ihnen eine Buchungsbestätigung per E-Mail?'],
];
}
/**
* The capabilities of a channel; a draft (key => bool|null) overrides what is stored, to show what a change would do.
*
* @param array<string, bool|null>|null $draft
* @return array<string, Capability>
*/
public function resolve(Channel $channel, ?array $draft = null): array
{
$stored = (array) (($channel->settings ?? [])['capabilities'] ?? []);
$legacy = (array) (($channel->process_overrides ?? [])['booking'] ?? []);
$suggested = (array) (config('channels.portal_profiles.'.app(ChannelProcessConfiguration::class)->profileKey($channel).'.capabilities') ?? []);
$result = [];
foreach (array_keys(self::definitions()) as $key) {
if ($draft !== null && array_key_exists($key, $draft) && $draft[$key] !== null && $draft[$key] !== '') {
// A value the landlord only left as shown keeps its origin; a changed one is a pending confirmation.
$value = filter_var($draft[$key], FILTER_VALIDATE_BOOLEAN);
$base = $this->resolve($channel)[$key];
if ($base->value !== $value) {
$result[$key] = new Capability($key, $value, Capability::CONFIRMED, null, now()->toIso8601String(), auth()->user()?->name);
continue;
}
}
if (isset($stored[$key]['value'])) {
$result[$key] = new Capability($key, (bool) $stored[$key]['value'], Capability::CONFIRMED, null, $stored[$key]['at'] ?? null, $stored[$key]['by'] ?? null);
continue;
}
if (isset(self::LEGACY[$key]) && filled($legacy[self::LEGACY[$key][0]] ?? null)) {
[$setting, $yes, $no] = self::LEGACY[$key];
$value = (string) $legacy[$setting];
if (in_array($value, [$yes, $no], true)) {
$result[$key] = new Capability($key, $value === $yes, Capability::DERIVED, $value === $yes ? 'Portal' : 'wir');
continue;
}
}
$result[$key] = array_key_exists($key, $suggested) && $suggested[$key] !== null
? new Capability($key, (bool) $suggested[$key], Capability::SUGGESTED)
: new Capability($key, null, Capability::UNKNOWN);
}
return $result;
}
public function value(Channel $channel, string $key): ?bool
{
return $this->resolve($channel)[$key]->value;
}
/**
* What is stored to confirm the capabilities of a draft, and the readable list of what changed.
*
* @param array<string, bool|string|null> $draft
* @return array{capabilities: array<string, array{value: bool, at: string, by: ?string}>, changes: list<string>}
*/
public function confirm(Channel $channel, array $draft, ?string $by): array
{
$stored = (array) (($channel->settings ?? [])['capabilities'] ?? []);
$changes = [];
foreach (self::definitions() as $key => $definition) {
if (! array_key_exists($key, $draft) || $draft[$key] === null || $draft[$key] === '') {
continue;
}
$value = filter_var($draft[$key], FILTER_VALIDATE_BOOLEAN);
if (isset($stored[$key]['value']) && (bool) $stored[$key]['value'] === $value) {
continue;
}
$changes[] = $definition['label'].': '.(isset($stored[$key]['value']) ? ($stored[$key]['value'] ? 'ja' : 'nein').' → ' : '').($value ? 'ja' : 'nein');
$stored[$key] = ['value' => $value, 'at' => now()->toIso8601String(), 'by' => $by];
}
return ['capabilities' => $stored, 'changes' => $changes];
}
}
+535
View File
@@ -0,0 +1,535 @@
<?php
namespace App\Process;
use App\Enums\BookingNoticeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\ContractDelivery;
use App\Enums\DataRequestMode;
use App\Enums\InquiryAnswer;
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;
use App\Process\Templates\FunctionTemplate;
use App\Process\Templates\TemplateComposer;
/**
* 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::PreReservation, ProcessSetting::HoldHours, ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes]],
'offer.binding' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::HoldHours, ProcessSetting::ContractTemplate]],
'offer.information' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::GuestLinkValidDays]],
'documents.send' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::ContractDelivery, ProcessSetting::ContractTemplate]],
'documents.booking_notice' => ['parameters' => [ProcessSetting::BookingNotice]],
'portal.confirmation' => ['parameters' => [ProcessSetting::AwaitPortalConfirmation, ProcessSetting::PortalConfirmationWaitHours]],
'arrival.info' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::ArrivalInfoSender], 'parameters' => [ProcessSetting::ArrivalInfoDaysBefore]],
'review.request' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::ReviewRequestSender]],
];
public function __construct(private ProcessCatalogue $catalogue, private TemplateComposer $composer) {}
/**
* 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';
}
/**
* Every model of the intake kind with whether this channel fits it and – if not – why and what to do (decision
* E2/O2 and V2.1 §3.2: the capabilities of the channel decide, not a fixed list of portals).
*
* @param array<string, bool|string|null>|null $capabilityDraft unsaved capability values of the configurator
* @return array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}>
*/
public function modelOptions(Channel $channel, IntakeKind $intake, ?array $capabilityDraft = null): array
{
$capabilities = app(ChannelCapabilities::class)->resolve($channel, $capabilityDraft);
$options = [];
foreach ($this->catalogue->admissible($intake) as $key => $model) {
// The archetypes of the other way (website: A1, portal: A2) are not offered; the base process fits both.
if (($channel->isWebsite() && str_starts_with($key, 'a2.')) || (! $channel->isWebsite() && str_starts_with($key, 'a1.'))) {
continue;
}
$restrictions = [];
$hints = [];
foreach ($model::capabilityRequirements() as $capability => $required) {
$actual = $capabilities[$capability] ?? null;
$definition = ChannelCapabilities::definitions()[$capability];
if ($actual === null || ! $actual->isKnown()) {
$hints[] = $definition['label'].' ist noch nicht bekannt – bitte bestätigen.';
continue;
}
if ($actual->value !== $required) {
$fits = collect($this->catalogue->admissible($intake))->first(fn (ProcessModel $other): bool => $other::key() !== $key && collect($other::capabilityRequirements())->every(fn (bool $value, string $name): bool => ($capabilities[$name] ?? null)?->value === $value));
$restrictions[] = new Restriction(
Restriction::CAPABILITY,
$model::label().' setzt voraus: „'.$definition['question'].'“ – '.($required ? 'ja' : 'nein').'. Für diesen Kanal gilt aber '.($actual->value ? 'ja' : 'nein').' ('.$actual->sourceLabel().').',
$fits ? $fits::label() : null,
'Wenn das nicht stimmt: oben bei „Was kann dieses Portal?“ „'.$definition['label'].'“ auf '.($required ? 'ja' : 'nein').' stellen und bestätigen.',
);
}
}
$options[$key] = ['model' => $model, 'admissible' => $restrictions === [], 'restrictions' => $restrictions, 'hints' => $hints];
}
return $options;
}
/**
* The models the landlord may choose now.
*
* @param array<string, bool|string|null>|null $capabilityDraft
* @return array<string, ProcessModel>
*/
public function admissibleModels(Channel $channel, IntakeKind $intake, ?array $capabilityDraft = null): array
{
return array_map(fn (array $option): ProcessModel => $option['model'], array_filter($this->modelOptions($channel, $intake, $capabilityDraft), fn (array $option): bool => $option['admissible']));
}
/**
* Every function template of each slot of the model with whether this channel fits it and – if not – why. The
* portal's confirmed capabilities decide; an unknown capability is never taken as proven (shown as "please confirm").
*
* @param array<string, bool|string|null>|null $capabilityDraft
* @return array<string, array<string, array{template: class-string<FunctionTemplate>, admissible: bool, restrictions: list<Restriction>, hints: list<string>, unconfirmed: list<string>}>> area value => template key => option
*/
public function templateOptions(Channel $channel, ProcessModel $model, ?array $capabilityDraft = null): array
{
$capabilities = app(ChannelCapabilities::class)->resolve($channel, $capabilityDraft);
$options = [];
foreach ($model->slots() as $area) {
foreach ($this->catalogue->templates($area) as $key => $class) {
$restrictions = $hints = $unconfirmed = [];
if (isset($model::templateRestrictions()[$key])) {
$restrictions[] = new Restriction(Restriction::BUSINESS, '„'.$class::label().'“ passt nicht zu „'.$model::label().'“: '.$model::templateRestrictions()[$key]);
}
if ($channel->isWebsite() && in_array(true, $class::capabilityRequirements(), true)) {
$restrictions[] = new Restriction(Restriction::BUSINESS, '„'.$class::label().'“ setzt ein Portal voraus; die eigene Webseite hat keines.');
}
foreach ($class::capabilityRequirements() as $capability => $required) {
$actual = $capabilities[$capability] ?? null;
$definition = ChannelCapabilities::definitions()[$capability];
if ($actual === null || ! $actual->isKnown()) {
$hints[] = $definition['label'].' ist noch nicht bekannt – bitte bestätigen.';
$unconfirmed[] = $capability;
continue;
}
if ($actual->source !== Capability::CONFIRMED) {
$unconfirmed[] = $capability;
$hints[] = $definition['label'].' gilt nur als „'.($actual->source === Capability::SUGGESTED ? 'Vorschlag des Kanalprofils' : 'abgeleitet').'“, nicht als bestätigt.';
}
if ($actual->value !== $required) {
$other = collect($this->catalogue->templates($area))->first(fn (string $candidate): bool => $candidate !== $class && collect($candidate::capabilityRequirements())->every(fn (bool $value, string $name): bool => ($capabilities[$name] ?? null)?->value === $value));
$restrictions[] = new Restriction(
Restriction::CAPABILITY,
'„'.$class::label().'“ setzt voraus: „'.$definition['question'].'“ – '.($required ? 'ja' : 'nein').'. Für diesen Kanal gilt aber '.($actual->value ? 'ja' : 'nein').' ('.$actual->sourceLabel().').',
$other ? $other::label() : null,
'Wenn das nicht stimmt: oben bei „Was kann dieses Portal?“ „'.$definition['label'].'“ auf '.($required ? 'ja' : 'nein').' stellen und bestätigen.',
);
}
}
$options[$area->value][$key] = ['template' => $class, 'admissible' => $restrictions === [], 'restrictions' => $restrictions, 'hints' => $hints, 'unconfirmed' => $unconfirmed];
}
}
return $options;
}
/**
* The templates in force for new cases of the channel and intake kind (key@version per area): the saved choice of a
* model with slots, otherwise the combination a legacy archetype reproduces (empty when there is none).
*
* @return array<string, string>
*/
public function currentTemplates(Channel $channel, IntakeKind $intake): array
{
$current = $this->current($channel, $intake);
$model = $this->catalogue->model($current['model']);
if ($model->slots() !== []) {
return $this->composer->resolve($model, $current['templates']);
}
$base = $model::composedBy();
return $base === null || $model::presetTemplates() === [] ? [] : $this->composer->resolve($this->catalogue->model($base), $model::presetTemplates());
}
/**
* The templates a draft uses for the model slots (chosen ones, otherwise the model defaults) as key@version.
*
* @param array<string, mixed> $draft
* @return array<string, string>
*/
public function templatesOf(ProcessModel $model, array $draft): array
{
return $this->composer->resolve($model, (array) ($draft['templates'] ?? []));
}
/**
* Stored settings of the channel that the chosen model fixes differently: saving the model would silently override
* them (they would stay stored but not take effect). They are listed so that the landlord confirms their removal.
*
* @param array<string, string> $templates area => template key chosen in the draft (templates fix responsibilities just like models)
* @return list<array{setting: ProcessSetting, stored: string, fixed: string, text: string}>
*/
public function conflicts(Channel $channel, IntakeKind $intake, string $modelKey, array $templates = []): array
{
if (! $this->catalogue->hasModel($modelKey)) {
return [];
}
$stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []);
$conflicts = [];
$model = $this->catalogue->model($modelKey);
$fixes = $model::fixes();
$fixedBy = array_fill_keys(array_keys($fixes), 'Das Modell „'.$modelKey.'“');
foreach ($this->composer->classes($this->composer->resolve($model, $templates)) as $class) {
foreach ($class::fixes() as $key => $fixed) {
$fixes[$key] = $fixed;
$fixedBy[$key] = 'Die Schablone „'.$class::label().'“';
}
}
foreach ($fixes as $key => $fixed) {
$setting = ProcessSetting::tryFrom($key);
$value = $setting?->normalize($stored[$key] ?? null);
$fixedValue = $setting?->normalize($fixed) ?? $fixed;
if ($setting === null || $value === null || (string) $value === (string) $fixedValue) {
continue;
}
$conflicts[] = ['setting' => $setting, 'stored' => $setting->describe($value), 'fixed' => $setting->describe($fixedValue),
'text' => $setting->question().' Bisher eingestellt: „'.$setting->describe($value).'“. '.$fixedBy[$key].' legt fest: „'.$setting->describe($fixedValue).'“.'];
}
// Stored responsibilities the model does not allow (variable ones, not fixed through fixes()) are just as stale.
$responsibilities = $this->catalogue->model($modelKey)::responsibilities();
foreach (Responsibilities::SETTINGS as $field => $setting) {
$value = $setting->normalize($stored[$setting->value] ?? null);
$responsibility = $value === null ? null : Responsibility::tryFrom((string) $value);
if ($responsibility === null || $responsibilities->admits($setting, $responsibility) || in_array($setting, array_column($conflicts, 'setting'), true)) {
continue;
}
$allowed = collect($responsibilities->allowed($field))->map(fn (Responsibility $allowedValue): string => $setting->describe($allowedValue->value))->implode(' oder ');
$conflicts[] = ['setting' => $setting, 'stored' => $setting->describe($value), 'fixed' => $allowed,
'text' => $setting->question().' Bisher eingestellt: „'.$setting->describe($value).'“. Das Modell „'.$modelKey.'“ erlaubt: „'.$allowed.'“.'];
}
// A model with slots does not narrow the guest communication itself: the portal's capability does.
$messages = $model->slots() === [] ? null : (app(ChannelCapabilities::class)->resolve($channel)[ChannelCapabilities::MESSAGES_GUEST] ?? null);
foreach ($model->slots() === [] ? [] : [ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoSender, ProcessSetting::ReviewRequestSender] as $sender) {
$storedSender = $sender->normalize($stored[$sender->value] ?? null);
if ($messages !== null && $messages->isKnown() && $messages->value === false && $storedSender === Responsibility::Portal->value) {
$conflicts[] = ['setting' => $sender, 'stored' => $sender->describe($storedSender), 'fixed' => $sender->describe(Responsibility::Landlord->value),
'text' => $sender->question().' Bisher eingestellt: „'.$sender->describe($storedSender).'“. Laut Fähigkeit des Portals schreibt es den Gast aber nicht an; künftig: „'.$sender->describe(Responsibility::Landlord->value).'“.'];
}
}
return $conflicts;
}
/**
* The draft without the stored settings the chosen model overrides (see conflicts()): the landlord has to confirm their
* removal when saving, so they are neither validated against the model nor saved again.
*
* @param array<string, mixed> $draft
* @return array<string, mixed>
*/
public function withoutOverriddenSettings(Channel $channel, IntakeKind $intake, array $draft): array
{
$stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []);
foreach ($this->conflicts($channel, $intake, (string) ($draft['model'] ?? ''), (array) ($draft['templates'] ?? [])) as $conflict) {
$key = $conflict['setting']->value;
$value = $draft['settings'][$key] ?? null;
if (array_key_exists($key, (array) ($draft['settings'] ?? [])) && (string) $conflict['setting']->normalize($value) === (string) $conflict['setting']->normalize($stored[$key] ?? null)) {
unset($draft['settings'][$key]);
}
}
return $draft;
}
/**
* The model a new case of this channel and intake would follow now: the chosen one, or the one derived from the
* settings as before (marked as derived).
*
* @return array{model: string, variant: string, derived: bool, templates: array<string, string>}
*/
public function current(Channel $channel, IntakeKind $intake): array
{
$config = ProcessPlan::configurationOf($channel, $intake);
if (filled($config['model'] ?? null) && $this->catalogue->hasModel((string) $config['model'])) {
return ['model' => (string) $config['model'], 'variant' => (string) ($config['variant'] ?? 'standard'), 'derived' => false, 'templates' => (array) ($config['templates'] ?? [])];
}
$property = $channel->property;
$profile = app(ProcessSettings::class)->resolve($property, $channel, $intake);
return ['model' => $this->catalogue->derivedModel($profile), 'variant' => 'standard', 'derived' => true, 'templates' => []];
}
/**
* Allowed values of the performer of a step under the model (variable responsibility), as setting values.
*
* @return array<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();
}
/**
* The fixed choices of a setting that is not free text (null: free input).
*
* @return array<string, string>|null
*/
public function settingOptions(ProcessSetting $setting): ?array
{
return match ($setting) {
ProcessSetting::ContractDelivery => collect(ContractDelivery::cases())->mapWithKeys(fn (ContractDelivery $case): array => [$case->value => $case->getLabel()])->all(),
ProcessSetting::BookingNotice => collect(BookingNoticeMode::cases())->mapWithKeys(fn (BookingNoticeMode $case): array => [$case->value => $case->getLabel()])->all(),
ProcessSetting::AwaitPortalConfirmation => ['1' => 'ja, erst nach der Bestätigungsmail', '0' => 'nein, sofort'],
default => null,
};
}
/**
* Allowed modes of a step (as values of its setting).
*
* @return array<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, template: ?string}>
*/
public function preview(Channel $channel, IntakeKind $intake, array $draft): array
{
$model = $this->catalogue->model((string) ($draft['model'] ?? $this->current($channel, $intake)['model']));
$variant = (string) ($draft['variant'] ?? 'standard');
$profile = $this->profileWith($channel, $intake, $draft);
$templates = $this->templatesOf($model, $draft);
$standard = $model->modules('standard', $templates);
$owners = [];
foreach ($this->composer->classes($templates) as $class) {
foreach ($class::modules() as $module) {
$owners[$module] = $class::label();
}
}
$rows = [];
foreach ($model->modules($variant, $templates) as $key) {
$class = $this->catalogue->modules()[$key];
$definition = $class::definition();
$on = ($draft['steps'][$key]['on'] ?? true) !== false || ! $definition->isOptional();
$reason = match (true) {
! $on => 'im Kanal abgeschaltet',
$key === 'hold' && ! $profile->preReservation() => 'keine Reservierung bei der Anfrage',
$key === 'offer.information' && $profile->inquiryAnswer() === InquiryAnswer::Offer => 'nicht bei verbindlichem Angebot',
$key === 'offer.binding' && $profile->inquiryAnswer() === InquiryAnswer::Information => 'erst, wenn ein Angebot von Hand gesendet wird',
$key === 'portal.payout' && $profile->payments() !== Responsibility::Portal => 'wir kassieren selbst',
$key === 'review.request' && $profile->reviewRequestSender() !== Responsibility::Landlord => 'die Bewertungsbitte kommt nicht von uns',
$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->arrivalInfoSender()->value,
'review.request' => $profile->reviewRequestSender()->value,
default => $definition->performers[0] ?? null,
};
$rows[] = ['module' => $key, 'label' => $definition->label, 'phase' => $definition->phase, 'on' => $on && $reason === null, 'reason' => $reason,
'performer' => $performer, 'mode' => $mode, 'toggle' => $definition->toggle, 'tester_only' => $definition->isTesterOnly(), 'inserted' => ! in_array($key, $standard, true), 'template' => $owners[$key] ?? null];
}
return $rows;
}
/**
* Everything that is not admissible in a draft (empty = it may be saved).
*
* @param array<string, mixed> $draft
* @return list<string>
*/
public function problems(Channel $channel, IntakeKind $intake, array $draft, bool $sandbox = false): array
{
$draft = $this->withoutOverriddenSettings($channel, $intake, $draft);
$problems = [];
if (! in_array($intake, $this->intakes($channel), true)) {
$problems[] = 'Dieser Kanal liefert keine '.($intake === IntakeKind::Booking ? 'festen Buchungen' : 'Anfragen').'.';
}
$key = (string) ($draft['model'] ?? '');
$options = $this->modelOptions($channel, $intake, (array) ($draft['capabilities'] ?? []) ?: null);
if ($key === '' || ! array_key_exists($key, $options)) {
return [...$problems, 'Das Ablaufmodell „'.$key.'“ gibt es für diese Eingangsart dieses Kanals nicht.'];
}
if (! $options[$key]['admissible']) {
return [...$problems, ...array_map(fn (Restriction $restriction): string => $restriction->text(), $options[$key]['restrictions'])];
}
$model = $options[$key]['model'];
$variant = $model->variant((string) ($draft['variant'] ?? 'standard'));
if ($variant === null) {
return [...$problems, 'Das Modell hat diese Variante nicht.'];
}
if ($variant->isTesterOnly() && ! $sandbox) {
$problems[] = 'Die Variante „'.$variant->label.'“ ist nur im Prozess-Tester verwendbar und kann nicht gespeichert werden.';
}
$templates = $this->templatesOf($model, $draft);
foreach ((array) ($draft['steps'] ?? []) as $module => $step) {
if (! $this->catalogue->hasModule($module) || ! in_array($module, $model->modules($variant->key, $templates), true)) {
$problems[] = "Der Schritt {$module} gehört nicht zu diesem Modell.";
continue;
}
$definition = $this->catalogue->modules()[$module]::definition();
if (($step['on'] ?? true) === false && ! $definition->isOptional()) {
$problems[] = 'Der Schritt „'.$definition->label.'“ ist Pflicht und kann nicht abgeschaltet werden.';
}
if ($definition->isTesterOnly() && ! $sandbox && ($step['on'] ?? true) !== false && $variant->isTesterOnly()) {
$problems[] = 'Der Schritt „'.$definition->label.'“ ist nur im Prozess-Tester verwendbar.';
}
}
// Responsibilities: fixed ones are set by the model; variable ones only to the values the model allows.
$responsibilities = $model::responsibilities();
foreach (Responsibilities::SETTINGS as $field => $setting) {
$value = $draft['settings'][$setting->value] ?? null;
if ($value === null || $value === '') {
continue;
}
$responsibility = Responsibility::tryFrom((string) $value);
if ($responsibility === null || ! $responsibilities->admits($setting, $responsibility)) {
$problems[] = Responsibilities::LABELS[$field].': „'.($responsibility?->getLabel() ?? $value).'“ ist in diesem Modell nicht zulässig.';
}
}
return array_values(array_unique([...$problems, ...$this->templateProblems($channel, $model, $draft)]));
}
/**
* What is wrong with the function templates of a draft: composition, the confirmed capabilities of the portal and
* responsibilities set by hand that contradict a template.
*
* @param array<string, mixed> $draft
* @return list<string>
*/
private function templateProblems(Channel $channel, ProcessModel $model, array $draft): array
{
$variant = (string) ($draft['variant'] ?? 'standard');
$problems = $this->composer->problems($model, (array) ($draft['templates'] ?? []), $variant);
if ($model->slots() === []) {
return $problems;
}
$capabilities = (array) ($draft['capabilities'] ?? []) ?: null;
$options = $this->templateOptions($channel, $model, $capabilities);
foreach ($this->composer->classes($this->templatesOf($model, $draft)) as $area => $class) {
foreach ($options[$area][$class::key()]['restrictions'] ?? [] as $restriction) {
$problems[] = $restriction->text();
}
foreach ($class::fixes() as $key => $fixed) {
$setting = ProcessSetting::tryFrom($key);
$value = $setting?->normalize($draft['settings'][$key] ?? null);
$fixedValue = $setting?->normalize($fixed) ?? $fixed;
if ($setting !== null && $value !== null && (string) $value !== (string) $fixedValue) {
$problems[] = $setting->question().' „'.$setting->describe($value).'“ widerspricht der Schablone „'.$class::label().'“ ('.$setting->describe($fixedValue).').';
}
}
}
$messages = app(ChannelCapabilities::class)->resolve($channel, $capabilities)[ChannelCapabilities::MESSAGES_GUEST] ?? null;
foreach ([ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoSender, ProcessSetting::ReviewRequestSender] as $sender) {
if (($draft['settings'][$sender->value] ?? null) === Responsibility::Portal->value && $messages !== null && $messages->isKnown() && $messages->value === false) {
$problems[] = $sender->question().' „Das Portal“ ist eingestellt, das Portal schreibt den Gast laut Fähigkeit aber nicht an.';
}
}
return $problems;
}
/**
* The profile a new case would get with the draft (model fixes and setting values applied).
*
* @param array<string, mixed> $draft
*/
public function profileWith(Channel $channel, IntakeKind $intake, array $draft): ProcessProfile
{
$draft = $this->withoutOverriddenSettings($channel, $intake, $draft);
$preview = clone $channel;
$overrides = (array) ($channel->process_overrides ?? []);
$overrides[$intake->value] = [...array_filter((array) ($draft['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== ''), 'model' => $draft['model'] ?? null, 'variant' => $draft['variant'] ?? 'standard', 'steps' => (array) ($draft['steps'] ?? []), 'templates' => (array) ($draft['templates'] ?? [])];
$preview->setAttribute('process_overrides', $overrides);
return app(ProcessSettings::class)->resolve($channel->property, $preview, $intake);
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace App\Process;
use App\Enums\Execution;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Channel;
use App\Process\Modules\ModuleDefinition;
use App\Process\Templates\TemplateComposer;
/**
* Rule-based comparison of a configuration draft (docs/Prozessarchitektur/MODUL_KONFIGURATIONSMATRIX.md §5): for every
* step the landlord switched off it names the steps that depend on it, what stays required, the admissible ways to
* achieve the result otherwise and what the configurator suggests. Derived from the module definitions the runner uses –
* no second set of rules. Pure: it reads and explains, it never changes a setting.
*/
final class ConfigurationImpact
{
public function __construct(private ProcessCatalogue $catalogue, private ChannelProcessConfiguration $configuration, private TemplateComposer $composer) {}
/**
* @param array<string, mixed> $draft
* @return list<array{module: string, label: string, valid: bool, affected: list<string>, relaxed: list<string>, remains: list<string>, alternatives: list<string>, suggestion: string}>
*/
public function of(Channel $channel, IntakeKind $intake, array $draft): array
{
$rows = collect($this->configuration->preview($channel, $intake, $draft));
$active = $rows->where('on', true)->pluck('module')->all();
$labels = $rows->mapWithKeys(fn (array $row): array => [$row['module'] => $row['label']])->all();
$impacts = [];
foreach ($rows as $row) {
$definition = $this->catalogue->modules()[$row['module']]::definition();
if (($draft['steps'][$row['module']]['on'] ?? true) !== false) {
continue;
}
$affected = $relaxed = [];
foreach ($active as $other) {
foreach ($this->catalogue->modules()[$other]::definition()->requires as $dependency) {
if ($dependency->module !== $row['module']) {
continue;
}
if ($dependency->hard) {
$affected[] = $labels[$other];
} else {
$relaxed[] = $labels[$other];
}
}
}
$alternatives = array_values(array_map(fn (Execution $execution): string => $execution->getLabel(), array_filter($definition->executions, fn (Execution $execution): bool => $execution !== Execution::NotRequired)));
$valid = $definition->isOptional();
$impacts[] = [
'module' => $row['module'], 'label' => $row['label'], 'valid' => $valid,
'affected' => array_values(array_unique($affected)), 'relaxed' => array_values(array_unique($relaxed)),
'remains' => $this->remains($definition, $affected, $labels),
'alternatives' => $alternatives,
'suggestion' => $this->suggestion($row['label'], $definition, $valid, $alternatives),
];
}
return $impacts;
}
/**
* What a change of function templates means (docs/Prozessarchitektur/SCHABLONEN.md): per changed area the modules that
* drop out, join or stay, the responsibility that changes, the stored switches and settings that no longer apply and
* what the new template still needs or does not build yet. Compared with the templates in force for new cases. Pure:
* nothing is changed, nothing is dropped silently – the landlord sees every consequence before saving.
*
* @param array<string, mixed> $draft
* @return list<array{area: string, from: ?string, to: string, removed: list<string>, added: list<string>, kept: list<string>, responsibility: ?array{from: string, to: string}, switches_lost: list<string>, settings_replaced: list<string>, needs: list<string>, extensions: list<string>}>
*/
public function ofTemplates(Channel $channel, IntakeKind $intake, array $draft): array
{
$model = $this->catalogue->model((string) ($draft['model'] ?? ''));
if ($model->slots() === []) {
return [];
}
$current = $this->configuration->currentTemplates($channel, $intake);
$target = $this->composer->resolve($model, (array) ($draft['templates'] ?? []));
$stored = (array) (($channel->process_overrides ?? [])[$intake->value] ?? []);
$labelOf = fn (string $module): string => ($this->catalogue->hasModule($module) ? $this->catalogue->modules()[$module]::definition()->label : $module);
$impacts = [];
foreach ($model->slots() as $area) {
$from = $current[$area->value] ?? null;
$to = $target[$area->value] ?? null;
$toClass = $to === null ? null : $this->catalogue->templateClass($to);
if ($toClass === null || $from === $to) {
continue;
}
$fromClass = $from === null ? null : $this->catalogue->templateClass($from);
$before = $fromClass === null ? [] : $fromClass::modules();
$after = $toClass::modules();
$removed = array_values(array_diff($before, $after));
$setting = $area->setting();
$changedFixes = [];
$replaced = [];
foreach ([...array_keys($toClass::fixes()), ...array_keys($toClass::defaults())] as $key) {
$changed = ProcessSetting::tryFrom($key);
$wanted = $toClass::fixes()[$key] ?? $toClass::defaults()[$key];
$previous = $fromClass === null ? null : ($fromClass::fixes()[$key] ?? $fromClass::defaults()[$key] ?? null);
if ($changed === null) {
continue;
}
if ($previous !== null && (string) $changed->normalize($previous) !== (string) $changed->normalize($wanted)) {
$changedFixes[] = $changed->question().' '.$changed->describe($changed->normalize($previous)).' → '.$changed->describe($changed->normalize($wanted)).(array_key_exists($key, $toClass::fixes()) ? '' : ' (nur ein Vorschlag – ausdrücklich gesetzte Werte bleiben)');
}
$storedValue = $changed->normalize($stored[$key] ?? null);
if (array_key_exists($key, $toClass::fixes()) && $storedValue !== null && (string) $storedValue !== (string) $changed->normalize($wanted)) {
$replaced[] = $changed->question().' Bisher gespeichert: „'.$changed->describe($storedValue).'“, künftig durch die Schablone: „'.$changed->describe($changed->normalize($wanted)).'“. Der gespeicherte Wert muss beim Speichern ausdrücklich entfernt werden.';
}
}
$impacts[] = [
'area' => $area->label(),
'from' => $fromClass === null ? null : $fromClass::label(),
'to' => $toClass::label(),
'removed' => array_map($labelOf, $removed),
'added' => array_map($labelOf, array_values(array_diff($after, $before))),
'kept' => array_map($labelOf, array_values(array_intersect($after, $before))),
'responsibility' => $fromClass !== null && $fromClass::responsibility() !== $toClass::responsibility()
? ['from' => $setting->describe($fromClass::responsibility()->value), 'to' => $setting->describe($toClass::responsibility()->value)]
: null,
'changed_settings' => $changedFixes,
'switches_lost' => array_map($labelOf, array_values(array_filter($removed, fn (string $module): bool => ($stored['steps'][$module]['on'] ?? true) === false))),
'settings_replaced' => $replaced,
'needs' => array_map(fn (string $result): string => 'Voraussetzung: '.$result, $toClass::requires()),
'extensions' => $toClass::extensions(),
];
}
return $impacts;
}
/**
* The results that stay necessary although the step is off: what the steps depending on it still need.
*
* @param list<string> $affected
* @param array<string, string> $labels
* @return list<string>
*/
private function remains(ModuleDefinition $definition, array $affected, array $labels): array
{
$remains = [];
if ($affected !== []) {
$remains[] = 'Weiterhin nötig, damit „'.implode('“, „', array_unique($affected)).'“ laufen kann: '.lcfirst($definition->purpose);
}
if ($definition->why !== null) {
$remains[] = $definition->why;
}
return $remains;
}
/**
* @param list<string> $alternatives
*/
private function suggestion(string $label, ModuleDefinition $definition, bool $valid, array $alternatives): string
{
if (! $valid) {
return '„'.$label.'“ ist Pflicht und kann nicht abgeschaltet werden.'.($alternatives !== [] ? ' Zulässig sind stattdessen: '.implode('; ', $alternatives).'.' : '');
}
return $alternatives === []
? '„'.$label.'“ entfällt ersatzlos; es ist nichts weiter einzustellen.'
: 'Statt abzuschalten, können Sie „'.$label.'“ auch so erledigen lassen: '.implode('; ', $alternatives).'. Es wird nichts anderes automatisch geändert.';
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
/**
* A1 – request on our own way answered with an information "unter Vorbehalt" (package 7).
*/
final class A1InformationModel extends InquiryModel
{
public static function key(): string
{
return 'a1.information';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Unverbindliche Auskunft';
}
public static function description(): string
{
return 'Die Anfrage reserviert nichts; der Gast erhält eine unverbindliche Auskunft, fragt die Buchung an, und wir bestätigen nach erneuter Prüfung verbindlich.';
}
public static function caseTypes(): array
{
return [CaseType::A1];
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'inquiry.request';
}
public static function presetTemplates(): array
{
return ['inquiry_answer' => 'inquiry.information'];
}
public static function fixes(): array
{
return ['pre_reservation' => false];
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
/**
* A1 – request on our own way (website, direct): reserving request, binding offer, acceptance.
*/
final class A1OfferModel extends InquiryModel
{
public static function key(): string
{
return 'a1.offer';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Angebot mit Vorreservierung';
}
public static function description(): string
{
return 'Die Anfrage reserviert den Zeitraum; sind alle Angaben da, geht das verbindliche Angebot mit Vertragsentwurf an den Gast, der es annimmt.';
}
public static function caseTypes(): array
{
return [CaseType::A1];
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'inquiry.request';
}
public static function presetTemplates(): array
{
return ['inquiry_answer' => 'inquiry.binding_offer'];
}
public static function fixes(): array
{
return ['pre_reservation' => true];
}
public function variants(): array
{
return [
Variant::make('standard', 'Angebot mit Vorreservierung'),
Variant::make('loyalty', 'Angebot mit Stammgastrabatt (Architekturnachweis, nur im Prozess-Tester)')
->testerOnly()
->insert(Point::AfterGuestIdentified, 'guest.loyalty_status')
->insert(Point::BeforePriceFixing, 'pricing.loyalty_discount'),
Variant::make('address_check', 'Angebot mit Anschriftsprüfung (Zusatzschritt, nur im Prozess-Tester)')
->testerOnly()
->insert(Point::AfterGuestIdentified, 'guest.address_check'),
];
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\Responsibility;
/**
* A2 – request of an intermediary answered with an information.
*/
final class A2InformationModel extends InquiryModel
{
public static function key(): string
{
return 'a2.information';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Portalanfrage mit Auskunft';
}
public static function description(): string
{
return 'Die Anfrage eines Portals wird mit einer unverbindlichen Auskunft beantwortet; verbindlich wird erst die Bestätigung des Buchungswunsches.';
}
public static function caseTypes(): array
{
return [CaseType::A2];
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'inquiry.request';
}
public static function presetTemplates(): array
{
return ['inquiry_answer' => 'inquiry.information'];
}
public static function fixes(): array
{
return ['pre_reservation' => false];
}
protected static function guestMessageOptions(): array
{
return [Responsibility::Landlord, Responsibility::Portal];
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\Responsibility;
/**
* A2 – request of an intermediary answered with our own binding offer.
*/
final class A2OfferModel extends InquiryModel
{
public static function key(): string
{
return 'a2.offer';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Portalanfrage mit Angebot';
}
public static function description(): string
{
return 'Die Anfrage eines Portals wird wie eine eigene behandelt: fehlende Angaben ergänzen, Zeitraum reservieren, verbindliches Angebot, Annahme.';
}
public static function caseTypes(): array
{
return [CaseType::A2];
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'inquiry.request';
}
public static function presetTemplates(): array
{
return ['inquiry_answer' => 'inquiry.binding_offer'];
}
public static function fixes(): array
{
return ['pre_reservation' => true];
}
protected static function guestMessageOptions(): array
{
return [Responsibility::Landlord, Responsibility::Portal];
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\Responsibility;
/**
* A3 – binding portal booking with our own handling (e.g. Destination Solutions, R08).
*/
class A3PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a3.portal_booking';
}
public static function version(): int
{
return 2;
}
public static function label(): string
{
return 'Portalbuchung, eigene Abwicklung';
}
public static function description(): string
{
return 'Das Portal bestätigt verbindlich; Vertragsunterlagen, Zahlungsforderung und -überwachung sowie Gastkommunikation übernehmen wir.';
}
public static function caseTypes(): array
{
return [CaseType::A3];
}
public static function capabilityRequirements(): array
{
return ['collects_payment' => false, 'provides_contract_documents' => false];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Landlord, 'contract_documents' => Responsibility::Landlord],
variable: ['guest_messages' => [Responsibility::Landlord], 'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody], 'local_services' => [Responsibility::Landlord]],
);
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'external.booking';
}
public static function presetTemplates(): array
{
return ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own'];
}
public static function fixes(): array
{
return ['payments' => 'landlord', 'documents' => 'landlord'];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Process\Models;
/**
* Version 1 (A3, V2) – the course the cases froze before V2.1; stays registered while any case carries it (requirement T3).
*/
final class A3PortalBookingModelV1 extends A3PortalBookingModel
{
public static function version(): int
{
return 1;
}
public function steps(): array
{
return $this->stepsOfVersion1();
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\Responsibility;
/**
* A4 – binding portal booking with shared handling: portal collection, our contract documentation (e.g. FeWo-direkt, R09).
*/
class A4PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a4.portal_booking';
}
public static function version(): int
{
return 2;
}
public static function label(): string
{
return 'Portalbuchung, Inkasso beim Portal';
}
public static function description(): string
{
return 'Das Portal bestätigt verbindlich und zieht das Geld des Gastes ein; die Vertragsdokumentation senden wir. Kommunikation, ergänzende Unterlagen und Anreiseinformation sind wählbar; die Auszahlung prüfen wir.';
}
public static function caseTypes(): array
{
return [CaseType::A4];
}
public static function capabilityRequirements(): array
{
return ['collects_payment' => true, 'provides_contract_documents' => false];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Portal, 'contract_documents' => Responsibility::Landlord],
variable: ['guest_messages' => [Responsibility::Landlord, Responsibility::Portal], 'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody], 'local_services' => [Responsibility::Landlord]],
);
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'external.booking';
}
public static function presetTemplates(): array
{
return ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own'];
}
public static function fixes(): array
{
return ['payments' => 'portal', 'documents' => 'landlord'];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Process\Models;
/**
* Version 1 (A4, V2) – the course the cases froze before V2.1; stays registered while any case carries it (requirement T3).
*/
final class A4PortalBookingModelV1 extends A4PortalBookingModel
{
public static function version(): int
{
return 1;
}
public function steps(): array
{
return $this->stepsOfVersion1();
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\Responsibility;
/**
* A5 – binding portal booking handled largely by the portal: collection and contract documentation at the portal.
*/
class A5PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a5.portal_booking';
}
public static function version(): int
{
return 2;
}
public static function label(): string
{
return 'Portalbuchung, weitgehend beim Portal';
}
public static function description(): string
{
return 'Das Portal bestätigt verbindlich, zieht das Geld ein und liefert die Vertragsunterlagen; wir übernehmen nur die eigenen lokalen Aufgaben und prüfen die Auszahlung.';
}
public static function caseTypes(): array
{
return [CaseType::A5];
}
public static function capabilityRequirements(): array
{
return ['collects_payment' => true, 'provides_contract_documents' => true];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Portal, 'contract_documents' => Responsibility::Portal],
variable: ['guest_messages' => [Responsibility::Portal, Responsibility::Landlord], 'supplementary_documents' => [Responsibility::Nobody, Responsibility::Landlord], 'local_services' => [Responsibility::Landlord]],
);
}
public static function isLegacy(): bool
{
return true;
}
public static function composedBy(): ?string
{
return 'external.booking';
}
public static function presetTemplates(): array
{
return ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.external'];
}
public static function fixes(): array
{
return ['payments' => 'portal', 'documents' => 'portal'];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Process\Models;
/**
* Version 1 (A5, V2) – the course the cases froze before V2.1; stays registered while any case carries it (requirement T3).
*/
final class A5PortalBookingModelV1 extends A5PortalBookingModel
{
public static function version(): int
{
return 1;
}
public function steps(): array
{
return $this->stepsOfVersion1();
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
/**
* A6 – own use, private stay or block (E-022/E-024): no contract, no reminders, no reviews; channels are blocked, an
* optional stay confirmation and a payment without reminders. Has no channel configuration.
*/
final class A6InternalModel extends ProcessModel
{
public static function key(): string
{
return 'a6.internal';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Eigenbelegung, private Überlassung, Sperre';
}
public static function description(): string
{
return 'Eigene Nutzung, privater Aufenthalt oder Sperrzeit: Kanäle sperren, bei Bedarf Aufenthaltsbestätigung und Zahlung ohne Erinnerungen.';
}
public static function caseTypes(): array
{
return [CaseType::A6];
}
public static function intakes(): array
{
return [IntakeKind::Internal];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of([]);
}
public function steps(): array
{
return [
Step::module('intake.record'),
Step::module('channels.block'),
Step::module('documents.stay_confirmation'),
Step::module('payments.internal'),
Step::module('case.tasks'),
Step::module('stay'),
Step::module('case.closure'),
Step::module('case.settlement'),
];
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\Responsibility;
use App\Process\Templates\TemplateArea;
/**
* The base process of a booking that is already binding at a portal (E-036), with slots for the function templates
* of collection and contract documentation. It replaces the fixed combinations A3/A4/A5: who collects and who provides
* the contract documents are chosen independently (docs/Prozessarchitektur/SCHABLONEN.md); the case type stays a derived
* classification. The course is the one A3–A5 share, with the slots at the positions of the modules they replace.
*/
class ExternalBookingModel extends ProcessModel
{
/** Results the base process provides to the templates. */
public const PROVIDES = ['case.recorded', 'guest.identified', 'binding.portal_total', 'price.known'];
public static function key(): string
{
return 'external.booking';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Extern verbindliche Portalbuchung';
}
public static function description(): string
{
return 'Das Portal bestätigt verbindlich. Wer das Geld einzieht und wer die Vertragsunterlagen bereitstellt, wählen Sie unabhängig voneinander; die Einzelschritte bleiben einstellbar.';
}
public static function caseTypes(): array
{
return [CaseType::A3, CaseType::A4, CaseType::A5];
}
public static function intakes(): array
{
return [IntakeKind::Booking];
}
/**
* Collection and contract documentation are chosen by template; guest communication is limited by the portal's
* confirmed capability, not by a fixed model.
*/
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Portal],
variable: [
'collection' => [Responsibility::Landlord, Responsibility::Portal],
'contract_documents' => [Responsibility::Landlord, Responsibility::Portal],
'guest_messages' => [Responsibility::Landlord, Responsibility::Portal],
'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody],
'local_services' => [Responsibility::Landlord],
],
);
}
public static function providedResults(): array
{
return self::PROVIDES;
}
public static function defaultTemplates(): array
{
return [
TemplateArea::Collection->value => 'collection.own',
TemplateArea::ContractDocuments->value => 'contract_docs.own',
TemplateArea::GuestCommunication->value => 'guest_comm.own',
];
}
public function steps(): array
{
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('binding.portal'),
Step::module('portal.confirmation'),
Step::point(Point::AfterBinding),
Step::slot(TemplateArea::ContractDocuments),
Step::module('channels.block'),
Step::slot(TemplateArea::Collection),
Step::module('case.tasks'),
Step::module('change.proposal'),
Step::slot(TemplateArea::GuestCommunication),
Step::module('guest.data_request'),
Step::point(Point::BeforeStay),
Step::module('stay'),
Step::module('review.request'),
Step::point(Point::BeforeSettlement),
Step::module('case.closure'),
Step::module('case.settlement'),
];
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Process\Models;
use App\Enums\IntakeKind;
use App\Enums\Responsibility;
/**
* Common course of a request answered on our own way (A1 direct/website, A2 via an intermediary): intake, guest's
* details, hold and availability, our answer (binding offer or information), acceptance, then the binding booking with
* our contract documentation, payments, stay and closing. The variants of A1/A2 share it; the models differ by intake
* channel and what they fix.
*/
abstract class InquiryModel extends ProcessModel
{
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Landlord, 'collection' => Responsibility::Landlord, 'contract_documents' => Responsibility::Landlord],
variable: [
'guest_messages' => static::guestMessageOptions(),
'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody],
'local_services' => [Responsibility::Landlord],
],
);
}
/**
* Who may write to the guest: ourselves; via an intermediary also its messaging.
*
* @return list<Responsibility>
*/
protected static function guestMessageOptions(): array
{
return [Responsibility::Landlord];
}
public function steps(): array
{
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('hold'),
Step::module('availability.check'),
Step::module('offer.information'),
Step::point(Point::BeforePriceFixing),
Step::module('offer.binding'),
Step::point(Point::BeforeBindingOffer),
Step::module('offer.acceptance'),
Step::point(Point::AfterBinding),
...self::bindingCourse(),
];
}
/**
* What follows once a case is binding – shared with the portal bookings.
*
* @return list<Step>
*/
public static function bindingCourse(): array
{
return [
Step::module('documents.send'),
Step::module('channels.block'),
Step::module('payments.monitor'),
Step::module('portal.payout'),
Step::module('case.tasks'),
Step::module('change.proposal'),
Step::module('arrival.details'),
Step::module('arrival.info'),
Step::module('guest.data_request'),
Step::point(Point::BeforeStay),
Step::module('stay'),
Step::module('review.request'),
Step::point(Point::BeforeSettlement),
Step::module('case.closure'),
Step::module('case.settlement'),
];
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\Responsibility;
use App\Process\Templates\TemplateArea;
/**
* The base process of a request (own website, portal inquiry, phone, e-mail) – the one course A1 and A2 shared, with
* slots for how it is answered (information or binding offer), the contract documentation, the collection and the
* guest communication. A1/A2 stay as presets, classification and for historical cases. The reservation is not part
* of the answer template: the hold module and the reservation setting stay independent of it (docs/Prozessarchitektur/
* SCHABLONENKATALOG.md §4.3).
*/
class InquiryRequestModel extends ProcessModel
{
/** Results the base process provides to the templates. */
public const PROVIDES = ['case.recorded', 'guest.identified', 'availability.checked', 'price.known'];
public static function key(): string
{
return 'inquiry.request';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Anfrage';
}
public static function description(): string
{
return 'Eine Anfrage – von der eigenen Webseite oder einem Portal. Sie wählen, womit Sie antworten (Auskunft oder verbindliches Angebot) und wer wem schreibt; Datenbeschaffung und Reservierung laufen unabhängig davon.';
}
public static function caseTypes(): array
{
return [CaseType::A1, CaseType::A2];
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(
fixed: ['contract' => Responsibility::Landlord, 'collection' => Responsibility::Landlord, 'contract_documents' => Responsibility::Landlord],
variable: [
'guest_messages' => [Responsibility::Landlord, Responsibility::Portal],
'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody],
'local_services' => [Responsibility::Landlord],
],
);
}
public static function providedResults(): array
{
return self::PROVIDES;
}
public static function templateRestrictions(): array
{
return [
'collection.portal' => 'Bei einer Anfrage schließen wir den Vertrag selbst (Annahme des Angebots) und kassieren selbst; Inkasso beim Portal gibt es nur bei bereits verbindlich gebuchten Portalbuchungen.',
'contract_docs.external' => 'Bei einer Anfrage entsteht der Vertrag erst durch unser Angebot und die Annahme des Gastes; das Portal kann keine Vertragsunterlagen dafür bereitstellen.',
];
}
public static function defaultTemplates(): array
{
return [
TemplateArea::InquiryAnswer->value => 'inquiry.binding_offer',
TemplateArea::ContractDocuments->value => 'contract_docs.own',
TemplateArea::Collection->value => 'collection.own',
TemplateArea::GuestCommunication->value => 'guest_comm.own',
];
}
public function steps(): array
{
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('hold'),
Step::module('availability.check'),
Step::slot(TemplateArea::InquiryAnswer),
Step::point(Point::BeforePriceFixing),
Step::module('offer.binding'),
Step::point(Point::BeforeBindingOffer),
Step::module('offer.acceptance'),
Step::point(Point::AfterBinding),
Step::slot(TemplateArea::ContractDocuments),
Step::module('channels.block'),
Step::slot(TemplateArea::Collection),
Step::module('case.tasks'),
Step::module('change.proposal'),
Step::slot(TemplateArea::GuestCommunication),
Step::module('guest.data_request'),
Step::point(Point::BeforeStay),
Step::module('stay'),
Step::module('review.request'),
Step::point(Point::BeforeSettlement),
Step::module('case.closure'),
Step::module('case.settlement'),
];
}
/**
* The extension variants of the architecture proof (tester only), as on the former offer model.
*
* @return list<Variant>
*/
public function variants(): array
{
return [
Variant::make('standard', 'Standard'),
Variant::make('loyalty', 'Mit Stammgastrabatt (Architekturnachweis, nur im Prozess-Tester)')
->testerOnly()
->insert(Point::AfterGuestIdentified, 'guest.loyalty_status')
->insert(Point::BeforePriceFixing, 'pricing.loyalty_discount'),
Variant::make('address_check', 'Mit Anschriftsprüfung (Zusatzschritt, nur im Prozess-Tester)')
->testerOnly()
->insert(Point::AfterGuestIdentified, 'guest.address_check'),
];
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Process\Models;
/**
* The fixed extension points of the process models (docs/Prozessarchitektur/Architektur/02 §5.1). A point guarantees
* what a module inserted there can rely on – BeforePriceFixing: the case is not binding yet; AfterBinding: it is.
* Adding a point changes every model that offers it (stage 4 of the module criteria, 02 §2).
*/
enum Point: string
{
case AfterGuestIdentified = 'after_guest_identified';
case BeforePriceFixing = 'before_price_fixing';
case BeforeBindingOffer = 'before_binding_offer';
case AfterBinding = 'after_binding';
case BeforeStay = 'before_stay';
case BeforeSettlement = 'before_settlement';
public function label(): string
{
return match ($this) {
self::AfterGuestIdentified => 'nach der Identifikation des Gastes',
self::BeforePriceFixing => 'vor der Preisfestlegung',
self::BeforeBindingOffer => 'vor dem verbindlichen Angebot',
self::AfterBinding => 'nach der Verbindlichkeit',
self::BeforeStay => 'vor dem Aufenthalt',
self::BeforeSettlement => 'vor dem Abschluss',
};
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Process\Models;
use App\Enums\IntakeKind;
/**
* Common course of a booking that is already binding at a portal (A3–A5, E-036): no second acceptance and no own
* price – the portal's total is taken over. What follows is the binding course shared with our own requests; who
* answers for collection and contract documentation is fixed by the concrete model (decision O1).
*/
abstract class PortalBookingModel extends ProcessModel
{
public static function intakes(): array
{
return [IntakeKind::Booking];
}
/**
* Version 2 (V2.1): waits for the portal's confirmation where the channel says so (before the guest-facing steps; the
* occupation does not depend on it) and offers the booking information as a step of its own after the documents.
*/
public function steps(): array
{
$course = [];
foreach (InquiryModel::bindingCourse() as $step) {
$course[] = $step;
if ($step->module === 'documents.send') {
$course[] = Step::module('documents.booking_notice');
}
}
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('binding.portal'),
Step::module('portal.confirmation'),
Step::point(Point::AfterBinding),
...$course,
];
}
/**
* The course of version 1 (V2), kept for the cases that froze it.
*
* @return list<Step>
*/
protected function stepsOfVersion1(): array
{
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('binding.portal'),
Step::point(Point::AfterBinding),
...InquiryModel::bindingCourse(),
];
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Process\ProcessCatalogue;
use App\Process\Templates\TemplateArea;
/**
* A centrally defined, versioned process model (docs/Prozessarchitektur/Architektur/02 §5): its course of steps with
* extension points, its admissible variants and the responsibilities it fixes. The case type stays the derived
* classification (ProcessProfile::caseTypeFor); a model only declares which case types it is admissible for.
* The landlord chooses among models, he never defines one.
*/
abstract class ProcessModel
{
abstract public static function key(): string;
abstract public static function version(): int;
abstract public static function label(): string;
abstract public static function description(): string;
/** @return list<CaseType> */
abstract public static function caseTypes(): array;
/** @return list<IntakeKind> */
abstract public static function intakes(): array;
abstract public static function responsibilities(): Responsibilities;
/** @return list<Step> */
abstract public function steps(): array;
/**
* What a channel must be able to do (and not do) for this model to fit: capability key => required value. Empty:
* the model fits every channel that delivers its intake kind (docs/Prozessarchitektur/V2.1/02 §3.2).
*
* @return array<string, bool>
*/
public static function capabilityRequirements(): array
{
return [];
}
/**
* Settings the model fixes for its cases (e.g. the pre-reservation of the offer model).
*
* @return array<string, string|int|bool>
*/
public static function fixes(): array
{
return [];
}
/**
* @return list<Variant>
*/
public function variants(): array
{
return [Variant::make('standard', 'Standard')];
}
public function variant(string $key): ?Variant
{
foreach ($this->variants() as $variant) {
if ($variant->key === $key) {
return $variant;
}
}
return null;
}
/**
* The function template areas this model offers a slot for (empty: the model's course is fixed).
*
* @return list<TemplateArea>
*/
public function slots(): array
{
return array_values(array_map(fn (Step $step): TemplateArea => $step->slot, array_filter($this->steps(), fn (Step $step): bool => $step->isSlot())));
}
/**
* Templates a model does not take, with the business reason (template key => reason). Everything not listed fits.
*
* @return array<string, string>
*/
public static function templateRestrictions(): array
{
return [];
}
/**
* For a legacy model: the key of the base process whose template combination it reproduces.
*/
public static function composedBy(): ?string
{
return null;
}
/**
* The results the base course provides to the templates of its slots (see FunctionTemplate::requires()).
*
* @return list<string>
*/
public static function providedResults(): array
{
return [];
}
/**
* The template (key) every slot gets when none was chosen: area value => template key.
*
* @return array<string, string>
*/
public static function defaultTemplates(): array
{
return [];
}
/**
* Whether the model is kept for compatibility (existing channels and frozen plans) and no longer offered as a
* choice: its combination is a preset of a composable model.
*/
public static function isLegacy(): bool
{
return false;
}
/**
* The template combination that reproduces this legacy model (area value => template key), or empty.
*
* @return array<string, string>
*/
public static function presetTemplates(): array
{
return [];
}
/**
* The modules of the course in order, with the variant's modules at their points and the chosen templates' modules
* at their slots.
*
* @param array<string, string> $templates area value => template key or key@version (missing areas: the default)
* @return list<string>
*/
public function modules(?string $variant = 'standard', array $templates = []): array
{
$chosen = $this->variant($variant ?? 'standard');
$catalogue = app(ProcessCatalogue::class);
$modules = [];
foreach ($this->steps() as $step) {
if ($step->isPoint()) {
array_push($modules, ...($chosen?->modulesAt($step->point) ?? []));
} elseif ($step->isSlot()) {
$reference = $templates[$step->slot->value] ?? static::defaultTemplates()[$step->slot->value] ?? null;
if ($reference !== null && ($class = $catalogue->templateClass($reference)) !== null) {
array_push($modules, ...$class::modules());
}
} else {
$modules[] = $step->module;
}
}
return $modules;
}
/**
* @return list<Point>
*/
public function points(): array
{
return array_values(array_map(fn (Step $step): Point => $step->point, array_filter($this->steps(), fn (Step $step): bool => $step->isPoint())));
}
public static function reference(): string
{
return static::key().'@'.static::version();
}
/** Whether the model fixes the setting (the configurator shows it, but not as a choice). */
public static function fixesSetting(ProcessSetting $setting): bool
{
return array_key_exists($setting->value, static::fixes());
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Process\Models;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
/**
* Who answers for what in a model (docs/Prozessarchitektur/Architektur/03 §2.3, decision E1/O1). The model fixes the
* responsibilities that decide the case type – contract, collection of the guest's money, binding contract
* documentation – and allows a set of values for the others; the configurator offers exactly these values at the step.
*/
final class Responsibilities
{
/** Responsibility fields that exist today as process settings. */
public const SETTINGS = [
'collection' => ProcessSetting::Payments,
'contract_documents' => ProcessSetting::Documents,
'guest_messages' => ProcessSetting::GuestMessages,
];
public const LABELS = [
'contract' => 'Vertragsabschluss',
'collection' => 'Inkasso (Geld des Gastes)',
'contract_documents' => 'Vertragsdokumentation',
'supplementary_documents' => 'Ergänzende Gastunterlagen',
'guest_messages' => 'Gastkommunikation und Anreiseinformation',
'local_services' => 'Lokale Leistungen',
];
/**
* @param array<string, Responsibility> $fixed
* @param array<string, list<Responsibility>> $variable
*/
private function __construct(public readonly array $fixed, public readonly array $variable) {}
/**
* @param array<string, Responsibility> $fixed
* @param array<string, list<Responsibility>> $variable
*/
public static function of(array $fixed, array $variable = []): self
{
return new self($fixed, $variable);
}
public function isFixed(string $field): bool
{
return array_key_exists($field, $this->fixed);
}
/**
* The values the configurator may offer for a field (one value when the model fixes it).
*
* @return list<Responsibility>
*/
public function allowed(string $field): array
{
return $this->isFixed($field) ? [$this->fixed[$field]] : ($this->variable[$field] ?? []);
}
/**
* Whether a setting value fits the model (used by the configurator and by the plausibility check of a plan).
*/
public function admits(ProcessSetting $setting, Responsibility $value): bool
{
$field = array_search($setting, self::SETTINGS, true);
return $field === false || $this->allowed($field) === [] || in_array($value, $this->allowed($field), true);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Process\Models;
use App\Process\Templates\TemplateArea;
/**
* One entry of a model's course: a module, an extension point where variants insert modules, or a slot where the
* function template chosen for its area puts its modules.
*/
final readonly class Step
{
private function __construct(public ?string $module, public ?Point $point, public ?TemplateArea $slot = null) {}
public static function module(string $key): self
{
return new self($key, null);
}
public static function point(Point $point): self
{
return new self(null, $point);
}
public static function slot(TemplateArea $area): self
{
return new self(null, null, $area);
}
public function isPoint(): bool
{
return $this->point !== null;
}
public function isSlot(): bool
{
return $this->slot !== null;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Models;
/**
* An admissible variant of a model: further modules at its extension points, the same case type. A variant marked
* tester-only can be configured as a draft and played through in the process tester, never frozen into a real case.
*/
final class Variant
{
/** @var array<string, list<string>> point value => module keys */
private array $inserts = [];
private bool $testerOnly = false;
private function __construct(public readonly string $key, public readonly string $label) {}
public static function make(string $key, string $label): self
{
return new self($key, $label);
}
public function insert(Point $point, string $module): self
{
$this->inserts[$point->value][] = $module;
return $this;
}
public function testerOnly(): self
{
$this->testerOnly = true;
return $this;
}
public function isTesterOnly(): bool
{
return $this->testerOnly;
}
/**
* @return list<string>
*/
public function modulesAt(Point $point): array
{
return $this->inserts[$point->value] ?? [];
}
/**
* @return array<string, list<string>>
*/
public function inserts(): array
{
return $this->inserts;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Process\Modules;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteLine;
use App\Process\CaseContext;
/**
* A module that adds lines to the price before it is fixed (extension point BeforePriceFixing). CasePricing asks it only
* for cases that are not binding yet; once the offer is made the lines are frozen in the case's quote.
*/
interface ContributesToPrice
{
/**
* @return list<QuoteLine> lines to add (empty: no contribution)
*/
public function priceLines(CaseContext $case, PriceQuote $quote): array;
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Process\Modules;
/**
* A dependency of one step on another (requirement T1, docs/Prozessarchitektur/Architektur/02 §7.1).
*
* - **hard:** the step may only run when the other step is done. Nothing switches this off – there is no flag on the
* other step that could lift it.
* - **soft:** the step should run after the other one when both are due in the same round; when the other one waits,
* fails or does not apply, the step goes on as long as its own requirements are met.
*
* Independent steps simply declare no dependency on each other; conditional steps express their condition in
* {@see ProcessModule::applies()}.
*/
final readonly class Dependency
{
private function __construct(public string $module, public bool $hard) {}
public static function hard(string $module): self
{
return new self($module, true);
}
public static function soft(string $module): self
{
return new self($module, false);
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Process\Modules\Guest;
use App\Enums\ActivityState;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
/**
* V2.1 case H (docs/Prozessarchitektur/V2.1/ABNAHME_V2_1.md): an optional plausibility check of the guest's address, added
* at the extension point „after the guest is identified“ without touching any other model. It only informs – the result
* never holds back an offer or a booking (the address gate of v0.11 stays the only rule). Tester only until released.
*/
final class AddressCheck extends Module
{
public static function key(): string
{
return 'guest.address_check';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Anschrift auf Plausibilität prüfen',
purpose: 'Prüft, ob die Anschrift des Gastes plausibel aussieht (Postleitzahl, Ort). Es ist ein Hinweis; nichts wird dadurch aufgehalten.',
phase: 'P01',
requires: [Dependency::hard('guest.details')],
triggers: ['facts.applied'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
events: ['facts'],
points: ['after_guest_identified'],
availability: ModuleDefinition::AVAILABILITY_TESTER_ONLY,
);
}
/**
* @return list<string> what looks implausible (empty: plausible)
*/
public function findings(CaseContext $case): array
{
$guest = $case->booking->guest;
$findings = [];
if (blank($guest?->street)) {
$findings[] = 'Straße fehlt';
}
if (blank($guest?->city)) {
$findings[] = 'Ort fehlt';
}
if (in_array(mb_strtoupper((string) $guest?->country), ['', 'DE', 'DEUTSCHLAND'], true) && ! preg_match('/^\d{5}$/', trim((string) $guest?->postal_code))) {
$findings[] = 'Postleitzahl hat nicht fünf Ziffern';
}
return $findings;
}
public function activities(CaseContext $case): array
{
$findings = $this->findings($case);
return [new Activity('address_check', 'Anschrift auf Plausibilität prüfen', ActivityState::Done, $findings === [] ? 'Anschrift wirkt plausibel' : 'Hinweis: '.implode(', ', $findings))];
}
public function state(CaseContext $case): ?StepState
{
return StepState::Done;
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Process\Modules\Intake;
use App\Availability\AvailabilityChecker;
use App\Enums\Execution;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
/**
* P01/P02: the dates are free (calendar truth of AvailabilityChecker, fresh imports by CalendarClearance). Mandatory
* and never switched off; the offer depends on it hard.
*/
final class AvailabilityCheck extends Module
{
public static function key(): string
{
return 'availability.check';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Verfügbarkeit',
purpose: 'Prüft, ob der Zeitraum frei ist und die Kalender der Portale aktuell sind.',
phase: 'P01',
executions: [Execution::Automatic],
condition: 'bei jeder Anfrage vor Angebot oder Bestätigung',
why: 'Doppelbuchungen sind nicht zu verantworten (E-027); die Verfügbarkeit wird immer geprüft.',
effects: ['network'],
triggers: ['intake', 'facts.applied'],
);
}
public function applies(CaseContext $case): bool
{
return $case->inquiry && ! $case->binding;
}
public function activities(CaseContext $case): array
{
return [];
}
public function state(CaseContext $case): ?StepState
{
$booking = $case->booking;
return app(AvailabilityChecker::class)->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking) ? StepState::Done : StepState::Problem;
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Process\Modules\Intake;
use App\Enums\ActivityState;
use App\Enums\ChannelTaskStatus;
use App\Enums\Execution;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Models\ChannelTask;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
/**
* Blocking and releasing the dates in portals that need it by hand (requires_manual_blocking): the tasks come from the
* observers (CreateChannelTasks) and are proven per portal (ChannelTaskProof). Mandatory, never switched off.
*/
final class ChannelBlocks extends Module
{
public static function key(): string
{
return 'channels.block';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Andere Kanäle sperren',
purpose: 'Sperrt den Zeitraum in Portalen, die nicht automatisch abgleichen, und gibt ihn bei Ende wieder frei – mit Nachweis je Portal.',
phase: 'P02',
executions: [Execution::Automatic, Execution::Manual],
condition: 'sobald ein Vorgang den Zeitraum belegt',
why: 'Die Belegung muss in anderen Portalen nachgezogen werden, sonst droht eine Doppelbuchung.',
effects: ['channel_task', 'landlord_mail', 'network'],
waits: ['landlord', 'portal'],
triggers: ['booking.occupies', 'booking.released'],
performers: ['landlord', 'system'],
);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
return ChannelTask::query()
->with('channel')
->whereHas('channel', fn ($query) => $query->where('property_id', $booking->property_id))
->whereDate('starts_on', $booking->arrival)
->whereDate('ends_on', $booking->departure)
->where('status', '!=', ChannelTaskStatus::Dismissed)
->orderBy('id')
->get()
->map(fn (ChannelTask $task): Activity => new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl()))
->all();
}
/** Listed on its own in the work list; it never holds another step back. */
public function state(CaseContext $case): ?StepState
{
return null;
}
}
@@ -0,0 +1,98 @@
<?php
namespace App\Process\Modules\Intake;
use App\Actions\RequestCaseData;
use App\Enums\ActivityState;
use App\Enums\Execution;
use App\Enums\ProcessSetting;
use App\Models\DataRequest;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\CaseRequirements;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\RunsAutomatically;
use App\Process\Modules\StepState;
use App\Process\StepResult;
/**
* P01: asks the guest for missing details by link and reminds (v0.11). It runs in its own mode (automatic / after
* release / by hand) whatever the case's processing is, and independently of the other steps: a clarification hold
* keeps its deadline while the request waits for the guest.
*/
final class GuestDataRequest extends Module implements RunsAutomatically
{
public static function key(): string
{
return 'guest.data_request';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Fehlende Angaben beim Gast anfragen',
purpose: 'Fragt fehlende Pflichtangaben per Link beim Gast an, erinnert und übergibt an Sie, wenn der Gast nicht antwortet.',
phase: 'P01',
executions: [Execution::Automatic, Execution::Approval, Execution::Manual, Execution::NotRequired],
condition: 'wenn Angaben für den nächsten Schritt fehlen und eine E-Mail-Adresse bekannt ist',
requires: [Dependency::hard('intake.record')],
effects: ['case_write', 'guest_mail'],
waits: ['guest', 'landlord', 'time'],
triggers: ['request.created', 'booking.taken_over', 'wish'],
parameters: [ProcessSetting::DataRequest, ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax, ProcessSetting::DataRequestReminderHours, ProcessSetting::GuestLinkValidDays],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
performers: ['system', 'landlord'],
modes: ['automatic', 'approval', 'manual'],
events: ['data_request', 'mail_in', 'facts', 'fact'],
);
}
/**
* Shown as a step of its own only for a binding booking (a request shows it inside the guest's details).
*/
public function activities(CaseContext $case): array
{
$request = $case->binding ? $case->booking->openDataRequest() : null;
if ($request === null) {
return [];
}
return [new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $case->later($request->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open),
implode(', ', CaseRequirements::labels($request->fields)).' · '.$request->statusLabel(), $request->status === DataRequest::OPEN ? null : 'approveDataRequest')];
}
public function state(CaseContext $case): ?StepState
{
$request = $case->booking->openDataRequest();
return match (true) {
$request === null => RequestCaseData::needs($case->booking) === null ? StepState::Done : StepState::Open,
$request->status === DataRequest::OPEN => StepState::Waiting,
default => StepState::Open,
};
}
public function due(CaseContext $case): bool
{
return RequestCaseData::needs($case->booking) !== null && $case->booking->openDataRequest() === null;
}
public function blockers(CaseContext $case): array
{
return CaseRequirements::isValid('guest.email', $case->booking->guest?->email) ? [] : ['Die E-Mail-Adresse des Gastes fehlt.'];
}
public function run(CaseContext $case): StepResult
{
$request = app(RequestCaseData::class)->forNextStep($case->booking);
return $request === null ? StepResult::blocked(['Nichts anzufragen.']) : StepResult::ran();
}
public function isOutward(): bool
{
return false;
}
}
Loaded 100 of 266 files, more files were not shown because too many files have changed in this diff. Show more