diff --git a/app/Actions/CreateReservation.php b/app/Actions/CreateReservation.php index b44dec2..800b584 100644 --- a/app/Actions/CreateReservation.php +++ b/app/Actions/CreateReservation.php @@ -6,6 +6,7 @@ use App\Enums\BookingStatus; use App\Enums\FactSource; use App\Enums\IntakeKind; +use App\Enums\ProcessingMode; use App\Exceptions\ReservationException; use App\Mail\NewReservation; use App\Mail\ReservationReceived; @@ -16,6 +17,7 @@ use App\Pricing\PriceCalculator; use App\Pricing\QuoteException; use App\Pricing\StayRequest; +use App\Process\ProcessRunner; use App\Process\ProcessSettings; use App\Process\RequestHold; use App\Support\Settings; @@ -174,35 +176,27 @@ private function sendMails(Booking $booking): void { $blockers = []; $offerSent = false; + $asked = false; + // The process core answers the request as far as its data allows (Architektur V2, trigger request.created): + // automatic mode sends the offer or information; if details are missing, the data request asks for them + // (and then replaces the receipt) – independently of the offer, which waits for the details. try { - $auto = app(AutoOffer::class); - if ($auto->applies($booking)) { - $blockers = $auto->handle($booking); - $offerSent = $blockers === []; - if (! $offerSent) { - $booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]); - } - $booking->refresh(); + $result = app(ProcessRunner::class)->advance($booking, 'request.created'); + $offerSent = $result->ran('offer.binding') || $result->ran('offer.information'); + $booking->refresh(); + if (! $offerSent && $booking->processingMode() === ProcessingMode::Automatic) { + $blockers = [...$result->reasons('offer.binding'), ...$result->reasons('offer.information')]; + $booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]); } + $asked = $result->ran('guest.data_request') && $booking->openDataRequest()?->last_sent_at !== null; + $booking->refresh(); } catch (Throwable $exception) { Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]); $blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.']; $offerSent = false; } - // v0.11: details for the offer are missing – the data request asks for them (and then replaces the receipt). - $asked = false; - if (! $offerSent) { - try { - $request = app(RequestCaseData::class)->forNextStep($booking); - $asked = $request?->last_sent_at !== null; - $booking->refresh(); - } catch (Throwable $exception) { - Log::warning('Rückfrage fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]); - } - } - try { if (! $offerSent && ! $asked && filled($booking->guest?->email)) { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking)); diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index 1fc2587..236bea4 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -14,6 +14,7 @@ use App\Filament\Resources\Bookings\BookingResource; use App\Mail\OfferMade; use App\Models\Booking; +use App\Pricing\CasePricing; use App\Pricing\PriceCalculator; use App\Pricing\PriceQuote; use App\Pricing\QuoteException; @@ -189,7 +190,8 @@ public function offerUrl(Booking $booking): string */ public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote { - $quote = $this->calculator->calculate($booking->property, $stay); + // Extension point BeforePriceFixing (Architektur V2): PriceCalculator plus the lines of contributing modules. + $quote = app(CasePricing::class)->quote($booking, $stay); if ($adjustment === 0) { return $quote; } diff --git a/app/Actions/SubmitBookingWish.php b/app/Actions/SubmitBookingWish.php index 194231c..fc00321 100644 --- a/app/Actions/SubmitBookingWish.php +++ b/app/Actions/SubmitBookingWish.php @@ -21,6 +21,7 @@ use App\Process\CaseAutomation; use App\Process\CaseLog; use App\Process\CaseRequirements; +use App\Process\ProcessRunner; use App\Support\Inbox; use App\Support\Money; use App\Support\Settings; @@ -148,7 +149,7 @@ public function handle(Booking $booking, int $version, ?string $ip = null): stri // v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing. if ($outcome === self::PENDING) { - rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); + app(ProcessRunner::class)->advance($booking->fresh(), 'wish'); } return $outcome; diff --git a/app/Actions/TakeOverExternalBooking.php b/app/Actions/TakeOverExternalBooking.php index eeb94c5..68807a2 100644 --- a/app/Actions/TakeOverExternalBooking.php +++ b/app/Actions/TakeOverExternalBooking.php @@ -13,7 +13,7 @@ use App\Models\Guest; use App\Models\Property; use App\Pricing\PortalPrice; -use App\Process\CaseAutomation; +use App\Process\ProcessRunner; use Carbon\CarbonImmutable; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; @@ -96,9 +96,9 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar return $booking->refresh(); }); - app(CaseAutomation::class)->advance($booking); - // v0.11 (E-036): the booking stays binding; only missing administrative details of a reachable guest are asked for. - rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); + // The process core sends the documents when everything is there (automatic mode); v0.11 (E-036): the booking + // stays binding, only missing administrative details of a reachable guest are asked for. + app(ProcessRunner::class)->advance($booking, 'booking.taken_over'); return $booking->refresh(); } diff --git a/app/Console/Commands/SendPendingAutoOffers.php b/app/Console/Commands/SendPendingAutoOffers.php index bef4684..bd59be1 100644 --- a/app/Console/Commands/SendPendingAutoOffers.php +++ b/app/Console/Commands/SendPendingAutoOffers.php @@ -6,6 +6,7 @@ use App\Enums\BookingStatus; use App\Models\Booking; use App\Models\Tenant; +use App\Process\ProcessRunner; use App\Tenancy\TenantRunner; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; @@ -19,9 +20,9 @@ class SendPendingAutoOffers extends Command /** * Execute the console command. */ - public function handle(AutoOffer $autoOffer, TenantRunner $runner): int + public function handle(AutoOffer $autoOffer, TenantRunner $tenants, ProcessRunner $runner): int { - $runner->each(function (Tenant $tenant) use ($autoOffer): void { + $tenants->each(function (Tenant $tenant) use ($autoOffer, $runner): void { $pending = Booking::query() ->where('status', BookingStatus::Reserved) ->where('offer_version', 0) @@ -36,7 +37,8 @@ public function handle(AutoOffer $autoOffer, TenantRunner $runner): int $sent = 0; foreach ($pending as $booking) { try { - $sent += $autoOffer->handle($booking) === [] ? 1 : 0; + $result = $runner->advance($booking, 'schedule:bookings:auto-offers'); + $sent += $result->ran('offer.binding') || $result->ran('offer.information') ? 1 : 0; } catch (Throwable) { // The request stays pending for the landlord; the next run tries again. } diff --git a/app/Pricing/CasePricing.php b/app/Pricing/CasePricing.php new file mode 100644 index 0000000..7a14b17 --- /dev/null +++ b/app/Pricing/CasePricing.php @@ -0,0 +1,43 @@ +calculator->calculate($booking->property, $stay); + if ($booking->isBinding() || ! $booking->exists) { + return $quote; + } + + $context = CaseContext::of($booking); + foreach ($context->plan->moduleKeys() as $key) { + if (! $this->catalogue->hasModule($key) || ! $context->plan->enabled($key)) { + continue; + } + $module = $this->catalogue->module($key); + if (! $module instanceof ContributesToPrice || ! $module->applies($context)) { + continue; + } + foreach ($module->priceLines($context, $quote) as $line) { + $quote = $quote->withLine($line); + } + } + + return $quote; + } +} diff --git a/app/Process/AdvanceResult.php b/app/Process/AdvanceResult.php new file mode 100644 index 0000000..b94b287 --- /dev/null +++ b/app/Process/AdvanceResult.php @@ -0,0 +1,35 @@ + */ + public array $ran = []; + + /** @var array> 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 + */ + 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 ?: [[]])))); + } +} diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index d842187..8dd893d 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -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 */ 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 - */ - 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 - */ - 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 - */ - 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 - */ - 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(); - } } diff --git a/app/Process/CaseAutomation.php b/app/Process/CaseAutomation.php index fa7d3cc..5f50c52 100644 --- a/app/Process/CaseAutomation.php +++ b/app/Process/CaseAutomation.php @@ -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 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 - */ - 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(); } /** diff --git a/app/Process/CaseContext.php b/app/Process/CaseContext.php new file mode 100644 index 0000000..30b4930 --- /dev/null +++ b/app/Process/CaseContext.php @@ -0,0 +1,63 @@ +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); + } +} diff --git a/app/Process/CaseRecorder.php b/app/Process/CaseRecorder.php index 5715cfd..b4a64c3 100644 --- a/app/Process/CaseRecorder.php +++ b/app/Process/CaseRecorder.php @@ -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: [ diff --git a/app/Process/Models/A1InformationModel.php b/app/Process/Models/A1InformationModel.php new file mode 100644 index 0000000..c769cf9 --- /dev/null +++ b/app/Process/Models/A1InformationModel.php @@ -0,0 +1,41 @@ + false]; + } +} diff --git a/app/Process/Models/A1OfferModel.php b/app/Process/Models/A1OfferModel.php new file mode 100644 index 0000000..c67a786 --- /dev/null +++ b/app/Process/Models/A1OfferModel.php @@ -0,0 +1,52 @@ + 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'), + ]; + } +} diff --git a/app/Process/Models/A2InformationModel.php b/app/Process/Models/A2InformationModel.php new file mode 100644 index 0000000..31fa024 --- /dev/null +++ b/app/Process/Models/A2InformationModel.php @@ -0,0 +1,47 @@ + false]; + } + + protected static function guestMessageOptions(): array + { + return [Responsibility::Landlord, Responsibility::Portal]; + } +} diff --git a/app/Process/Models/A2OfferModel.php b/app/Process/Models/A2OfferModel.php new file mode 100644 index 0000000..52c5689 --- /dev/null +++ b/app/Process/Models/A2OfferModel.php @@ -0,0 +1,47 @@ + true]; + } + + protected static function guestMessageOptions(): array + { + return [Responsibility::Landlord, Responsibility::Portal]; + } +} diff --git a/app/Process/Models/A3PortalBookingModel.php b/app/Process/Models/A3PortalBookingModel.php new file mode 100644 index 0000000..d988301 --- /dev/null +++ b/app/Process/Models/A3PortalBookingModel.php @@ -0,0 +1,50 @@ + 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']; + } +} diff --git a/app/Process/Models/A4PortalBookingModel.php b/app/Process/Models/A4PortalBookingModel.php new file mode 100644 index 0000000..ae42984 --- /dev/null +++ b/app/Process/Models/A4PortalBookingModel.php @@ -0,0 +1,50 @@ + 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']; + } +} diff --git a/app/Process/Models/A5PortalBookingModel.php b/app/Process/Models/A5PortalBookingModel.php new file mode 100644 index 0000000..46ad106 --- /dev/null +++ b/app/Process/Models/A5PortalBookingModel.php @@ -0,0 +1,50 @@ + 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']; + } +} diff --git a/app/Process/Models/A6InternalModel.php b/app/Process/Models/A6InternalModel.php new file mode 100644 index 0000000..a80ae84 --- /dev/null +++ b/app/Process/Models/A6InternalModel.php @@ -0,0 +1,62 @@ + 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 + */ + 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 + */ + 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'), + ]; + } +} diff --git a/app/Process/Models/Point.php b/app/Process/Models/Point.php new file mode 100644 index 0000000..ac1a95b --- /dev/null +++ b/app/Process/Models/Point.php @@ -0,0 +1,30 @@ + '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', + }; + } +} diff --git a/app/Process/Models/PortalBookingModel.php b/app/Process/Models/PortalBookingModel.php new file mode 100644 index 0000000..ced270a --- /dev/null +++ b/app/Process/Models/PortalBookingModel.php @@ -0,0 +1,30 @@ + */ + abstract public static function caseTypes(): array; + + /** @return list */ + abstract public static function intakes(): array; + + abstract public static function responsibilities(): Responsibilities; + + /** @return list */ + abstract public function steps(): array; + + /** + * Settings the model fixes for its cases (e.g. the pre-reservation of the offer model). + * + * @return array + */ + public static function fixes(): array + { + return []; + } + + /** + * @return list + */ + 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 + */ + 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 + */ + 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()); + } +} diff --git a/app/Process/Models/Responsibilities.php b/app/Process/Models/Responsibilities.php new file mode 100644 index 0000000..40e3277 --- /dev/null +++ b/app/Process/Models/Responsibilities.php @@ -0,0 +1,70 @@ + 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 $fixed + * @param array> $variable + */ + private function __construct(public readonly array $fixed, public readonly array $variable) {} + + /** + * @param array $fixed + * @param array> $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 + */ + 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); + } +} diff --git a/app/Process/Models/Step.php b/app/Process/Models/Step.php new file mode 100644 index 0000000..9bf065f --- /dev/null +++ b/app/Process/Models/Step.php @@ -0,0 +1,26 @@ +point !== null; + } +} diff --git a/app/Process/Models/Variant.php b/app/Process/Models/Variant.php new file mode 100644 index 0000000..0c06d33 --- /dev/null +++ b/app/Process/Models/Variant.php @@ -0,0 +1,57 @@ +> 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 + */ + public function modulesAt(Point $point): array + { + return $this->inserts[$point->value] ?? []; + } + + /** + * @return array> + */ + public function inserts(): array + { + return $this->inserts; + } +} diff --git a/app/Process/Modules/ContributesToPrice.php b/app/Process/Modules/ContributesToPrice.php new file mode 100644 index 0000000..26951b0 --- /dev/null +++ b/app/Process/Modules/ContributesToPrice.php @@ -0,0 +1,19 @@ + lines to add (empty: no contribution) + */ + public function priceLines(CaseContext $case, PriceQuote $quote): array; +} diff --git a/app/Process/Modules/Dependency.php b/app/Process/Modules/Dependency.php new file mode 100644 index 0000000..7990e1f --- /dev/null +++ b/app/Process/Modules/Dependency.php @@ -0,0 +1,29 @@ +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; + } +} diff --git a/app/Process/Modules/Intake/ChannelBlocks.php b/app/Process/Modules/Intake/ChannelBlocks.php new file mode 100644 index 0000000..3967b8f --- /dev/null +++ b/app/Process/Modules/Intake/ChannelBlocks.php @@ -0,0 +1,60 @@ +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; + } +} diff --git a/app/Process/Modules/Intake/GuestDataRequest.php b/app/Process/Modules/Intake/GuestDataRequest.php new file mode 100644 index 0000000..38d52da --- /dev/null +++ b/app/Process/Modules/Intake/GuestDataRequest.php @@ -0,0 +1,95 @@ +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; + } +} diff --git a/app/Process/Modules/Intake/GuestDetails.php b/app/Process/Modules/Intake/GuestDetails.php new file mode 100644 index 0000000..6f60963 --- /dev/null +++ b/app/Process/Modules/Intake/GuestDetails.php @@ -0,0 +1,84 @@ +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'))]; + } +} diff --git a/app/Process/Modules/Intake/Hold.php b/app/Process/Modules/Intake/Hold.php new file mode 100644 index 0000000..d09f05b --- /dev/null +++ b/app/Process/Modules/Intake/Hold.php @@ -0,0 +1,63 @@ +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, + }; + } +} diff --git a/app/Process/Modules/Intake/IntakeRecord.php b/app/Process/Modules/Intake/IntakeRecord.php new file mode 100644 index 0000000..929ec62 --- /dev/null +++ b/app/Process/Modules/Intake/IntakeRecord.php @@ -0,0 +1,43 @@ +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())]; + } +} diff --git a/app/Process/Modules/Intake/PortalBinding.php b/app/Process/Modules/Intake/PortalBinding.php new file mode 100644 index 0000000..e46bd4b --- /dev/null +++ b/app/Process/Modules/Intake/PortalBinding.php @@ -0,0 +1,54 @@ +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), + ]; + } +} diff --git a/app/Process/Modules/Loyalty/LoyaltyDiscount.php b/app/Process/Modules/Loyalty/LoyaltyDiscount.php new file mode 100644 index 0000000..9b0756c --- /dev/null +++ b/app/Process/Modules/Loyalty/LoyaltyDiscount.php @@ -0,0 +1,69 @@ +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')]; + } +} diff --git a/app/Process/Modules/Loyalty/LoyaltyStatusCheck.php b/app/Process/Modules/Loyalty/LoyaltyStatusCheck.php new file mode 100644 index 0000000..c59ae63 --- /dev/null +++ b/app/Process/Modules/Loyalty/LoyaltyStatusCheck.php @@ -0,0 +1,90 @@ +} + */ + 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; + } +} diff --git a/app/Process/Modules/Module.php b/app/Process/Modules/Module.php new file mode 100644 index 0000000..56dfa9b --- /dev/null +++ b/app/Process/Modules/Module.php @@ -0,0 +1,28 @@ +activities($case)[0] ?? null; + + return $activity === null ? null : StepState::fromActivity($activity->state); + } +} diff --git a/app/Process/Modules/ModuleDefinition.php b/app/Process/Modules/ModuleDefinition.php new file mode 100644 index 0000000..62bb629 --- /dev/null +++ b/app/Process/Modules/ModuleDefinition.php @@ -0,0 +1,72 @@ + $requires dependencies for readiness (checked: every module exists, no cycle) + * @param list $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 $waits whom or what the step can wait for: guest, portal, landlord, time (describes) + * @param list $triggers events after which the step is evaluated again (describes; listed in process:check) + * @param list $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 $performers who may carry the step out (checked against the models' responsibilities) + * @param list $modes automatic / approval / manual (checked in the configurator) + * @param list $events history types that belong to the step (shown behind the step) + * @param list $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; + } +} diff --git a/app/Process/Modules/Money/InternalPayment.php b/app/Process/Modules/Money/InternalPayment.php new file mode 100644 index 0000000..cef9925 --- /dev/null +++ b/app/Process/Modules/Money/InternalPayment.php @@ -0,0 +1,47 @@ +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')]; + } +} diff --git a/app/Process/Modules/Money/PaymentMonitoring.php b/app/Process/Modules/Money/PaymentMonitoring.php new file mode 100644 index 0000000..89f6785 --- /dev/null +++ b/app/Process/Modules/Money/PaymentMonitoring.php @@ -0,0 +1,81 @@ +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') : '')), + ]; + } +} diff --git a/app/Process/Modules/Money/PortalPayout.php b/app/Process/Modules/Money/PortalPayout.php new file mode 100644 index 0000000..a2682d4 --- /dev/null +++ b/app/Process/Modules/Money/PortalPayout.php @@ -0,0 +1,57 @@ +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' : '')))]; + } +} diff --git a/app/Process/Modules/Offer/AnswersRequest.php b/app/Process/Modules/Offer/AnswersRequest.php new file mode 100644 index 0000000..72d5514 --- /dev/null +++ b/app/Process/Modules/Offer/AnswersRequest.php @@ -0,0 +1,44 @@ +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; + } +} diff --git a/app/Process/Modules/Offer/BindingOffer.php b/app/Process/Modules/Offer/BindingOffer.php new file mode 100644 index 0000000..f621e6d --- /dev/null +++ b/app/Process/Modules/Offer/BindingOffer.php @@ -0,0 +1,86 @@ +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')]; + } +} diff --git a/app/Process/Modules/Offer/Information.php b/app/Process/Modules/Offer/Information.php new file mode 100644 index 0000000..d77861e --- /dev/null +++ b/app/Process/Modules/Offer/Information.php @@ -0,0 +1,86 @@ +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', + }), + ]; + } +} diff --git a/app/Process/Modules/Offer/OfferAcceptance.php b/app/Process/Modules/Offer/OfferAcceptance.php new file mode 100644 index 0000000..09ec2dd --- /dev/null +++ b/app/Process/Modules/Offer/OfferAcceptance.php @@ -0,0 +1,59 @@ +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, + })]; + } +} diff --git a/app/Process/Modules/ProcessModule.php b/app/Process/Modules/ProcessModule.php new file mode 100644 index 0000000..1e373ba --- /dev/null +++ b/app/Process/Modules/ProcessModule.php @@ -0,0 +1,37 @@ + + */ + 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; +} diff --git a/app/Process/Modules/RunsAutomatically.php b/app/Process/Modules/RunsAutomatically.php new file mode 100644 index 0000000..5dea6c2 --- /dev/null +++ b/app/Process/Modules/RunsAutomatically.php @@ -0,0 +1,30 @@ + + */ + 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; +} diff --git a/app/Process/Modules/Settlement/BookingDocuments.php b/app/Process/Modules/Settlement/BookingDocuments.php new file mode 100644 index 0000000..25f3a22 --- /dev/null +++ b/app/Process/Modules/Settlement/BookingDocuments.php @@ -0,0 +1,116 @@ +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; + } +} diff --git a/app/Process/Modules/Settlement/CaseTasks.php b/app/Process/Modules/Settlement/CaseTasks.php new file mode 100644 index 0000000..6ab65fd --- /dev/null +++ b/app/Process/Modules/Settlement/CaseTasks.php @@ -0,0 +1,90 @@ +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); + } +} diff --git a/app/Process/Modules/Settlement/ChangeProposal.php b/app/Process/Modules/Settlement/ChangeProposal.php new file mode 100644 index 0000000..717fcf7 --- /dev/null +++ b/app/Process/Modules/Settlement/ChangeProposal.php @@ -0,0 +1,53 @@ +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; + } +} diff --git a/app/Process/Modules/Settlement/CommercialSettlement.php b/app/Process/Modules/Settlement/CommercialSettlement.php new file mode 100644 index 0000000..bb81249 --- /dev/null +++ b/app/Process/Modules/Settlement/CommercialSettlement.php @@ -0,0 +1,65 @@ +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)]; + } +} diff --git a/app/Process/Modules/Settlement/StayClosure.php b/app/Process/Modules/Settlement/StayClosure.php new file mode 100644 index 0000000..3a6ec89 --- /dev/null +++ b/app/Process/Modules/Settlement/StayClosure.php @@ -0,0 +1,62 @@ +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)]; + } +} diff --git a/app/Process/Modules/Settlement/StayConfirmation.php b/app/Process/Modules/Settlement/StayConfirmation.php new file mode 100644 index 0000000..23eae1c --- /dev/null +++ b/app/Process/Modules/Settlement/StayConfirmation.php @@ -0,0 +1,47 @@ +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)]; + } +} diff --git a/app/Process/Modules/Stay/ArrivalDetails.php b/app/Process/Modules/Stay/ArrivalDetails.php new file mode 100644 index 0000000..18cfc73 --- /dev/null +++ b/app/Process/Modules/Stay/ArrivalDetails.php @@ -0,0 +1,57 @@ +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')]; + } +} diff --git a/app/Process/Modules/Stay/ArrivalInformation.php b/app/Process/Modules/Stay/ArrivalInformation.php new file mode 100644 index 0000000..2a25837 --- /dev/null +++ b/app/Process/Modules/Stay/ArrivalInformation.php @@ -0,0 +1,48 @@ +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')]; + } +} diff --git a/app/Process/Modules/Stay/ReviewRequest.php b/app/Process/Modules/Stay/ReviewRequest.php new file mode 100644 index 0000000..9f84ae5 --- /dev/null +++ b/app/Process/Modules/Stay/ReviewRequest.php @@ -0,0 +1,49 @@ +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))]; + } +} diff --git a/app/Process/Modules/Stay/Stay.php b/app/Process/Modules/Stay/Stay.php new file mode 100644 index 0000000..3b6b56e --- /dev/null +++ b/app/Process/Modules/Stay/Stay.php @@ -0,0 +1,53 @@ +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'))]; + } +} diff --git a/app/Process/Modules/StepState.php b/app/Process/Modules/StepState.php new file mode 100644 index 0000000..4117797 --- /dev/null +++ b/app/Process/Modules/StepState.php @@ -0,0 +1,48 @@ + 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; + } +} diff --git a/app/Process/OutwardSuspension.php b/app/Process/OutwardSuspension.php new file mode 100644 index 0000000..3a7ca83 --- /dev/null +++ b/app/Process/OutwardSuspension.php @@ -0,0 +1,32 @@ +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.'; + } +} diff --git a/app/Process/ProcessCatalogue.php b/app/Process/ProcessCatalogue.php new file mode 100644 index 0000000..32bf0dc --- /dev/null +++ b/app/Process/ProcessCatalogue.php @@ -0,0 +1,214 @@ +>|null */ + private ?array $modules = null; + + /** + * @return array> 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>> + */ + 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 + */ + 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 + */ + 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 + */ + 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> + */ + 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)); + } +} diff --git a/app/Process/ProcessPlan.php b/app/Process/ProcessPlan.php new file mode 100644 index 0000000..76c00d7 --- /dev/null +++ b/app/Process/ProcessPlan.php @@ -0,0 +1,224 @@ + $modules module key => frozen version + * @param array}> $steps + * @param array $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 $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 + */ + 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 $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 + */ + 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 + */ + 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 $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, + ); + } +} diff --git a/app/Process/ProcessRunner.php b/app/Process/ProcessRunner.php new file mode 100644 index 0000000..d6a547a --- /dev/null +++ b/app/Process/ProcessRunner.php @@ -0,0 +1,197 @@ + 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 + */ + 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 $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 + */ + 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; + } +} diff --git a/app/Process/StepResult.php b/app/Process/StepResult.php new file mode 100644 index 0000000..7f77eb8 --- /dev/null +++ b/app/Process/StepResult.php @@ -0,0 +1,44 @@ + $reasons + */ + private function __construct(public string $outcome, public array $reasons = []) {} + + public static function ran(): self + { + return new self(self::RAN); + } + + /** + * @param list $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; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 0ff9e98..b18c48f 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,7 @@ namespace App\Providers; +use App\Process\ProcessCatalogue; use App\Support\StripImageMetadata; use App\Support\SystemSettings; use App\Tenancy\TenantConfig; @@ -21,6 +22,7 @@ public function register(): void { $this->app->singleton(TenantContext::class); $this->app->singleton(TenantConfig::class); + $this->app->singleton(ProcessCatalogue::class); } /** diff --git a/config/process.php b/config/process.php new file mode 100644 index 0000000..4bfefaa --- /dev/null +++ b/config/process.php @@ -0,0 +1,70 @@ + [ + Intake\IntakeRecord::class, + Intake\GuestDetails::class, + Intake\GuestDataRequest::class, + Intake\Hold::class, + Intake\AvailabilityCheck::class, + Intake\PortalBinding::class, + Intake\ChannelBlocks::class, + Offer\Information::class, + Offer\BindingOffer::class, + Offer\OfferAcceptance::class, + Settlement\BookingDocuments::class, + Settlement\StayConfirmation::class, + Settlement\CaseTasks::class, + Settlement\ChangeProposal::class, + Settlement\StayClosure::class, + Settlement\CommercialSettlement::class, + Money\PaymentMonitoring::class, + Money\PortalPayout::class, + Money\InternalPayment::class, + Stay\ArrivalDetails::class, + Stay\ArrivalInformation::class, + Stay\Stay::class, + Stay\ReviewRequest::class, + // Architecture proof, tester only (decision E7). + Loyalty\LoyaltyStatusCheck::class, + Loyalty\LoyaltyDiscount::class, + ], + + /* + | Module versions an older plan may name although the module has moved on: the current class serves them because the + | change was declared compatible (rule R2/R4 – e.g. a correction that rightly applies to running cases). + */ + 'compatible' => [ + 'offer.binding' => [1], + ], + + 'models' => [ + 'a1.offer' => [1 => Models\A1OfferModel::class], + 'a1.information' => [1 => Models\A1InformationModel::class], + 'a2.offer' => [1 => Models\A2OfferModel::class], + 'a2.information' => [1 => Models\A2InformationModel::class], + 'a3.portal_booking' => [1 => Models\A3PortalBookingModel::class], + 'a4.portal_booking' => [1 => Models\A4PortalBookingModel::class], + 'a5.portal_booking' => [1 => Models\A5PortalBookingModel::class], + 'a6.internal' => [1 => Models\A6InternalModel::class], + ], +]; diff --git a/tests/Feature/Process/LoyaltyArchitectureProofTest.php b/tests/Feature/Process/LoyaltyArchitectureProofTest.php new file mode 100644 index 0000000..0d2d065 --- /dev/null +++ b/tests/Feature/Process/LoyaltyArchitectureProofTest.php @@ -0,0 +1,155 @@ +travelTo(CarbonImmutable::parse('2026-10-23 18:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Storage::fake('local'); + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + config(['mail.default' => 'array']); + Mail::swap(new MailManager($this->app)); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org']); + Http::preventStrayRequests(); + } + + public function test_without_contributing_modules_the_case_price_is_exactly_the_calculator_price(): void + { + $booking = $this->request('neu@example.org'); + $stay = $this->stay(); + + $this->assertEquals(app(PriceCalculator::class)->calculate($this->property, $stay), app(CasePricing::class)->quote($booking, $stay)); + } + + public function test_a_returning_guest_gets_the_discount_line_after_the_status_check_and_before_the_price_is_fixed(): void + { + $this->formerStay('stamm@example.org'); + $booking = $this->loyaltyCase($this->request('stamm@example.org')); + + $quote = app(CasePricing::class)->quote($booking, $this->stay()); + $plain = app(PriceCalculator::class)->calculate($this->property, $this->stay()); + $discount = collect($quote->lines)->first(fn ($line): bool => $line->type === QuoteLineType::Discount); + + $this->assertNotNull($discount, 'the discount reads the status of the check before it'); + $this->assertSame(-(int) round($plain->rent() * 5 / 100), $discount->amount); + $this->assertStringContainsString('1 frühere Aufenthalte', $discount->label); + + // The offer fixes the price: the line is in the frozen quote, and the binding case gets no contribution any more. + app(SendOffer::class)->handle($booking->fresh()); + $booking->refresh(); + $this->assertSame($quote->total(), $booking->total); + $this->assertContains('discount', array_column($booking->quote['lines'], 'type')); + app(AcceptOffer::class)->handle($booking->fresh(), $booking->offer_version); + $this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status); + $this->assertEquals($plain, app(CasePricing::class)->quote($booking->fresh(), $this->stay()), 'no contribution after binding (R5)'); + $this->assertSame('loyalty_status', collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'loyalty_status')?->key); + } + + public function test_a_new_guest_and_an_unknown_status_get_no_discount_and_the_offer_is_never_held_back(): void + { + $new = $this->loyaltyCase($this->request('neu@example.org')); + $this->assertSame(app(PriceCalculator::class)->calculate($this->property, $this->stay())->total(), app(CasePricing::class)->quote($new, $this->stay())->total()); + + $unknown = $this->loyaltyCase($this->request('ohne@example.org', '2026-11-20', '2026-11-23')); + $unknown->guest->forceFill(['email' => null])->saveQuietly(); + $activity = collect(CaseActivities::for($unknown->fresh()))->firstWhere('key', 'loyalty_status'); + $this->assertStringContainsString('nicht feststellbar', $activity->detail); + } + + public function test_the_discount_is_not_combined_with_a_special_offer_discount(): void + { + $this->formerStay('stamm@example.org'); + $booking = $this->loyaltyCase($this->request('stamm@example.org')); + $quote = app(PriceCalculator::class)->calculate($this->property, $this->stay()) + ->withLine(new QuoteLine(QuoteLineType::Discount, 'Sonderangebot', 1, -1000, -1000)); + + $this->assertSame([], app(LoyaltyDiscount::class)->priceLines(CaseContext::of($booking), $quote)); + } + + public function test_loyalty_cannot_reach_a_real_case_and_leaves_the_other_models_unchanged(): void + { + $catalogue = app(ProcessCatalogue::class); + $using = array_keys(array_filter($catalogue->models(), fn ($model): bool => collect($model->variants())->contains(fn ($variant): bool => in_array('pricing.loyalty_discount', $model->modules($variant->key), true)))); + + $this->assertSame(['a1.offer'], $using, 'only the A1 offer model has the variant'); + $this->assertSame([], $catalogue->problems()); + foreach ($catalogue->models() as $key => $model) { + $this->assertNotContains('guest.loyalty_status', $model->modules('standard'), "{$key}: standard course unchanged"); + } + $this->expectExceptionMessage('nur im Prozess-Tester'); + ProcessPlan::freeze($this->request('neu@example.org')->process(), ['model' => 'a1.offer', 'variant' => 'loyalty']); + } + + private function loyaltyCase(Booking $booking): Booking + { + $plan = ProcessPlan::freeze($booking->process(), ['model' => 'a1.offer', 'variant' => 'loyalty'], sandbox: true); + $booking->forceFill(['profile' => [...$booking->profile, 'plan' => $plan->toArray()]])->saveQuietly(); + + return $booking->fresh(); + } + + private function formerStay(string $email): void + { + $guest = Guest::query()->create(['tenant_id' => $this->property->tenant_id, 'first_name' => 'Stamm', 'last_name' => 'Gast', 'email' => 'alt-'.$email]); + Booking::factory()->for($this->property)->create(['guest_id' => $guest->id, 'status' => BookingStatus::Completed, 'arrival' => '2025-08-01', 'departure' => '2025-08-08']); + $guest->forceFill(['email' => $email])->saveQuietly(); + } + + private function request(string $email, string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking + { + return app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email, 'street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']); + } + + private function stay(): StayRequest + { + return new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2); + } +} diff --git a/tests/Feature/Process/ProcessCoreTest.php b/tests/Feature/Process/ProcessCoreTest.php new file mode 100644 index 0000000..810f939 --- /dev/null +++ b/tests/Feature/Process/ProcessCoreTest.php @@ -0,0 +1,167 @@ +travelTo(CarbonImmutable::parse('2026-10-23 18:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Storage::fake('local'); + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + config(['mail.default' => 'array']); + Mail::swap(new MailManager($this->app)); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org', + 'process_defaults' => ['processing' => 'automatic', 'clarification_hold_auto_minutes' => 120, 'data_request_mode' => 'automatic']]); + Http::preventStrayRequests(); + } + + public function test_the_catalogue_is_consistent(): void + { + $this->assertSame([], app(ProcessCatalogue::class)->problems()); + } + + public function test_a_new_case_freezes_its_plan(): void + { + $booking = $this->request(['street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']); + + $plan = $booking->fresh()->profile['plan']; + $this->assertSame(['a1.offer', 1, 'standard', ProcessPlan::DERIVED], [$plan['model'], $plan['model_version'], $plan['variant'], $plan['source']]); + $this->assertSame(2, $plan['modules']['offer.binding']); + $this->assertSame('Verbindliches Angebot', $plan['labels']['offer.binding']); + $this->assertArrayNotHasKey('guest.loyalty_status', $plan['modules'], 'tester-only modules never enter a real plan'); + } + + public function test_clarification_hold_runs_on_while_the_data_request_waits_and_the_late_answer_brings_the_offer(): void + { + $booking = $this->request([]); + + // The data request went out, the offer waits for the address, the clarification hold runs independently. + $context = CaseContext::of($booking->fresh()); + $this->assertSame([BookingStatus::Reserved, Booking::HOLD_CLARIFICATION], [$booking->status, $booking->hold_purpose]); + $this->assertSame(StepState::Waiting, app(Hold::class)->state($context)); + $this->assertSame(DataRequest::OPEN, $booking->openDataRequest()->status); + $this->assertSame(ActivityState::Later, $this->activity($booking, 'offer')->state); + $this->assertSame(ActivityState::Waiting, $this->activity($booking, 'contact')->state); + + // The hold expires; the request stays open for its details (only offer holds expire). + $this->travel(125)->minutes(); + $this->artisan('bookings:expire-holds')->assertSuccessful(); + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + $this->assertSame(StepState::Done, app(Hold::class)->state(CaseContext::of($booking->fresh()))); + + // The guest answers later; the offer becomes ready and goes out with a new offer hold. + app(ContributeCaseFacts::class)->handle($booking->fresh(), ['guest.street' => 'Lindenallee 12', 'guest.postal_code' => '10115', 'guest.city' => 'Berlin', 'guest.country' => 'DE'], FactSource::GuestLink); + $booking->refresh(); + $this->assertSame([BookingStatus::OfferSent, Booking::HOLD_OFFER], [$booking->status, $booking->hold_purpose]); + $this->assertSame(DataRequest::COMPLETED, $booking->dataRequests()->sole()->status); + } + + public function test_an_external_address_check_waits_without_holding_back_the_offer(): void + { + config([ + 'process.modules' => [...config('process.modules'), AddressVerification::class], + 'process.models' => [...config('process.models'), 'a1.offer_address' => [1 => A1WithAddressCheck::class]], + ]); + $this->app->forgetInstance(ProcessCatalogue::class); + AddressVerification::$serviceAvailable = false; + $booking = $this->request(['street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE'], automatic: false); + $plan = ProcessPlan::freeze($booking->process(), ['model' => 'a1.offer_address', 'variant' => 'address_check']); + $booking->forceFill(['profile' => [...$booking->profile, 'plan' => $plan->toArray()], 'processing_mode' => 'automatic'])->saveQuietly(); + + $result = app(ProcessRunner::class)->advance($booking->fresh()); + + $this->assertTrue($result->ran('offer.binding'), 'the offer does not depend on the address check'); + $this->assertSame(ActivityState::Waiting, $this->activity($booking, 'address_check')->state); + $this->assertSame([], app(ProcessCatalogue::class)->problems(), 'a new module and a variant fit without changing other models'); + } + + public function test_a_finished_case_of_a_retired_version_stays_readable(): void + { + $booking = $this->request(['street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']); + $plan = $booking->profile['plan']; + // An older release: model version 0 and a module that no longer exists. + $plan['model_version'] = 0; + $plan['modules'] = ['intake.record' => 1, 'old.welcome_call' => 1, ...$plan['modules']]; + $plan['labels']['old.welcome_call'] = 'Begrüßungsanruf'; + $booking->forceFill(['status' => BookingStatus::Declined, 'profile' => [...$booking->profile, 'plan' => $plan]])->saveQuietly(); + + $activities = CaseActivities::for($booking->fresh()); + + $this->assertTrue(ProcessPlan::of($booking->fresh())->isHistoric()); + $this->assertSame('Begrüßungsanruf (frühere Fassung)', collect($activities)->firstWhere('key', 'old.welcome_call')->label); + $this->assertSame('done', collect($activities)->firstWhere('key', 'offer')->state->value); + $this->assertNotNull(CaseActivities::situation($booking->fresh())); + } + + public function test_a_tester_only_variant_is_refused_for_real_cases(): void + { + $booking = $this->request(['street' => 'Weg 1', 'postal_code' => '10115', 'city' => 'Berlin', 'country' => 'DE']); + + $this->expectExceptionMessage('nur im Prozess-Tester'); + ProcessPlan::freeze($booking->process(), ['model' => 'a1.offer', 'variant' => 'loyalty']); + } + + /** + * @param array $address + */ + private function request(array $address, bool $automatic = true): Booking + { + if (! $automatic) { + Settings::tenant()->update(['process_defaults' => ['processing' => 'manual']]); + } + + return app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', ...$address]); + } + + private function activity(Booking $booking, string $key): Activity + { + return collect(CaseActivities::for($booking->fresh()))->firstWhere('key', $key) ?? $this->fail("No activity {$key}"); + } +} diff --git a/tests/Feature/Process/ProcessRunnerTest.php b/tests/Feature/Process/ProcessRunnerTest.php new file mode 100644 index 0000000..56d37fa --- /dev/null +++ b/tests/Feature/Process/ProcessRunnerTest.php @@ -0,0 +1,207 @@ +seed(PropertySeeder::class); + FakeModule::reset(); + config([ + 'process.modules' => [...config('process.modules'), FakeModuleA::class, FakeModuleB::class, FakeModuleC::class, FakeModuleD::class], + 'process.models' => [...config('process.models'), 'test.model' => [1 => FakeModel::class]], + ]); + $this->app->forgetInstance(ProcessCatalogue::class); + $this->booking = Booking::factory()->for(Property::sole())->reserved()->create(['intake' => 'inquiry']); + $this->plan('standard'); + } + + public function test_a_hard_dependency_holds_the_step_back_while_an_independent_step_goes_on(): void + { + FakeModule::$script = [ + 'test.a' => ['state' => StepState::Waiting, 'due' => false], + 'test.b' => ['requires' => [Dependency::hard('test.a')]], + 'test.c' => [], + ]; + + $result = $this->advance(); + + $this->assertSame(['test.c'], FakeModule::$runs, 'the waiting step holds back only what depends on it hard'); + $this->assertSame(['Wartet auf: Testschritt test.a.'], $result->reasons('test.b')); + } + + public function test_a_hard_dependency_cannot_be_lifted_by_the_waiting_step(): void + { + // Whatever the waiting step declares, the dependent decides: hard is hard. + FakeModule::$script = [ + 'test.a' => ['state' => StepState::Problem, 'due' => false], + 'test.b' => ['requires' => [Dependency::hard('test.a')]], + ]; + + $this->advance(); + + $this->assertNotContains('test.b', FakeModule::$runs); + } + + public function test_a_soft_dependency_orders_steps_but_does_not_wait(): void + { + FakeModule::$script = [ + 'test.a' => ['requires' => [Dependency::soft('test.c')]], + 'test.c' => [], + ]; + $this->advance(); + $this->assertSame(['test.c', 'test.a'], FakeModule::$runs, 'both due: the soft dependency goes first'); + + FakeModule::reset(); + FakeModule::$script = [ + 'test.a' => ['requires' => [Dependency::soft('test.c')]], + 'test.c' => ['state' => StepState::Waiting, 'due' => false], + ]; + $this->advance(); + $this->assertSame(['test.a'], FakeModule::$runs, 'the soft dependency waits: the step goes on'); + } + + public function test_readiness_is_determined_anew_after_every_state_change(): void + { + FakeModule::$script = [ + // A's run completes what B needs and makes C superfluous. + 'test.a' => ['run' => function (): ?StepResult { + FakeModule::$script['test.b']['state'] = StepState::Open; + FakeModule::$script['test.c']['due'] = false; + + return null; + }], + 'test.b' => ['state' => StepState::Later, 'due' => true, 'requires' => [Dependency::hard('test.a')]], + 'test.c' => [], + ]; + + $this->advance(); + + $this->assertSame(['test.a', 'test.b'], FakeModule::$runs, 'B became ready after A; C was ready before A ran, but no longer afterwards'); + } + + public function test_conditional_steps_and_switched_off_optional_steps_are_skipped(): void + { + FakeModule::$script = ['test.a' => ['applies' => false], 'test.b' => [], 'test.c' => []]; + $this->plan('standard', ['test.c' => ['on' => false]]); + + $this->advance(); + + // test.c is a fake module without the optional toggle: a mandatory step cannot be switched off. + $this->assertSame(['test.b', 'test.c'], FakeModule::$runs); + } + + public function test_a_failing_step_is_reported_and_independent_steps_go_on(): void + { + FakeModule::$script = ['test.a' => ['run' => fn () => FakeModule::fail()], 'test.b' => []]; + + $result = $this->advance(); + + $this->assertSame(['test.a', 'test.b'], FakeModule::$runs); + $this->assertSame(['Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.'], $result->reasons('test.a')); + $this->assertTrue($result->ran('test.b')); + } + + public function test_a_second_advance_has_no_effect(): void + { + FakeModule::$script = ['test.a' => [], 'test.b' => []]; + $this->advance(); + FakeModule::$runs = []; + + $this->advance(); + + $this->assertSame([], FakeModule::$runs, 'every step is done; nothing is due'); + } + + public function test_a_step_runs_once_per_advance_even_if_it_stays_due(): void + { + FakeModule::$script = ['test.a' => ['run' => fn (): StepResult => StepResult::blocked(['noch nicht'])]]; + + $result = $this->advance(); + + $this->assertSame(['test.a'], FakeModule::$runs); + $this->assertSame(['noch nicht'], $result->reasons('test.a')); + } + + public function test_only_steps_that_declare_the_trigger_are_considered(): void + { + FakeModule::$script = ['test.a' => []]; + + app(ProcessRunner::class)->advance($this->booking, 'request.created'); + + $this->assertSame([], FakeModule::$runs); + } + + public function test_a_variant_inserts_its_module_at_the_extension_point(): void + { + FakeModule::$script = ['test.a' => [], 'test.b' => [], 'test.c' => [], 'test.d' => []]; + $this->plan('extra'); + + $this->advance(); + + $this->assertSame(['test.a', 'test.b', 'test.d', 'test.c'], FakeModule::$runs); + } + + public function test_an_open_portal_report_suspends_outward_steps_only(): void + { + FakeModule::$script = ['test.a' => ['outward' => true], 'test.b' => []]; + BookingTask::query()->create(['tenant_id' => $this->booking->tenant_id, 'booking_id' => $this->booking->id, 'kind' => BookingTaskKind::PortalCancellationReported, 'status' => BookingTaskStatus::Open, 'title' => 'Portal meldet Stornierung']); + + $result = $this->advance(); + + $this->assertSame(['test.b'], FakeModule::$runs, 'internal steps go on (decision O4)'); + $this->assertStringContainsString('warten, bis die Meldung', $result->reasons('test.a')[0]); + } + + /** + * @param array> $steps + */ + private function plan(string $variant, array $steps = []): void + { + $model = app(ProcessCatalogue::class)->model('test.model'); + $modules = array_fill_keys($model->modules($variant), 1); + $plan = new ProcessPlan('test.model', 1, $variant, $modules, $steps, ProcessPlan::CONFIGURED); + $this->booking->forceFill(['profile' => [...(array) $this->booking->profile, 'plan' => $plan->toArray()]])->saveQuietly(); + } + + private function advance(): AdvanceResult + { + return app(ProcessRunner::class)->advance($this->booking->fresh(), 'test'); + } +} diff --git a/tests/Fixtures/process/behaviour/a1_dates_taken.json b/tests/Fixtures/process/behaviour/a1_dates_taken.json index ef300e0..3bcf040 100644 --- a/tests/Fixtures/process/behaviour/a1_dates_taken.json +++ b/tests/Fixtures/process/behaviour/a1_dates_taken.json @@ -323,9 +323,9 @@ { "key": "offer", "label": "Angebot senden (automatisch)", - "state": "open", - "detail": "Zeitraum reserviert bis 23.10.2026, 18:30 Uhr", - "action": "sendOffer" + "state": "problem", + "detail": "Der Zeitraum ist inzwischen belegt.", + "action": null }, { "key": "acceptance", diff --git a/tests/Fixtures/process/intended.md b/tests/Fixtures/process/intended.md index aa3e595..eb43011 100644 --- a/tests/Fixtures/process/intended.md +++ b/tests/Fixtures/process/intended.md @@ -6,6 +6,7 @@ # Beabsichtigte Abweichungen von der v0.11-Referenz |---|---|---|---|---| | I-001 | Ereignistypen der Schrittdetails kommen aus der Moduldefinition statt aus `ActivityDetails::EVENT_TYPES` | eine Quelle (Architektur `02` §7.7) | `ActivityDetailsTest` unverändert grün | keine (gleiches Ergebnis) | | I-002 | Offene, einem Vorgang zugeordnete Portalmeldung (Storno/Änderung) setzt automatische **Außenwirkungen** aus: Unterlagen, Erinnerungen, Anreiseinformation | Entscheidung O4 | `PortalReportSuspendsAutomationTest` | `portal_mail_cancellation` (nur wenn Außenwirkungen anstanden) | -| I-003 | Zeit-Actions (`ExpireReservations`, `RequestCaseData::handOver`) rufen danach `ProcessRunner::advance` für den Vorgang | K1: Wiederaufnahme ohne neuen Auslöser | `RunnerResumesAfterDeadlineTest` | keine erwartet | -| I-004 | Angebotsschritt bei belegtem Zeitraum = `problem` | Fehler F-001 | `OfferModuleTest::taken_dates_are_a_problem` | `a1_dates_taken.answer_dates_taken` | -| I-005 | Detail des Angebotsschritts zeigt den tatsächlichen Reservierungszustand | Fehler F-002 | `OfferModuleTest::expired_hold_is_not_shown_as_reserved` | `a1_dates_taken.*`, `a1_missing_address.clarification_expired`, `a1_missing_address.first_reminder` | +| I-003 | ~~Zeit-Actions rufen danach `advance`~~ – **entfällt**: `bookings:auto-offers` bewertet offene Anfragen alle 5 Minuten über den Runner neu; `ExpireReservations` und `handOver` machen keinen Schritt bereit | – | – | – | +| I-004 | Angebotsschritt bei belegtem Zeitraum = `problem`, ohne Senden-Aktion | Fehler F-001 | `BehaviourComparisonTest` (`a1_dates_taken`, neu aufgenommen) | `a1_dates_taken.answer_dates_taken` | +| I-005 | Detail des Angebotsschritts zeigt den tatsächlichen Reservierungszustand | Fehler F-002 | `BehaviourComparisonTest` (`a1_dates_taken`), `OngoingCaseRegressionTest` (`legacy_migration_offer`) | `a1_dates_taken.answer_dates_taken`; Bestandsfall `legacy_migration_offer` | +| I-006 | Technischer Fehler eines automatischen Schritts: einheitlicher Text „Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.“ je Schritt (vorher je Aufrufer eigener Text); `CreateReservation` behält seinen Text, wenn der Runner selbst scheitert | ein Ablaufkern | `ProcessRunnerTest::test_a_failing_step_is_reported_and_independent_steps_go_on` | keine (kein Fehlerfall in der Referenz) | diff --git a/tests/Fixtures/process/ongoing/cases.json b/tests/Fixtures/process/ongoing/cases.json index 18618a8..3b42681 100644 --- a/tests/Fixtures/process/ongoing/cases.json +++ b/tests/Fixtures/process/ongoing/cases.json @@ -2356,7 +2356,7 @@ [ "offer", "open", - "Zeitraum reserviert bis 25.10.2026, 17:00 Uhr", + "Reservierung abgelaufen am 25.10.2026, 17:00 Uhr – Zeitraum nicht reserviert", "sendOffer" ], [ diff --git a/tests/Support/Process/A1WithAddressCheck.php b/tests/Support/Process/A1WithAddressCheck.php new file mode 100644 index 0000000..a30cbbc --- /dev/null +++ b/tests/Support/Process/A1WithAddressCheck.php @@ -0,0 +1,49 @@ + true]; + } + + public function variants(): array + { + return [Variant::make('standard', 'Standard'), Variant::make('address_check', 'Mit Adressprüfung')->insert(Point::AfterGuestIdentified, 'guest.address_verification')]; + } +} diff --git a/tests/Support/Process/AddressVerification.php b/tests/Support/Process/AddressVerification.php new file mode 100644 index 0000000..5c0674d --- /dev/null +++ b/tests/Support/Process/AddressVerification.php @@ -0,0 +1,77 @@ +state($case); + + return [new Activity('address_check', 'Anschrift extern prüfen', $state === StepState::Done ? ActivityState::Done : ActivityState::Waiting, self::$serviceAvailable ? null : 'Adressdienst nicht erreichbar – neuer Versuch später')]; + } + + public function state(CaseContext $case): ?StepState + { + return self::$serviceAvailable ? StepState::Done : StepState::Waiting; + } + + public function due(CaseContext $case): bool + { + return ! self::$serviceAvailable; + } + + public function blockers(CaseContext $case): array + { + return []; + } + + public function run(CaseContext $case): StepResult + { + return StepResult::blocked(['Adressdienst nicht erreichbar.']); + } + + public function isOutward(): bool + { + return false; + } +} diff --git a/tests/Support/Process/FakeModel.php b/tests/Support/Process/FakeModel.php new file mode 100644 index 0000000..9203c21 --- /dev/null +++ b/tests/Support/Process/FakeModel.php @@ -0,0 +1,62 @@ +insert(Point::BeforePriceFixing, 'test.d')]; + } +} diff --git a/tests/Support/Process/FakeModule.php b/tests/Support/Process/FakeModule.php new file mode 100644 index 0000000..ef706fd --- /dev/null +++ b/tests/Support/Process/FakeModule.php @@ -0,0 +1,101 @@ +, run?: callable(): ?StepResult, outward?: bool, applies?: bool}> + */ + public static array $script = []; + + /** @var list */ + public static array $runs = []; + + public static function reset(): void + { + self::$script = []; + self::$runs = []; + } + + public static function version(): int + { + return 1; + } + + public static function definition(): ModuleDefinition + { + return new ModuleDefinition( + label: 'Testschritt '.static::key(), + purpose: 'Test', + phase: 'P01', + requires: self::$script[static::key()]['requires'] ?? [], + triggers: ['automation', 'test'], + modes: ['automatic'], + ); + } + + public function applies(CaseContext $case): bool + { + return array_key_exists(static::key(), self::$script) && (self::$script[static::key()]['applies'] ?? true); + } + + public function activities(CaseContext $case): array + { + $state = $this->state($case) ?? StepState::Open; + + return [new Activity(static::key(), static::key(), ActivityState::from($state->value))]; + } + + public function state(CaseContext $case): ?StepState + { + return self::$script[static::key()]['state'] ?? StepState::Open; + } + + public function due(CaseContext $case): bool + { + return self::$script[static::key()]['due'] ?? ($this->state($case) === StepState::Open); + } + + public function blockers(CaseContext $case): array + { + return []; + } + + public function run(CaseContext $case): StepResult + { + self::$runs[] = static::key(); + $run = self::$script[static::key()]['run'] ?? null; + $result = $run === null ? null : $run(); + if ($result === null) { + self::$script[static::key()]['state'] = StepState::Done; + } + + return $result ?? StepResult::ran(); + } + + public function isOutward(): bool + { + return self::$script[static::key()]['outward'] ?? false; + } + + public static function fail(): never + { + throw new RuntimeException('Testfehler'); + } +} diff --git a/tests/Support/Process/FakeModuleA.php b/tests/Support/Process/FakeModuleA.php new file mode 100644 index 0000000..ba22f9c --- /dev/null +++ b/tests/Support/Process/FakeModuleA.php @@ -0,0 +1,11 @@ +