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>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 14:49:44 +01:00
1 parent 98df5e9e3b
commit 7e22e12cac
80 files changed
+4628 -445

No files matched your search

+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 ?: [[]]))));
}
}
+3 -365
View File
@@ -3,26 +3,9 @@
namespace App\Process;
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\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeStatus;
use App\Enums\ChannelTaskStatus;
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\BookingTask;
use App\Models\ChannelTask;
use App\Models\DataRequest;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Carbon\CarbonImmutable;
/**
@@ -39,341 +22,13 @@ class CaseActivities
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>
*/
public static function for(Booking $booking): array
{
$booking->loadMissing(['guest', 'property', 'payments']);
$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);
return app(ProcessRunner::class)->activities($booking);
}
/**
@@ -439,21 +94,4 @@ public static function situation(Booking $booking): string
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;
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 Throwable;
/**
* Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a binding booking
* once their composition is complete and needs no confirmation (template released and, for portal bookings, confirmed
* as the portal's terms). Whatever stops it is returned in plain
* 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).
* Facade of the process core (ProcessRunner, trigger 'automation') for the places that carry a case on after new
* facts, portal amounts or the landlord's "continue automatically": only what the landlord would do next anyway and
* only when the case is handled automatically – the offer or information of a request, the documents of a binding
* booking (never for cases taken over from the old data). Whatever stops it is returned in plain words.
*/
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)
*/
public function advance(Booking $booking): array
{
$booking->loadMissing(['guest', 'property']);
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 [];
return $this->runner->advance($booking, ProcessRunner::AUTOMATION)->reasons();
}
/**
+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\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Tenant;
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
@@ -30,10 +33,32 @@ public static function freeze(Booking $booking): void
$booking->intake ??= ProcessSettings::intakeFor($booking);
$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;
}
/**
* 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
{
CaseLog::record($booking, 'created', 'Vorgang angelegt: '.$booking->caseType()->getLabel().' ('.$booking->bookingChannelLabel().')', data: [
+41
View File
@@ -0,0 +1,41 @@
<?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 fixes(): array
{
return ['pre_reservation' => false];
}
}
+52
View File
@@ -0,0 +1,52 @@
<?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 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'),
];
}
}
+47
View File
@@ -0,0 +1,47 @@
<?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 fixes(): array
{
return ['pre_reservation' => false];
}
protected static function guestMessageOptions(): array
{
return [Responsibility::Landlord, Responsibility::Portal];
}
}
+47
View File
@@ -0,0 +1,47 @@
<?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 fixes(): array
{
return ['pre_reservation' => true];
}
protected static function guestMessageOptions(): array
{
return [Responsibility::Landlord, Responsibility::Portal];
}
}
@@ -0,0 +1,50 @@
<?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).
*/
final class A3PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a3.portal_booking';
}
public static function version(): int
{
return 1;
}
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 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 fixes(): array
{
return ['payments' => 'landlord', 'documents' => 'landlord'];
}
}
@@ -0,0 +1,50 @@
<?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).
*/
final class A4PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a4.portal_booking';
}
public static function version(): int
{
return 1;
}
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 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 fixes(): array
{
return ['payments' => 'portal', 'documents' => 'landlord'];
}
}
@@ -0,0 +1,50 @@
<?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.
*/
final class A5PortalBookingModel extends PortalBookingModel
{
public static function key(): string
{
return 'a5.portal_booking';
}
public static function version(): int
{
return 1;
}
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 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 fixes(): array
{
return ['payments' => 'portal', 'documents' => 'portal'];
}
}
+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'),
];
}
}
+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'),
];
}
}
+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',
};
}
}
+30
View File
@@ -0,0 +1,30 @@
<?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];
}
public function steps(): array
{
return [
Step::module('intake.record'),
Step::module('guest.details'),
Step::point(Point::AfterGuestIdentified),
Step::module('binding.portal'),
Step::point(Point::AfterBinding),
...InquiryModel::bindingCourse(),
];
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace App\Process\Models;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
/**
* 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;
/**
* 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 modules of the course in order, with the variant's modules at their points.
*
* @return list<string>
*/
public function modules(?string $variant = 'standard'): array
{
$chosen = $this->variant($variant ?? 'standard');
$modules = [];
foreach ($this->steps() as $step) {
if ($step->isPoint()) {
array_push($modules, ...($chosen?->modulesAt($step->point) ?? []));
} 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);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Process\Models;
/**
* One entry of a model's course: a module or an extension point where variants insert modules.
*/
final readonly class Step
{
private function __construct(public ?string $module, public ?Point $point) {}
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 function isPoint(): bool
{
return $this->point !== 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,49 @@
<?php
namespace App\Process\Modules\Intake;
use App\Availability\AvailabilityChecker;
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',
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,60 @@
<?php
namespace App\Process\Modules\Intake;
use App\Enums\ActivityState;
use App\Enums\ChannelTaskStatus;
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',
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,95 @@
<?php
namespace App\Process\Modules\Intake;
use App\Actions\RequestCaseData;
use App\Enums\ActivityState;
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',
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;
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Process\Modules\Intake;
use App\Enums\ActivityState;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
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;
/**
* P01: who the guest is and whether every detail the next step needs is there and valid (v0.11 G2a). The details
* themselves come in through the common fact intake (ContributeCaseFacts) from every source.
*/
final class GuestDetails extends Module
{
public static function key(): string
{
return 'guest.details';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Angaben des Gastes',
purpose: 'Identifiziert den Gast, führt seine Angaben aus allen Quellen zusammen und prüft, ob alles für den nächsten Schritt da ist.',
phase: 'P01',
requires: [Dependency::hard('intake.record')],
effects: ['case_write'],
waits: ['guest', 'landlord'],
triggers: ['facts.applied'],
parameters: [ProcessSetting::FormRequiresAddress],
performers: ['guest', 'landlord'],
events: ['facts', 'fact', 'guest', 'data_request', 'mail_in'],
);
}
/** We correspond with the guest ourselves (a request, or our documents, messages or payments). */
public function applies(CaseContext $case): bool
{
$profile = $case->profile;
return $case->inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$profile = $case->profile;
$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 = $case->inquiry && ! $case->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;
return [new Activity('contact', $title, $case->later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact'))];
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Process\Modules\Intake;
use App\Enums\ProcessSetting;
use App\Models\Booking;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
/**
* P01/P02: the hold of a request – clarification hold of an incomplete request or offer hold – and its deadline. It is
* set by the intake (RequestHold under the calendar lock) and by SendOffer, it ends by ExpireReservations or the
* release; this step only watches it. It depends on the intake alone, never on the guest's details, so a request that
* waits for its address keeps its clarification hold running (requirement K1/T1).
*/
final class Hold extends Module
{
public static function key(): string
{
return 'hold';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Reservierung des Zeitraums',
purpose: 'Hält den Zeitraum während der Klärung bzw. der Angebotsfrist frei und gibt ihn nach Ablauf wieder frei.',
phase: 'P01',
requires: [Dependency::hard('intake.record')],
effects: ['calendar_hold'],
waits: ['time'],
triggers: ['intake', 'offer.sent', 'schedule:bookings:expire-holds'],
parameters: [ProcessSetting::PreReservation, ProcessSetting::HoldHours, ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes],
toggle: ModuleDefinition::TOGGLE_CONDITIONAL,
events: ['hold'],
);
}
public function applies(CaseContext $case): bool
{
return $case->inquiry && $case->profile->preReservation();
}
/** The hold has no line of its own: the offer step and the situation show it. */
public function activities(CaseContext $case): array
{
return [];
}
public function state(CaseContext $case): ?StepState
{
$booking = $case->booking;
return match (true) {
$booking->isHoldActive() => StepState::Waiting,
$booking->hold_expires_at === null && $booking->hold_purpose === Booking::HOLD_CLARIFICATION => StepState::NotApplicable,
default => StepState::Done,
};
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Process\Modules\Intake;
use App\Enums\ActivityState;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P01: the case came in – request, portal booking or internal occasion. Recording it (and the hold of a request,
* under the calendar lock) is done by the intake actions; the step only shows it.
*/
final class IntakeRecord extends Module
{
public static function key(): string
{
return 'intake.record';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Eingang',
purpose: 'Hält den Eingang der Anfrage, Buchung oder Eigenbelegung fest und friert den Ablauf ein.',
phase: 'P01',
effects: ['case_write', 'calendar_hold'],
triggers: ['intake'],
events: ['created', 'intake', 'profile', 'hold', 'mode'],
);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
if ($booking->isInternal()) {
return [new Activity('intake', ($booking->internal_kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
}
return [new Activity('intake', $case->inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel())];
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Process\Modules\Intake;
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\Support\Money;
/**
* P02 for A3–A5: the booking is binding at the portal (E-036) – no second acceptance, no own price. The guest's total
* comes "laut Portal" (RecordPortalAmounts) and is never recalculated.
*/
final class PortalBinding extends Module
{
public static function key(): string
{
return 'binding.portal';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Verbindlichkeit beim Portal',
purpose: 'Stellt fest, dass die Buchung beim Portal verbindlich ist, und übernimmt den Gesamtpreis laut Portal.',
phase: 'P02',
requires: [Dependency::hard('intake.record')],
effects: ['case_write'],
waits: ['portal', 'landlord'],
triggers: ['intake', 'portal.amounts'],
performers: ['portal', 'landlord'],
events: ['status', 'portal_signal', 'price', 'amount'],
readsContractData: true,
);
}
public function applies(CaseContext $case): bool
{
return ! $case->inquiry;
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
return [
new Activity('binding', 'Beim Portal fest gebucht', $case->binding || $case->closed ? ActivityState::External : ActivityState::Open, $booking->portal_reference ? 'Buchungsnummer '.$booking->portal_reference : null, $case->binding ? null : 'confirm'),
new Activity('price', 'Gesamtpreis laut Portal eintragen', $case->later($booking->total === null ? ActivityState::Open : ActivityState::Done), $booking->total === null ? 'noch nicht bekannt' : Money::format($booking->total), $booking->total === null ? 'portalPrice' : null),
];
}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Process\Modules\Loyalty;
use App\Enums\ActivityState;
use App\Enums\QuoteLineType;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteLine;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\ContributesToPrice;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Support\Money;
/**
* Architecture proof (decision E7): a returning guest's discount as a Discount line before the price is fixed. Tester
* only. Test assumptions (E5/E6, not released business rules): a percentage of the rent with a cap; no discount when the
* quote already has a special offer discount; once the offer is made the line is frozen in the quote and never
* recalculated (also not when the booking changes).
*/
final class LoyaltyDiscount extends Module implements ContributesToPrice
{
public static function key(): string
{
return 'pricing.loyalty_discount';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Stammgastrabatt',
purpose: 'Gewährt Stammgästen einen Rabatt auf die Miete, bevor der Preis festgelegt wird (Architekturnachweis, nur im Prozess-Tester).',
phase: 'P02',
requires: [Dependency::hard('guest.loyalty_status')],
effects: [],
parameters: ['percent', 'max'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
points: ['before_price_fixing'],
readsContractData: true,
availability: ModuleDefinition::AVAILABILITY_TESTER_ONLY,
);
}
public function priceLines(CaseContext $case, PriceQuote $quote): array
{
$status = app(LoyaltyStatusCheck::class)->status($case);
if ($status['status'] !== LoyaltyStatusCheck::QUALIFIED || $quote->discount() > 0) {
return [];
}
$percent = (int) ($case->parameter(self::key(), 'percent') ?? 5);
$max = (int) ($case->parameter(self::key(), 'max') ?? 10000);
$amount = min($max, (int) round($quote->rent() * $percent / 100));
if ($amount <= 0) {
return [];
}
return [new QuoteLine(QuoteLineType::Discount, 'Stammgastrabatt '.$percent.' % ('.count($status['stays']).' frühere Aufenthalte)', 1, -$amount, -$amount)];
}
public function activities(CaseContext $case): array
{
$line = collect((array) ($case->booking->quote['lines'] ?? []))->first(fn (array $line): bool => str_starts_with((string) ($line['label'] ?? ''), 'Stammgastrabatt'));
return [new Activity('loyalty_discount', 'Stammgastrabatt', ActivityState::Done, $line !== null ? Money::format(-(int) $line['amount']).' im Angebot' : 'kein Rabatt im Angebot')];
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Process\Modules\Loyalty;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Models\Booking;
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;
/**
* Architecture proof (decision E7, docs/Prozessarchitektur/Architektur/02 §6): whether the guest is a returning guest –
* completed, not cancelled stays of the same guest e-mail at the same landlord within the look-back. Tester only: never
* part of a real case's plan. The status is derived from the stays on every evaluation (no second truth); the rules
* (count, look-back) are test assumptions, not released business rules.
*/
final class LoyaltyStatusCheck extends Module
{
public const QUALIFIED = 'qualified';
public const NOT_QUALIFIED = 'not_qualified';
public const UNKNOWN = 'unknown';
public static function key(): string
{
return 'guest.loyalty_status';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Stammgaststatus feststellen',
purpose: 'Stellt fest, ob der Gast schon bei Ihnen zu Gast war (Architekturnachweis, nur im Prozess-Tester).',
phase: 'P01',
requires: [Dependency::hard('guest.details')],
triggers: ['facts.applied'],
parameters: ['min_stays', 'lookback_years'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
events: ['facts'],
points: ['after_guest_identified'],
availability: ModuleDefinition::AVAILABILITY_TESTER_ONLY,
);
}
/**
* @return array{status: string, stays: list<string>}
*/
public function status(CaseContext $case): array
{
$email = mb_strtolower(trim((string) $case->booking->guest?->email));
if ($email === '') {
return ['status' => self::UNKNOWN, 'stays' => []];
}
$years = (int) ($case->parameter(self::key(), 'lookback_years') ?? 5);
$minimum = (int) ($case->parameter(self::key(), 'min_stays') ?? 1);
$stays = Booking::query()
->whereKeyNot($case->booking->id)
->where('status', BookingStatus::Completed)
->whereDate('departure', '>=', $case->today->subYears($years))
->whereHas('guest', fn ($query) => $query->whereRaw('lower(email) = ?', [$email]))
->orderBy('arrival')
->get()
->map(fn (Booking $stay): string => (string) $stay->reference)
->all();
return ['status' => count($stays) >= $minimum ? self::QUALIFIED : self::NOT_QUALIFIED, 'stays' => $stays];
}
public function activities(CaseContext $case): array
{
$status = $this->status($case);
return [new Activity('loyalty_status', 'Stammgaststatus feststellen', ActivityState::Done, match ($status['status']) {
self::QUALIFIED => 'Stammgast: '.count($status['stays']).' frühere Aufenthalte ('.implode(', ', $status['stays']).')',
self::NOT_QUALIFIED => 'kein Stammgast',
default => 'Status nicht feststellbar (keine E-Mail-Adresse) – kein Rabatt',
})];
}
public function state(CaseContext $case): ?StepState
{
return StepState::Done;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Process\Modules;
use App\Process\CaseContext;
/**
* Common ground of the modules: version 1, the state of the step is the state of its (first) activity.
*/
abstract class Module implements ProcessModule
{
public static function version(): int
{
return 1;
}
public function applies(CaseContext $case): bool
{
return true;
}
public function state(CaseContext $case): ?StepState
{
$activity = $this->activities($case)[0] ?? null;
return $activity === null ? null : StepState::fromActivity($activity->state);
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Process\Modules;
use App\Enums\ProcessSetting;
/**
* The contract of a module as data (docs/Prozessarchitektur/Architektur/02 §3.2). Fields marked "checked" are verified
* by `process:check` or the contract tests; the others describe and are reviewed by hand – they promise nothing a test
* cannot verify.
*
* @phpstan-type Performer 'system'|'landlord'|'guest'|'portal'|'service_provider'
*/
final readonly class ModuleDefinition
{
public const TOGGLE_MANDATORY = 'mandatory';
public const TOGGLE_OPTIONAL = 'optional';
public const TOGGLE_CONDITIONAL = 'conditional';
public const TOGGLE_EVENT_DRIVEN = 'event_driven';
public const AVAILABILITY_PRODUCTION = 'production';
/** Only in the process tester; never part of a real case's plan (decision E7, loyalty). */
public const AVAILABILITY_TESTER_ONLY = 'tester_only';
/**
* @param string $label name of the step for the landlord (describes)
* @param string $purpose what the step does, in plain words (describes)
* @param string $phase P01–P05 (checked)
* @param list<Dependency> $requires dependencies for readiness (checked: every module exists, no cycle)
* @param list<string> $effects kinds of effects the step may cause: case_write, guest_mail, landlord_mail, document, calendar_hold, channel_task, network (checked by the contract test)
* @param list<string> $waits whom or what the step can wait for: guest, portal, landlord, time (describes)
* @param list<string> $triggers events after which the step is evaluated again (describes; listed in process:check)
* @param list<ProcessSetting|string> $parameters settings or module parameters that shape the step (checked: known)
* @param string $toggle mandatory / optional / conditional / event_driven (checked: mandatory cannot be switched off)
* @param list<string> $performers who may carry the step out (checked against the models' responsibilities)
* @param list<string> $modes automatic / approval / manual (checked in the configurator)
* @param list<string> $events history types that belong to the step (shown behind the step)
* @param list<string> $points extension points the module may be inserted at (checked; empty = fixed place in a model)
* @param bool $readsContractData evaluates frozen contract data – needs an ongoing-case test (checked)
*/
public function __construct(
public string $label,
public string $purpose,
public string $phase,
public array $requires = [],
public array $effects = [],
public array $waits = [],
public array $triggers = [],
public array $parameters = [],
public string $toggle = self::TOGGLE_MANDATORY,
public array $performers = ['system'],
public array $modes = [],
public array $events = [],
public array $points = [],
public bool $readsContractData = false,
public string $availability = self::AVAILABILITY_PRODUCTION,
) {}
public function isOptional(): bool
{
return $this->toggle === self::TOGGLE_OPTIONAL;
}
public function isTesterOnly(): bool
{
return $this->availability === self::AVAILABILITY_TESTER_ONLY;
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Process\Modules\Money;
use App\Enums\ActivityState;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Support\Money;
/**
* A6: payment of an internal occasion with a price (e.g. linen, visitor's tax) – recorded, never reminded.
*/
final class InternalPayment extends Module
{
public static function key(): string
{
return 'payments.internal';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Zahlung (ohne Erinnerungen)',
purpose: 'Hält fest, was bei einer Eigenbelegung oder privaten Überlassung bezahlt wurde – ohne Erinnerungen.',
phase: 'P03',
effects: ['case_write'],
toggle: ModuleDefinition::TOGGLE_CONDITIONAL,
performers: ['landlord'],
events: ['payment'],
);
}
public function applies(CaseContext $case): bool
{
return $case->booking->total !== null && $case->booking->total > 0;
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$paid = $booking->paidAmount();
return [new Activity('payment', 'Zahlung (ohne Erinnerungen)', $case->later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt')];
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Process\Modules\Money;
use App\Enums\ActivityState;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Support\Money;
/**
* P03: the guest's payments – deposit and balance when we collect (A1–A3), the portal's collection when it collects
* (A4/A5: only "laut Portal", never money on our account). Reminders are sent by SendBookingReminders.
*/
final class PaymentMonitoring extends Module
{
public static function key(): string
{
return 'payments.monitor';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Zahlungen des Gastes',
purpose: 'Überwacht Anzahlung und Restzahlung und erinnert rechtzeitig – oder zeigt, was das Portal laut eigener Angabe eingezogen hat.',
phase: 'P03',
effects: ['case_write', 'guest_mail'],
waits: ['guest', 'portal', 'time'],
triggers: ['payment.recorded', 'portal.amounts', 'schedule:reminders'],
parameters: [ProcessSetting::Payments, ProcessSetting::GuestMessages],
performers: ['landlord', 'portal'],
events: ['payment', 'amount'],
readsContractData: true,
);
}
public function applies(CaseContext $case): bool
{
return ! $case->booking->isInternal();
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$binding = $case->binding;
if ($case->profile->payments() === Responsibility::Portal) {
$portal = $booking->processChannel()?->name ?? 'das Portal';
$viaPortal = $booking->paidViaPortal();
return [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',
})];
}
if ($booking->total === null) {
return [new Activity('payment', 'Zahlungen überwachen', $case->later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist')];
}
$paid = $booking->paidAmount();
return [
new Activity('deposit', 'Anzahlung erhalten', $case->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') : '')),
new Activity('balance', 'Restzahlung erhalten', $case->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') : '')),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Modules\Money;
use App\Enums\ActivityState;
use App\Enums\Responsibility;
use App\Pricing\CaseMoney;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Support\Money;
/**
* P03 for portal collection (A4/A5): the portal's payout on our account. Only a payout the landlord recorded as
* received counts (PaymentKind::PortalPayout); an announced payout or a portal report is no proof (decision O5).
*/
final class PortalPayout extends Module
{
public static function key(): string
{
return 'portal.payout';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Auszahlung des Portals',
purpose: 'Prüft, ob die Auszahlung des Portals tatsächlich auf unserem Konto eingegangen ist und zu den Angaben passt.',
phase: 'P03',
effects: ['case_write'],
waits: ['portal', 'landlord', 'time'],
triggers: ['portal.amounts', 'payment.recorded'],
performers: ['landlord'],
events: ['payment', 'amount'],
readsContractData: true,
);
}
public function applies(CaseContext $case): bool
{
return ! $case->booking->isInternal() && $case->profile->payments() === Responsibility::Portal;
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$portal = $booking->processChannel()?->name ?? 'das Portal';
$payout = CaseMoney::of($booking)->payout();
return [new Activity('payout', 'Auszahlung von '.$portal.' auf unser Konto', $case->later(match (true) {
! $case->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' : '')))];
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Process\Modules\Offer;
use App\Actions\AutoOffer;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Process\CaseContext;
use App\Process\StepResult;
/**
* The automatic answer of a request (binding offer or information "unter Vorbehalt"): due while the request waits for
* its first answer and the case is handled automatically; carried out by {@see AutoOffer}, which checks every release
* rule (dates, contract texts, calendar clearance, document composition) itself.
*/
trait AnswersRequest
{
public function due(CaseContext $case): bool
{
$booking = $case->booking;
return $booking->processingMode() === ProcessingMode::Automatic
&& $booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0
&& $booking->intake !== IntakeKind::Booking;
}
public function blockers(CaseContext $case): array
{
return app(AutoOffer::class)->blockers($case->booking);
}
public function run(CaseContext $case): StepResult
{
$reasons = app(AutoOffer::class)->handle($case->booking);
return $reasons === [] ? StepResult::ran() : StepResult::blocked($reasons);
}
public function isOutward(): bool
{
return true;
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Process\Modules\Offer;
use App\Availability\AvailabilityChecker;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
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;
/**
* P02: our own binding offer with the contract draft (SendOffer, versioned). The price is fixed here – extension point
* BeforePriceFixing lies before it. Never without every required detail (hard dependency on guest.details) and never
* for dates that are taken.
*/
final class BindingOffer extends Module implements RunsAutomatically
{
use AnswersRequest;
public static function key(): string
{
return 'offer.binding';
}
public static function version(): int
{
// 2: dates taken meanwhile are a problem of the step, an expired hold is not shown as reserved (F-001, F-002).
return 2;
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Verbindliches Angebot',
purpose: 'Erstellt das verbindliche Angebot mit Vertragsentwurf und sendet es dem Gast; der Zeitraum ist für die Haltefrist reserviert.',
phase: 'P02',
requires: [Dependency::hard('guest.details'), Dependency::hard('availability.check'), Dependency::soft('guest.data_request')],
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document', 'calendar_hold', 'network'],
waits: ['guest', 'landlord'],
triggers: ['automation', 'request.created', 'schedule:bookings:auto-offers'],
parameters: [ProcessSetting::Processing, ProcessSetting::HoldHours, ProcessSetting::ContractTemplate],
performers: ['system', 'landlord'],
modes: ['automatic', 'manual'],
events: ['offer', 'hold', 'mail', 'status'],
);
}
/** The binding way: the request reserves (pre-reservation) or an offer was made anyway. */
public function applies(CaseContext $case): bool
{
return $case->inquiry && ! ($case->profile->preReservation() === false && $case->booking->offer_version === 0);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$offerDone = $booking->offer_version > 0 || $case->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);
$open = ! $offerDone && $offerMissing === [] && $booking->status === BookingStatus::Reserved && filled($booking->guest?->email);
$taken = $open && ! app(AvailabilityChecker::class)->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking);
return [new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $case->later(match (true) {
$offerDone => ActivityState::Done,
$offerMissing !== [] => ActivityState::Later,
$taken => ActivityState::Problem,
$open => 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',
$taken => 'Der Zeitraum ist inzwischen belegt.',
$booking->isHoldActive() => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr',
$booking->hold_expires_at !== null => 'Reservierung abgelaufen am '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr – Zeitraum nicht reserviert',
default => null,
}, $offerDone || $offerMissing !== [] || $taken ? null : 'sendOffer')];
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Process\Modules\Offer;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
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\RunsAutomatically;
/**
* P02 (package 7): a request without a hold is answered with an information "unter Vorbehalt"; the guest asks for
* the booking (wish) and we check again and confirm bindingly.
*/
final class Information extends Module implements RunsAutomatically
{
use AnswersRequest;
public static function key(): string
{
return 'offer.information';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Unverbindliche Auskunft und Buchungswunsch',
purpose: 'Beantwortet die Anfrage mit einer unverbindlichen Auskunft ohne Reservierung; fragt der Gast die Buchung an, wird erneut geprüft und verbindlich bestätigt.',
phase: 'P02',
requires: [Dependency::hard('intake.record'), Dependency::soft('guest.data_request')],
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document'],
waits: ['guest', 'landlord'],
triggers: ['automation', 'request.created', 'schedule:bookings:auto-offers'],
parameters: [ProcessSetting::Processing, ProcessSetting::GuestLinkValidDays],
performers: ['system', 'landlord', 'guest'],
modes: ['automatic', 'manual'],
events: ['information', 'mail', 'hold', 'wish', 'status'],
);
}
public function applies(CaseContext $case): bool
{
return $case->inquiry && ! $case->profile->preReservation() && $case->booking->offer_version === 0;
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$binding = $case->binding;
$informed = $booking->information_version > 0 || $binding;
return [
new Activity('information', $booking->processingMode() === ProcessingMode::Automatic ? 'Unverbindliche Auskunft senden (automatisch)' : 'Unverbindliche Auskunft prüfen und senden', $case->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'),
new Activity('wish', 'Gast fragt die Buchung an', $case->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,
}),
new Activity('wish_check', 'Erneut prüfen und verbindlich bestätigen', $case->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',
}),
];
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Process\Modules\Offer;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P02: the guest accepts (AcceptOffer, acceptance record) or declines (RejectOffer); the booking becomes binding
* (ConfirmBooking). Cannot be switched off – our own way never binds without the guest's acceptance.
*/
final class OfferAcceptance extends Module
{
public static function key(): string
{
return 'offer.acceptance';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Annahme durch den Gast',
purpose: 'Der Gast nimmt das Angebot an oder lehnt es ab; mit der Annahme wird die Buchung verbindlich.',
phase: 'P02',
requires: [Dependency::hard('offer.binding')],
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document'],
waits: ['guest', 'time'],
triggers: ['offer.accepted', 'offer.declined'],
performers: ['guest'],
events: ['offer', 'status'],
);
}
public function applies(CaseContext $case): bool
{
return app(BindingOffer::class)->applies($case);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
return [new Activity('acceptance', 'Gast nimmt das Angebot an', $case->later(match (true) {
$case->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'),
$case->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,
})];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Process\Modules;
use App\Process\Activity;
use App\Process\CaseContext;
/**
* A business capability of the process (docs/Prozessarchitektur/Architektur/02 §3): it offers one step of a case's
* course and derives where that step stands from the case's data. Reading methods never write; a module that can carry
* its step out by itself also implements {@see RunsAutomatically}.
*/
interface ProcessModule
{
/** Stable key, e.g. 'offer.binding'. */
public static function key(): string;
/** Version of the module's business behaviour (raised for every change of behaviour, not for wording). */
public static function version(): int;
/** What the configurator, the impact analysis and the contract tests read (pure data, no I/O). */
public static function definition(): ModuleDefinition;
/** Whether the step belongs to this case at all. */
public function applies(CaseContext $case): bool;
/**
* Where the step stands, as the landlord sees it – usually one activity, some steps show none (they only watch) or
* several (one per portal task).
*
* @return list<Activity>
*/
public function activities(CaseContext $case): array;
/** The state the runner uses for dependencies (null: the step has no state of its own and never blocks). */
public function state(CaseContext $case): ?StepState;
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Process\Modules;
use App\Process\CaseContext;
use App\Process\StepResult;
/**
* A module whose step the system may carry out by itself (docs/Prozessarchitektur/Architektur/02 §7): the runner asks
* whether it is due, checks its hard dependencies, then runs it through the existing actions. `run` must be idempotent:
* a second run of a step that is already carried out has no effect.
*/
interface RunsAutomatically
{
/** Whether the system may carry the step out now by itself (its mode is automatic and the step is still to do). */
public function due(CaseContext $case): bool;
/**
* What keeps the step from being carried out now (plain words; empty = it may run).
*
* @return list<string>
*/
public function blockers(CaseContext $case): array;
/** Carries the step out by calling the existing action(s). */
public function run(CaseContext $case): StepResult;
/** Whether the step speaks to the guest or a third party (suspended while a portal report is open, decision O4). */
public function isOutward(): bool;
}
@@ -0,0 +1,116 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Actions\SendBookingDocuments;
use App\Enums\ActivityState;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Process\Activity;
use App\Process\CaseAutomation;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\RunsAutomatically;
use App\Process\StepResult;
/**
* P03: the binding contract documentation for the guest (booking confirmation with contract, or the documents of a
* portal booking). Who is responsible for it decides the case type (decision O1): ours in A1–A4, the portal's in A5 –
* then the step is shown as external.
*/
final class BookingDocuments extends Module implements RunsAutomatically
{
public static function key(): string
{
return 'documents.send';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Buchungsunterlagen (Vertragsdokumentation)',
purpose: 'Sendet dem Gast die verbindliche Buchungsbestätigung mit Vertrag bzw. die Unterlagen der Portalbuchung.',
phase: 'P03',
requires: [Dependency::hard('guest.details')],
effects: ['case_write', 'guest_mail', 'document'],
waits: ['landlord', 'portal'],
triggers: ['automation', 'booking.taken_over'],
parameters: [ProcessSetting::Documents, ProcessSetting::Processing, ProcessSetting::ContractTemplate],
performers: ['system', 'landlord', 'portal'],
modes: ['automatic', 'manual'],
events: ['document', 'mail'],
readsContractData: true,
);
}
public function applies(CaseContext $case): bool
{
return ! $case->booking->isInternal();
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
if ($case->profile->documents() === Responsibility::Portal) {
return [new Activity('documents', 'Buchungsunterlagen an den Gast', ActivityState::External)];
}
$binding = $case->binding;
$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() : [];
return [new Activity('documents', match (true) {
$state !== ActivityState::Open => $case->inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden',
$case->inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden',
default => 'Buchungsunterlagen prüfen und senden',
}, $case->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,
})];
}
/** The guest's e-mail and the price are what the documents need – not every detail of a request. */
public function due(CaseContext $case): bool
{
$booking = $case->booking;
return $booking->processingMode() === ProcessingMode::Automatic
&& $case->binding && $booking->confirmation_sent_at === null
&& $case->profile->documents() === Responsibility::Landlord && $case->profile->origin !== 'migration';
}
public function blockers(CaseContext $case): array
{
return app(CaseAutomation::class)->documentBlockers($case->booking);
}
public function run(CaseContext $case): StepResult
{
$reasons = app(SendBookingDocuments::class)->automatically($case->booking);
return $reasons === [] ? StepResult::ran() : StepResult::blocked($reasons);
}
public function isOutward(): bool
{
return true;
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Availability\AvailabilityChecker;
use App\Enums\ActivityState;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Models\BookingTask;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\CaseRequirements;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
use Carbon\CarbonImmutable;
/**
* Event-driven work on the case (docs/Prozessarchitektur/Architektur/02 §4.1): every open task – a portal's
* cancellation or change report, a booking wish to decide, conflicting details, payment and service tasks – and the done
* tasks of the stay as its record. Tasks have no fixed place in the course; the model shows them where it lists events.
*/
final class CaseTasks extends Module
{
public static function key(): string
{
return 'case.tasks';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Aufgaben und Meldungen',
purpose: 'Zeigt offene Aufgaben des Vorgangs – Meldungen der Portale, Entscheidungen, Zahlungs- und Leistungsaufgaben.',
phase: 'P03',
effects: ['case_write'],
waits: ['landlord'],
triggers: ['task.created', 'portal.report'],
toggle: ModuleDefinition::TOGGLE_EVENT_DRIVEN,
performers: ['landlord'],
events: ['task'],
);
}
public function activities(CaseContext $case): array
{
return BookingTask::query()->where('booking_id', $case->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()
->map(fn (BookingTask $task): Activity => self::task($task))
->all();
}
public function state(CaseContext $case): ?StepState
{
return null;
}
/**
* An open task of the case and the action that settles it.
*/
public 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);
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Enums\ActivityState;
use App\Enums\ChangeStatus;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
use App\Process\Modules\StepState;
/**
* Event-driven: a change of a binding booking proposed to the guest (ChangeBooking) – shown while it waits for the guest.
*/
final class ChangeProposal extends Module
{
public static function key(): string
{
return 'change.proposal';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Änderungsvorschlag',
purpose: 'Zeigt einen Änderungsvorschlag, der beim Gast liegt.',
phase: 'P03',
effects: ['case_write', 'guest_mail'],
waits: ['guest', 'time'],
triggers: ['change.proposed'],
toggle: ModuleDefinition::TOGGLE_EVENT_DRIVEN,
performers: ['landlord', 'guest'],
events: ['change'],
readsContractData: true,
);
}
public function activities(CaseContext $case): array
{
$activities = [];
foreach ($case->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') : ''));
}
return $activities;
}
public function state(CaseContext $case): ?StepState
{
return null;
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Process\Activity;
use App\Process\CaseClosure;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P05 (package 9): the commercial closing – payments, refunds and payouts cleared (CaseClosure::commercialPoints). With
* portal collection only after financial clearance; a portal report of a payout is no proof (decision O5).
*/
final class CommercialSettlement extends Module
{
public static function key(): string
{
return 'case.settlement';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Kaufmännisch abschließen',
purpose: 'Schließt den Vorgang kaufmännisch ab, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind.',
phase: 'P05',
requires: [Dependency::soft('case.closure')],
effects: ['case_write'],
waits: ['landlord', 'portal'],
triggers: ['payment.recorded', 'stay.closed'],
performers: ['landlord', 'system'],
events: ['settled'],
readsContractData: true,
);
}
public function applies(CaseContext $case): bool
{
$booking = $case->booking;
$settlementApplies = $booking->status === BookingStatus::Completed || $booking->status === BookingStatus::Cancelled;
return $settlementApplies || ($booking->isBinding() && ! $booking->isInternal()) || ($booking->isInternal() && (int) $booking->total > 0);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$settlementApplies = $booking->status === BookingStatus::Completed || $booking->status === BookingStatus::Cancelled;
$points = $settlementApplies && $booking->settled_at === null ? CaseClosure::commercialPoints($booking) : [];
return [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)];
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\InternalKind;
use App\Models\BookingTask;
use App\Process\Activity;
use App\Process\CaseClosure;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P05 (package 9): closing the stay once nothing is open for it (CaseClosure, overnight or by hand).
*/
final class StayClosure extends Module
{
public static function key(): string
{
return 'case.closure';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Aufenthalt abschließen',
purpose: 'Schließt den Aufenthalt ab, sobald nach der Abreise nichts mehr für ihn offen ist.',
phase: 'P05',
effects: ['case_write'],
waits: ['time', 'landlord'],
triggers: ['schedule:daily'],
performers: ['system', 'landlord'],
events: ['task', 'status', 'settled'],
);
}
public function applies(CaseContext $case): bool
{
return ! $case->closed && ($case->booking->isBinding() || $case->booking->status === BookingStatus::Completed);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$today = $case->today;
$completed = $booking->status === BookingStatus::Completed;
$blockers = $booking->isBinding() && ! $completed ? CaseClosure::stayBlockers($booking) : collect();
return [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)];
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Process\Modules\Settlement;
use App\Enums\ActivityState;
use App\Enums\InternalKind;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* A6: an optional stay confirmation for the guests of an own use or private stay (no rental contract).
*/
final class StayConfirmation extends Module
{
public static function key(): string
{
return 'documents.stay_confirmation';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Aufenthaltsbestätigung',
purpose: 'Bestätigt den Gästen einer Eigenbelegung oder privaten Überlassung den Aufenthalt – nur bei Bedarf.',
phase: 'P03',
effects: ['guest_mail', 'document'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
performers: ['landlord'],
events: ['document', 'mail'],
);
}
public function applies(CaseContext $case): bool
{
return $case->booking->internal_kind !== InternalKind::Block && filled($case->booking->guest?->email);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
return [new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $case->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 && ! $case->closed ? 'sendDocuments' : null)];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Modules\Stay;
use App\Actions\PrepareStays;
use App\Enums\ActivityState;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Models\BookingTask;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P04: contact and arrival time for the stay (PrepareStays reports missing ones in time as a task).
*/
final class ArrivalDetails extends Module
{
public static function key(): string
{
return 'arrival.details';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Anreisedaten',
purpose: 'Sammelt Telefon und Anreisezeit für die Übergabe und meldet rechtzeitig, was fehlt.',
phase: 'P04',
effects: ['case_write'],
waits: ['guest', 'landlord', 'time'],
triggers: ['schedule:prepare-stays'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
performers: ['landlord', 'guest', 'service_provider'],
events: ['task', 'services'],
);
}
public function applies(CaseContext $case): bool
{
return $case->binding && ! BookingTask::query()->where('booking_id', $case->booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->exists();
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$missing = PrepareStays::missingArrivalDetails($booking);
$left = $case->binding && $booking->departure <= $case->today;
return [new Activity('arrival_details', 'Anreisedaten', $case->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')];
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Process\Modules\Stay;
use App\Enums\ActivityState;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P04: the arrival information for the guest – sent by us (SendBookingReminders) or announced by the portal. Who sends
* it is variable within the model (supplementary, not contract documentation; decision O1).
*/
final class ArrivalInformation extends Module
{
public static function key(): string
{
return 'arrival.info';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Anreise-Informationen',
purpose: 'Wegbeschreibung, Schlüssel und Kontakt vor Ort rechtzeitig vor der Anreise.',
phase: 'P04',
effects: ['guest_mail'],
waits: ['time', 'portal'],
triggers: ['schedule:reminders'],
parameters: [ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoDaysBefore],
performers: ['system', 'portal', 'service_provider'],
events: ['document', 'mail'],
);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
$profile = $case->profile;
return [$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)', $case->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')];
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Process\Modules\Stay;
use App\Enums\ActivityState;
use App\Enums\Responsibility;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Dependency;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P05: asking the guest for a review after the stay (RequestReviews). Optional; today it follows who writes to the
* guest (GuestMessages = us).
*/
final class ReviewRequest extends Module
{
public static function key(): string
{
return 'review.request';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Bitte um eine Bewertung',
purpose: 'Bittet den Gast nach dem Aufenthalt um eine Bewertung.',
phase: 'P05',
requires: [Dependency::hard('stay')],
effects: ['guest_mail'],
waits: ['time'],
triggers: ['schedule:reviews'],
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
performers: ['system'],
events: ['mail'],
);
}
public function applies(CaseContext $case): bool
{
return $case->profile->guestMessages() === Responsibility::Landlord && ! $case->booking->isInternal();
}
public function activities(CaseContext $case): array
{
return [new Activity('review', 'Bitte um eine Bewertung (automatisch)', $case->later($case->booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later))];
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Process\Modules\Stay;
use App\Enums\ActivityState;
use App\Enums\InternalKind;
use App\Process\Activity;
use App\Process\CaseContext;
use App\Process\Modules\Module;
use App\Process\Modules\ModuleDefinition;
/**
* P04: the stay itself (or the time of an internal occupation).
*/
final class Stay extends Module
{
public static function key(): string
{
return 'stay';
}
public static function definition(): ModuleDefinition
{
return new ModuleDefinition(
label: 'Aufenthalt',
purpose: 'Der Aufenthalt vom Anreise- bis zum Abreisetag.',
phase: 'P04',
waits: ['time'],
triggers: ['schedule:daily'],
performers: ['guest', 'landlord'],
events: ['task', 'services', 'status'],
);
}
public function activities(CaseContext $case): array
{
$booking = $case->booking;
if ($booking->isInternal()) {
$kind = $booking->internal_kind;
return [new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $case->closed ? ActivityState::NotApplicable : ($booking->departure <= $case->today ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'))];
}
$arrived = $case->binding && $booking->arrival <= $case->today;
$left = $case->binding && $booking->departure <= $case->today;
return [new Activity('stay', 'Aufenthalt', $case->later(match (true) {
$left => ActivityState::Done,
$arrived => ActivityState::Waiting,
default => ActivityState::Later,
}), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'))];
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Process\Modules;
use App\Enums\ActivityState;
/**
* The state of a step as the runner reads it for dependencies (docs/Prozessarchitektur/Architektur/02 §7.2). Derived
* from the case's data on every evaluation, never stored.
*/
enum StepState: string
{
/** Carried out (by us or, where the model says so, by the portal). */
case Done = 'done';
/** To do now. */
case Open = 'open';
/** Waits for the guest, the portal, the landlord or a deadline. */
case Waiting = 'waiting';
/** Something went wrong or stands in the way (e.g. the dates are taken). */
case Problem = 'problem';
/** Not yet: a previous step of the case is not there. */
case Later = 'later';
/** Does not apply (any more) to this case. */
case NotApplicable = 'not_applicable';
public static function fromActivity(ActivityState $state): self
{
return match ($state) {
ActivityState::Done, ActivityState::External => self::Done,
ActivityState::Open => self::Open,
ActivityState::Waiting => self::Waiting,
ActivityState::Problem => self::Problem,
ActivityState::Later => self::Later,
ActivityState::NotApplicable => self::NotApplicable,
};
}
/** Whether a hard dependency on a step in this state is fulfilled. */
public function fulfils(): bool
{
return $this === self::Done;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Process;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Models\Booking;
use App\Models\BookingTask;
/**
* Decision O4: while a portal's report of a cancellation or change is open on a case, automatic messages to the guest
* that the report could make wrong or misleading (booking documents, payment reminders, arrival information, review
* request) wait until the landlord has clarified the report. The report itself never changes the booking.
*
* Only reports that the intake reliably assigned to this case count: PortalIntake opens these tasks only for a case
* found by its booking reference or its exact nights (E-019); unassigned portal mails never become a task on a case.
* Internal checks, deadlines, conflict detection and tasks go on as before.
*/
final class OutwardSuspension
{
public const KINDS = [BookingTaskKind::PortalCancellationReported, BookingTaskKind::PortalChangeReported];
/**
* The reason automatic messages to the guest wait, or null when they may go.
*/
public static function reason(Booking $booking): ?string
{
$task = BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', self::KINDS)->where('status', BookingTaskStatus::Open)->first();
return $task === null ? null : 'Automatische Nachrichten an den Gast warten, bis die Meldung „'.$task->label().'“ geklärt ist.';
}
}
+214
View File
@@ -0,0 +1,214 @@
<?php
namespace App\Process;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Process\Models\ProcessModel;
use App\Process\Modules\ProcessModule;
use App\Process\Modules\RunsAutomatically;
use InvalidArgumentException;
/**
* The registered modules and models (config/process.php) and the checks that keep the catalogue consistent
* (`php artisan process:check`, ProcessCatalogueTest).
*/
final class ProcessCatalogue
{
/** @var array<string, class-string<ProcessModule>>|null */
private ?array $modules = null;
/**
* @return array<string, class-string<ProcessModule>> key => class
*/
public function modules(): array
{
if ($this->modules === null) {
$this->modules = [];
foreach ((array) config('process.modules', []) as $class) {
$this->modules[$class::key()] = $class;
}
}
return $this->modules;
}
public function hasModule(string $key): bool
{
return array_key_exists($key, $this->modules());
}
public function module(string $key): ProcessModule
{
$class = $this->modules()[$key] ?? throw new InvalidArgumentException("Unknown process module [{$key}].");
return app($class);
}
/**
* Whether the registered class can serve a plan that froze the module in the given version.
*/
public function serves(string $key, int $version): bool
{
$class = $this->modules()[$key] ?? null;
return $class !== null && ($class::version() === $version || in_array($version, (array) config("process.compatible.{$key}", []), true));
}
/**
* @return array<string, array<int, class-string<ProcessModel>>>
*/
public function modelVersions(): array
{
return (array) config('process.models', []);
}
public function hasModel(string $key, ?int $version = null): bool
{
$versions = $this->modelVersions()[$key] ?? [];
return $version === null ? $versions !== [] : array_key_exists($version, $versions);
}
/**
* A model in a version (null: the latest).
*/
public function model(string $key, ?int $version = null): ProcessModel
{
$versions = $this->modelVersions()[$key] ?? throw new InvalidArgumentException("Unknown process model [{$key}].");
$version ??= max(array_keys($versions));
$class = $versions[$version] ?? throw new InvalidArgumentException("Process model [{$key}] has no version {$version}.");
return app($class);
}
/**
* The latest version of every model.
*
* @return array<string, ProcessModel>
*/
public function models(): array
{
$models = [];
foreach (array_keys($this->modelVersions()) as $key) {
$models[$key] = $this->model($key);
}
return $models;
}
/**
* The model a case follows when nobody chose one: derived from its frozen profile exactly as the v0.11 course
* branched (legacy mapping, docs/Prozessarchitektur/Architektur/06 §4).
*/
public function derivedModel(ProcessProfile $profile): string
{
return match ($profile->intake) {
IntakeKind::Internal => 'a6.internal',
IntakeKind::Inquiry => ($profile->caseType === CaseType::A2 ? 'a2' : 'a1').($profile->preReservation() ? '.offer' : '.information'),
IntakeKind::Booking => match ($profile->caseType) {
CaseType::A5 => 'a5.portal_booking',
CaseType::A4 => 'a4.portal_booking',
default => 'a3.portal_booking',
},
};
}
/**
* The models admissible for a case type and intake kind.
*
* @return array<string, ProcessModel>
*/
public function admissible(IntakeKind $intake, ?CaseType $caseType = null): array
{
return array_filter($this->models(), fn (ProcessModel $model): bool => in_array($intake, $model::intakes(), true)
&& ($caseType === null || in_array($caseType, $model::caseTypes(), true)));
}
/**
* Everything that is inconsistent in the catalogue (empty = consistent).
*
* @return list<string>
*/
public function problems(): array
{
$problems = [];
foreach ($this->modules() as $key => $class) {
$definition = $class::definition();
foreach ($definition->requires as $dependency) {
if (! $this->hasModule($dependency->module)) {
$problems[] = "Modul {$key}: Abhängigkeit {$dependency->module} ist nicht registriert.";
}
}
if (! in_array($definition->phase, ['P01', 'P02', 'P03', 'P04', 'P05'], true)) {
$problems[] = "Modul {$key}: unbekannte Phase {$definition->phase}.";
}
if (is_subclass_of($class, RunsAutomatically::class) && $definition->modes === []) {
$problems[] = "Modul {$key}: läuft automatisch, nennt aber keine Ausführungsart.";
}
}
foreach ($this->cycles() as $cycle) {
$problems[] = 'Zyklische harte Abhängigkeit: '.implode(' → ', $cycle);
}
foreach ($this->modelVersions() as $key => $versions) {
foreach ($versions as $version => $class) {
if ($class::key() !== $key || $class::version() !== $version) {
$problems[] = "Modell {$key}@{$version}: Klasse {$class} meldet ".$class::key().'@'.$class::version().'.';
}
$model = app($class);
foreach ($model->variants() as $variant) {
foreach ($model->modules($variant->key) as $module) {
if (! $this->hasModule($module)) {
$problems[] = "Modell {$key}@{$version}, Variante {$variant->key}: Modul {$module} ist nicht registriert.";
}
}
foreach ($variant->inserts() as $point => $modules) {
if (! in_array($point, array_map(fn ($p) => $p->value, $model->points()), true)) {
$problems[] = "Modell {$key}@{$version}, Variante {$variant->key}: Erweiterungspunkt {$point} gibt es im Modell nicht.";
}
foreach ($modules as $module) {
$points = $this->hasModule($module) ? $this->modules()[$module]::definition()->points : [];
if ($points !== [] && ! in_array($point, $points, true)) {
$problems[] = "Modell {$key}@{$version}: Modul {$module} darf nicht an {$point} stehen.";
}
if ($this->hasModule($module) && $this->modules()[$module]::definition()->isTesterOnly() && ! $variant->isTesterOnly()) {
$problems[] = "Modell {$key}@{$version}: Modul {$module} ist nur für den Prozess-Tester, Variante {$variant->key} aber nicht.";
}
}
}
}
}
}
return $problems;
}
/**
* @return list<list<string>>
*/
private function cycles(): array
{
$edges = [];
foreach ($this->modules() as $key => $class) {
$edges[$key] = array_values(array_map(fn ($dependency): string => $dependency->module, array_filter($class::definition()->requires, fn ($dependency): bool => $dependency->hard)));
}
$cycles = [];
$visit = function (string $node, array $path) use (&$visit, &$cycles, $edges): void {
if (in_array($node, $path, true)) {
$cycles[] = [...array_slice($path, (int) array_search($node, $path, true)), $node];
return;
}
foreach ($edges[$node] ?? [] as $next) {
$visit($next, [...$path, $node]);
}
};
foreach (array_keys($edges) as $node) {
$visit($node, []);
}
return array_values(array_unique($cycles, SORT_REGULAR));
}
}
+224
View File
@@ -0,0 +1,224 @@
<?php
namespace App\Process;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Process\Models\ProcessModel;
use DomainException;
/**
* The frozen process plan of a case (docs/Prozessarchitektur/Architektur/02 §1, §5.3): model and version, variant,
* the versions of its modules and the step settings of the channel (on/off, mode, performer, parameters) as they were
* when the case came in. Stored in `bookings.profile.plan`; cases without one (all before V2) get the derived plan of
* their profile on reading, which reproduces the v0.11 course (legacy mapping). The plan also keeps the labels of its
* steps, so a finished case stays readable even if a model definition is ever retired (requirement T3).
*/
final class ProcessPlan
{
public const DERIVED = 'derived';
public const CONFIGURED = 'configured';
public const TESTER = 'tester';
/**
* @param array<string, int> $modules module key => frozen version
* @param array<string, array{on?: bool, mode?: ?string, performer?: ?string, params?: array<string, mixed>}> $steps
* @param array<string, string> $labels module key => label at the time of freezing
*/
public function __construct(
public readonly string $model,
public readonly int $modelVersion,
public readonly string $variant,
public readonly array $modules,
public readonly array $steps = [],
public readonly string $source = self::DERIVED,
public readonly array $labels = [],
public readonly ?string $notice = null,
) {}
/**
* The plan of a case: frozen with it, or derived from its profile (never stored by reading).
*/
public static function of(Booking $booking): self
{
$data = (array) (($booking->profile ?? [])['plan'] ?? []);
return $data !== [] ? self::fromArray($data) : self::derive($booking->process());
}
/**
* The plan a case gets from its profile when no model was chosen for its channel.
*/
public static function derive(ProcessProfile $profile): self
{
$catalogue = app(ProcessCatalogue::class);
return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', [], self::DERIVED);
}
/**
* The plan frozen for a new case: the model and step settings chosen for its channel and intake kind (Kanal ›
* Ablauf), when admissible for the case's type; otherwise the derived one with a notice. Tester-only variants or
* modules are refused outside the process tester (decision E7).
*
* @param array<string, mixed> $configuration model, variant, steps of channels.process_overrides[intake]
*/
public static function freeze(ProcessProfile $profile, array $configuration, bool $sandbox = false): self
{
$catalogue = app(ProcessCatalogue::class);
$chosen = (string) ($configuration['model'] ?? '');
if ($chosen === '') {
return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', (array) ($configuration['steps'] ?? []), self::DERIVED);
}
if (! $catalogue->hasModel($chosen)) {
return self::derive($profile)->withNotice("Gewähltes Modell {$chosen} ist nicht registriert – abgeleitetes Modell verwendet.");
}
$model = $catalogue->model($chosen);
if (! in_array($profile->caseType, $model::caseTypes(), true) || ! in_array($profile->intake, $model::intakes(), true)) {
return self::derive($profile)->withNotice("Gewähltes Modell {$chosen} passt nicht zu Vorgangsart {$profile->caseType->value} – abgeleitetes Modell verwendet.");
}
$variant = (string) ($configuration['variant'] ?? 'standard');
$chosenVariant = $model->variant($variant) ?? throw new DomainException("Modell {$chosen} hat keine Variante {$variant}.");
if (! $sandbox && $chosenVariant->isTesterOnly()) {
throw new DomainException("Die Variante „{$chosenVariant->label}“ ist nur im Prozess-Tester verwendbar.");
}
foreach ($model->modules($variant) as $module) {
if (! $sandbox && $catalogue->module($module)::definition()->isTesterOnly()) {
throw new DomainException("Das Modul {$module} ist nur im Prozess-Tester verwendbar.");
}
}
return self::build($model, $variant, (array) ($configuration['steps'] ?? []), $sandbox ? self::TESTER : self::CONFIGURED);
}
/**
* The configuration of a channel for one intake kind as the plan reads it (model, variant, steps).
*
* @return array<string, mixed>
*/
public static function configurationOf(?Channel $channel, IntakeKind $intake): array
{
if ($channel === null || $intake === IntakeKind::Internal) {
return [];
}
return array_intersect_key((array) (($channel->process_overrides ?? [])[$intake->value] ?? []), array_flip(['model', 'variant', 'steps']));
}
/**
* @param array<string, mixed> $steps
*/
private static function build(ProcessModel $model, string $variant, array $steps, string $source): self
{
$catalogue = app(ProcessCatalogue::class);
$modules = [];
$labels = [];
foreach ($model->modules($variant) as $key) {
$class = $catalogue->modules()[$key];
$modules[$key] = $class::version();
$labels[$key] = $class::definition()->label;
}
return new self($model::key(), $model::version(), $variant, $modules, array_intersect_key($steps, $modules), $source, $labels);
}
private function withNotice(string $notice): self
{
return new self($this->model, $this->modelVersion, $this->variant, $this->modules, $this->steps, $this->source, $this->labels, $notice);
}
public function modelDefinition(): ProcessModel
{
$catalogue = app(ProcessCatalogue::class);
// A retired version (T3): its cases stay readable through the latest definition of the same model.
return $catalogue->hasModel($this->model, $this->modelVersion) ? $catalogue->model($this->model, $this->modelVersion) : $catalogue->model($this->model);
}
public function isHistoric(): bool
{
return ! app(ProcessCatalogue::class)->hasModel($this->model, $this->modelVersion);
}
/**
* The module keys of the case's course, in order.
*
* @return list<string>
*/
public function moduleKeys(): array
{
return array_keys($this->modules);
}
/** Whether a step is switched on (only optional steps can be switched off; mandatory ones are always on). */
public function enabled(string $module): bool
{
if (($this->steps[$module]['on'] ?? true) !== false) {
return true;
}
$catalogue = app(ProcessCatalogue::class);
return $catalogue->hasModule($module) && ! $catalogue->module($module)::definition()->isOptional();
}
public function mode(string $module): ?string
{
return $this->steps[$module]['mode'] ?? null;
}
public function performer(string $module): ?string
{
return $this->steps[$module]['performer'] ?? null;
}
public function parameter(string $module, string $name): mixed
{
return $this->steps[$module]['params'][$name] ?? null;
}
public function reference(): string
{
return $this->model.'@'.$this->modelVersion.($this->variant !== 'standard' ? ':'.$this->variant : '');
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return array_filter([
'model' => $this->model,
'model_version' => $this->modelVersion,
'variant' => $this->variant,
'modules' => $this->modules,
'steps' => $this->steps,
'source' => $this->source,
'labels' => $this->labels,
'notice' => $this->notice,
], fn (mixed $value): bool => $value !== null);
}
/**
* @param array<string, mixed> $data
*/
public static function fromArray(array $data): self
{
return new self(
(string) $data['model'],
(int) $data['model_version'],
(string) ($data['variant'] ?? 'standard'),
array_map('intval', (array) ($data['modules'] ?? [])),
(array) ($data['steps'] ?? []),
(string) ($data['source'] ?? self::DERIVED),
(array) ($data['labels'] ?? []),
isset($data['notice']) ? (string) $data['notice'] : null,
);
}
}
+197
View File
@@ -0,0 +1,197 @@
<?php
namespace App\Process;
use App\Enums\ActivityState;
use App\Models\Booking;
use App\Process\Modules\ProcessModule;
use App\Process\Modules\RunsAutomatically;
use App\Process\Modules\StepState;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* The one process core (docs/Prozessarchitektur/Architektur/02 §7): reads a case's course from its frozen plan and
* carries it on as far as its data allows.
*
* - **No second truth:** every state is derived from the case's data on each evaluation; the runner stores nothing.
* - **Readiness (requirement T1):** an automatic step is ready when it applies, is switched on, is due, its hard
* dependencies are done and nothing blocks it. A soft dependency only orders steps due in the same round. A waiting
* step therefore holds back exactly the steps that depend on it hard – a clarification hold runs on while the data
* request waits for the guest.
* - **Re-evaluation:** one step per round; after each step the case is read again and readiness is determined anew – a
* list of runnable steps is never carried over a state change.
* - **Triggers:** the existing places call {@see advance()} with what happened; only modules that declare the trigger
* are considered, so every caller keeps the scope it had in v0.11.
*/
final class ProcessRunner
{
/** The trigger of the former CaseAutomation::advance (facts, portal amounts, the landlord's "continue automatically"). */
public const AUTOMATION = 'automation';
/** @var array<int, true> cases being advanced in this process (a nested call returns at once) */
private static array $running = [];
public function __construct(private ProcessCatalogue $catalogue) {}
/**
* The activities of a case in the order of its plan, as the landlord sees them.
*
* @return list<Activity>
*/
public function activities(Booking $booking): array
{
$context = CaseContext::of($booking);
$activities = [];
foreach ($context->plan->moduleKeys() as $key) {
if (! $this->catalogue->hasModule($key)) {
// A step whose module was retired (T3): the finished case stays readable with the frozen label.
$activities[] = new Activity($key, ($context->plan->labels[$key] ?? $key).' (frühere Fassung)', ActivityState::NotApplicable);
continue;
}
$module = $this->catalogue->module($key);
if (! $context->plan->enabled($key) || ! $module->applies($context)) {
continue;
}
array_push($activities, ...$module->activities($context));
}
return $activities;
}
/**
* Carries a case on by itself as far as its data allows (only steps whose mode is automatic).
*
* @param string $trigger what happened (a trigger the modules declare, e.g. 'request.created')
*/
public function advance(Booking $booking, string $trigger = self::AUTOMATION): AdvanceResult
{
$result = new AdvanceResult;
if (isset(self::$running[$booking->id])) {
return $result;
}
$lock = Cache::lock('case-advance:'.$booking->id, 60);
if (! $lock->get()) {
// Another process is advancing this case right now and evaluates it again after each step.
return $result;
}
self::$running[$booking->id] = true;
try {
$this->rounds($booking, $trigger, $result);
} finally {
unset(self::$running[$booking->id]);
$lock->release();
}
return $result;
}
private function rounds(Booking $booking, string $trigger, AdvanceResult $result): void
{
$attempted = [];
$plan = ProcessPlan::of($booking);
$limit = count($plan->modules) + 1;
for ($round = 0; $round < $limit; $round++) {
$context = new CaseContext($booking->fresh() ?? $booking, $plan);
$ready = $this->ready($context, $trigger, $attempted, $result);
if ($ready === null) {
return;
}
$key = $ready::key();
$attempted[$key] = true;
/** @var ProcessModule&RunsAutomatically $ready */
try {
$step = CaseLog::context(fn (): StepResult => $ready->run($context), actor: CaseLog::SYSTEM.' (automatisch)');
} catch (Throwable $exception) {
report($exception);
$step = StepResult::failed('Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.');
}
if ($step->didRun()) {
$result->ran[] = $key;
} else {
$result->held[$key] = $step->reasons;
}
}
}
/**
* The next step to carry out, determined anew from the case's current data; steps that are due but cannot run are
* recorded with their reasons.
*
* @param array<string, true> $attempted
*/
private function ready(CaseContext $context, string $trigger, array $attempted, AdvanceResult $result): ?ProcessModule
{
$candidates = [];
foreach ($context->plan->moduleKeys() as $key) {
if (isset($attempted[$key]) || ! $this->catalogue->hasModule($key)) {
continue;
}
$module = $this->catalogue->module($key);
if (! $module instanceof RunsAutomatically || ! in_array($trigger, $module::definition()->triggers, true)) {
continue;
}
if (! $context->plan->enabled($key) || ! $module->applies($context) || ! $module->due($context)) {
continue;
}
$unmet = $this->unmetHardDependencies($module, $context);
if ($unmet !== []) {
// Not ready: a hard requirement is missing. Its own blockers say what (e.g. the missing details).
$result->held[$key] = $module->blockers($context) ?: array_map(fn (string $label): string => 'Wartet auf: '.$label.'.', $unmet);
continue;
}
if ($module->isOutward() && ($reason = OutwardSuspension::reason($context->booking)) !== null) {
$result->held[$key] = [$reason];
continue;
}
$candidates[$key] = $module;
}
foreach ($candidates as $key => $module) {
// A soft dependency that is ready in the same round goes first.
$before = array_filter($module::definition()->requires, fn ($dependency): bool => ! $dependency->hard && isset($candidates[$dependency->module]));
if ($before === []) {
return $module;
}
}
return $candidates === [] ? null : reset($candidates);
}
/**
* Labels of the hard dependencies that are not done. A dependency on a step that is not part of the plan or does
* not apply to the case is fulfilled (the condition does not concern this case).
*
* @return list<string>
*/
public function unmetHardDependencies(ProcessModule $module, CaseContext $context): array
{
$unmet = [];
foreach ($module::definition()->requires as $dependency) {
if (! $dependency->hard || ! array_key_exists($dependency->module, $context->plan->modules) || ! $this->catalogue->hasModule($dependency->module)) {
continue;
}
$required = $this->catalogue->module($dependency->module);
if (! $context->plan->enabled($dependency->module) || ! $required->applies($context)) {
continue;
}
$state = $required->state($context);
if ($state !== null && ! $state->fulfils() && $state !== StepState::NotApplicable) {
$unmet[] = $required::definition()->label;
}
}
return $unmet;
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Process;
/**
* What happened when the runner carried out one step: it ran (the action did its work), it was held back (with the
* reasons, shown to the landlord as before) or it failed technically.
*/
final readonly class StepResult
{
public const RAN = 'ran';
public const BLOCKED = 'blocked';
public const FAILED = 'failed';
/**
* @param list<string> $reasons
*/
private function __construct(public string $outcome, public array $reasons = []) {}
public static function ran(): self
{
return new self(self::RAN);
}
/**
* @param list<string> $reasons
*/
public static function blocked(array $reasons): self
{
return new self(self::BLOCKED, array_values($reasons));
}
public static function failed(string $reason): self
{
return new self(self::FAILED, [$reason]);
}
public function didRun(): bool
{
return $this->outcome === self::RAN;
}
}