Merge feature/prozessarchitektur-v2: kontrolliert modulare Prozessarchitektur V2 (Prozesskern, Kanalkonfigurator, Prozess-Tester, Kanalereignisse)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
79f3344568
185 files changed
+40492
-503
No files matched your search
@@ -5,6 +5,7 @@
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Models\ProcessTestRun;
|
||||
|
||||
/**
|
||||
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
|
||||
@@ -44,6 +45,9 @@ public function handle(): int
|
||||
|
||||
private function purgeOperationalData(): void
|
||||
{
|
||||
// Process tester reports (synthetic data only, decision O3).
|
||||
ProcessTestRun::query()->where('created_at', '<', now()->subDays(config('fewo.retention.process_test_run_days')))->delete();
|
||||
|
||||
PortalEmail::query()
|
||||
->whereNotNull('excerpt')
|
||||
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Models\Channel;
|
||||
use App\Process\ChannelProcessConfiguration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Saves the process of a channel for one intake kind (Kanal › Ablauf, docs/Prozessarchitektur/Architektur/03): the
|
||||
* chosen model and variant, the step switches and the step settings – in channels.process_overrides[intake], next to
|
||||
* the existing settings, so their inheritance stays as it is. Refuses everything the configuration does not admit
|
||||
* (mandatory steps off, responsibilities the model does not allow, tester-only variants). Changes apply to new cases
|
||||
* only (decision E3): running cases keep their frozen plan.
|
||||
*/
|
||||
class ConfigureChannelProcess
|
||||
{
|
||||
public function __construct(private ChannelProcessConfiguration $configuration) {}
|
||||
|
||||
/**
|
||||
* @param array{model: string, variant?: string, steps?: array<string, array{on?: bool}>, settings?: array<string, mixed>} $draft
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function handle(Channel $channel, IntakeKind $intake, array $draft, ?string $by = null): Channel
|
||||
{
|
||||
$problems = $this->configuration->problems($channel, $intake, $draft);
|
||||
if ($problems !== []) {
|
||||
throw ValidationException::withMessages(['process' => $problems]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($channel, $intake, $draft, $by): Channel {
|
||||
$channel = Channel::query()->lockForUpdate()->findOrFail($channel->id);
|
||||
$overrides = (array) ($channel->process_overrides ?? []);
|
||||
$current = (array) ($overrides[$intake->value] ?? []);
|
||||
|
||||
$settings = [];
|
||||
foreach (ProcessSetting::cases() as $setting) {
|
||||
$value = array_key_exists($setting->value, (array) ($draft['settings'] ?? [])) ? $setting->normalize($draft['settings'][$setting->value]) : $setting->normalize($current[$setting->value] ?? null);
|
||||
if ($value !== null && in_array($intake, $setting->channelIntakes(), true)) {
|
||||
$settings[$setting->value] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$steps = [];
|
||||
foreach ((array) ($draft['steps'] ?? []) as $module => $step) {
|
||||
if (array_key_exists('on', $step) && $step['on'] === false) {
|
||||
$steps[$module] = ['on' => false];
|
||||
}
|
||||
}
|
||||
|
||||
$overrides[$intake->value] = [
|
||||
...$settings,
|
||||
'model' => $draft['model'],
|
||||
'variant' => $draft['variant'] ?? 'standard',
|
||||
'steps' => $steps,
|
||||
'configured_at' => now()->toIso8601String(),
|
||||
'configured_by' => $by ?? auth()->user()?->name,
|
||||
];
|
||||
$channel->update(['process_overrides' => $overrides]);
|
||||
|
||||
return $channel;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
use App\Enums\Responsibility;
|
||||
use App\Mail\ReviewRequest;
|
||||
use App\Models\Booking;
|
||||
use App\Process\OutwardSuspension;
|
||||
use App\Process\ProcessPlan;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
@@ -27,7 +29,10 @@ public function handle(): int
|
||||
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
||||
->with('guest')
|
||||
->get()
|
||||
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord);
|
||||
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord
|
||||
// The step can be switched off per channel (Kanal › Ablauf); an open portal report holds it back (O4).
|
||||
&& ProcessPlan::of($booking)->enabled('review.request')
|
||||
&& OutwardSuspension::reason($booking) === null);
|
||||
|
||||
foreach ($bookings as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
use App\Mail\ArrivalInformation;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Process\OutwardSuspension;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
@@ -63,7 +64,9 @@ public function handle(): array
|
||||
->whereDate('arrival', '>=', $today)
|
||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
|
||||
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord
|
||||
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore())));
|
||||
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore()))
|
||||
// Decision O4: an open portal report of a cancellation or change holds the message back until clarified.
|
||||
&& OutwardSuspension::reason($booking) === null);
|
||||
foreach ($arrivals as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
|
||||
$booking->update(['arrival_info_sent_at' => now()]);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -111,7 +111,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
|
||||
*/
|
||||
private function checkEvidence(BlockedPeriod $evidence): ?Booking
|
||||
{
|
||||
if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) {
|
||||
if (! in_array($evidence->source, ['channel', 'email', 'api'], true) || $evidence->channel_id === null) {
|
||||
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
|
||||
}
|
||||
if ($evidence->occupationKind() === OccupationKind::Block) {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Contracts;
|
||||
|
||||
use App\Channels\Events\ChannelEvent;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Capability of a connector whose portal offers an interface for bookings, cancellations, changes and amounts
|
||||
* (Architektur V2, 02 §8.4). The events go to ChannelEventHandler; the connector itself decides nothing. Network access
|
||||
* only through the Http facade (SideEffectPathsTest), so the process tester can replace it.
|
||||
*/
|
||||
interface DeliversEvents
|
||||
{
|
||||
/**
|
||||
* @return list<ChannelEvent>
|
||||
*/
|
||||
public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Contracts;
|
||||
|
||||
use App\Channels\Events\ChannelEvent;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Capability of a connector whose portal pushes events (webhook). The connector verifies the signature (authenticity
|
||||
* of the origin) and translates the payload; the business decision stays with ChannelEventHandler.
|
||||
*/
|
||||
interface ReceivesWebhooks
|
||||
{
|
||||
/**
|
||||
* @return list<ChannelEvent> empty when the signature is not valid
|
||||
*/
|
||||
public function receive(Channel $channel, Request $request): array;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
/**
|
||||
* The portal reports a cancellation of a known booking: a task on the case, never a cancellation, refund or fee (E-019).
|
||||
*/
|
||||
final readonly class BookingCancelledByChannel extends ChannelEvent
|
||||
{
|
||||
public function __construct(Provenance $provenance, public ?string $note = null)
|
||||
{
|
||||
parent::__construct($provenance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* The portal reports other dates or guests of a known booking: a task with the comparison, never a change of the booking.
|
||||
*/
|
||||
final readonly class BookingChangedByChannel extends ChannelEvent
|
||||
{
|
||||
public function __construct(Provenance $provenance, public ?CarbonImmutable $arrival = null, public ?CarbonImmutable $departure = null, public ?int $guests = null)
|
||||
{
|
||||
parent::__construct($provenance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
/**
|
||||
* A normalised business event of a portal, independent of its transport (Architektur V2, K4/K10). Future API or
|
||||
* webhook adapters deliver these; ChannelEventHandler maps them onto the existing intake, so duplicates, origin and the
|
||||
* external binding are judged in one place for every transport.
|
||||
*/
|
||||
abstract readonly class ChannelEvent
|
||||
{
|
||||
public function __construct(public Provenance $provenance) {}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use App\Actions\RecordPortalAmounts;
|
||||
use App\Channels\Intake\IntakeDecision;
|
||||
use App\Channels\Intake\PortalIntake;
|
||||
use App\Enums\IntakeOutcome;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\IntakeObservation;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Money;
|
||||
use App\Tenancy\TenantContext;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* The one entry of channel events (docs/Prozessarchitektur/Architektur/02 §8.3–8.4): maps each normalised event onto
|
||||
* the existing intake, so iCal, mail and future APIs are judged by the same rules – duplicates and certainty in
|
||||
* PortalIntake, amounts in RecordPortalAmounts, reports about known cases as tasks. Contains no decision rules of its
|
||||
* own and never changes a binding booking (stage M4 needs the landlord's action).
|
||||
*/
|
||||
final class ChannelEventHandler
|
||||
{
|
||||
public function __construct(private PortalIntake $intake, private RecordPortalAmounts $amounts) {}
|
||||
|
||||
public function handle(ChannelEvent $event): ?IntakeDecision
|
||||
{
|
||||
$channel = $event->provenance->channel;
|
||||
if (! $channel->isPortal() || $channel->tenant_id === null) {
|
||||
throw new InvalidArgumentException('Kanalereignisse kommen nur von Portalen.');
|
||||
}
|
||||
|
||||
return app(TenantContext::class)->run($channel->tenant, fn (): ?IntakeDecision => match (true) {
|
||||
$event instanceof IncomingBooking => $this->booking($event),
|
||||
$event instanceof BookingCancelledByChannel => $this->report($event, IntakeOutcome::CancellationSignal, $channel->name.' meldet über die Schnittstelle eine Stornierung'.($event->note ? ' ('.$event->note.')' : '').'. Bitte prüfen Sie die Buchung und die nächsten Schritte.'),
|
||||
$event instanceof BookingChangedByChannel => $this->report($event, IntakeOutcome::ChangeSignal, $channel->name.' meldet über die Schnittstelle eine Änderung'.($event->arrival && $event->departure ? ': '.$event->arrival->format('d.m.').'–'.$event->departure->format('d.m.Y') : '').($event->guests ? ', '.$event->guests.' Personen' : '').'. Die Buchung bleibt unverändert, bis Sie entscheiden.'),
|
||||
$event instanceof PaymentReported => $this->payment($event),
|
||||
$event instanceof PayoutReported => $this->payout($event),
|
||||
default => throw new InvalidArgumentException('Unbekanntes Kanalereignis '.$event::class.'.'),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A booking binding at the portal: blocked like a booking e-mail – source api, reference in the identifier – and judged
|
||||
* by PortalIntake – the same case, never a second one; a case only when certain.
|
||||
*/
|
||||
private function booking(IncomingBooking $event): IntakeDecision
|
||||
{
|
||||
$provenance = $event->provenance;
|
||||
$reference = $provenance->externalReference;
|
||||
// The reference is the identity of the block (as for booking mails); without one it is never taken as a reference.
|
||||
$uid = $reference !== null ? 'api:'.$reference : 'api-event:'.$provenance->evidenceRef;
|
||||
$block = $provenance->channel->blockedPeriods()->withTrashed()->where('source', 'api')->where('external_uid', $uid)->first()
|
||||
?? new BlockedPeriod(['property_id' => $provenance->channel->property_id, 'source' => 'api', 'reason' => $provenance->channel->name, 'external_uid' => $uid]);
|
||||
$block->fill(['starts_on' => $event->arrival->toDateString(), 'ends_on' => $event->departure->toDateString()]);
|
||||
if ($block->trashed()) {
|
||||
$block->restore();
|
||||
}
|
||||
$provenance->channel->blockedPeriods()->save($block);
|
||||
|
||||
return $this->intake->process($block->fresh(), IntakeObservation::SOURCE_API);
|
||||
}
|
||||
|
||||
private function report(BookingCancelledByChannel|BookingChangedByChannel $event, IntakeOutcome $outcome, string $message): ?IntakeDecision
|
||||
{
|
||||
$case = $this->case($event);
|
||||
if ($case === null) {
|
||||
return new IntakeDecision(IntakeOutcome::Clarify, ['Keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||
}
|
||||
$this->intake->reportToCase($event->provenance->channel, $case, $outcome, $message, 'api:'.$event->provenance->evidenceRef, IntakeObservation::SOURCE_API);
|
||||
|
||||
return new IntakeDecision($outcome, [$message], $case, reference: $event->provenance->externalReference);
|
||||
}
|
||||
|
||||
private function payment(PaymentReported $event): ?IntakeDecision
|
||||
{
|
||||
$case = $this->case($event);
|
||||
if ($case === null) {
|
||||
return new IntakeDecision(IntakeOutcome::Clarify, ['Zahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||
}
|
||||
$this->amounts->handle($case, null, [], [['amount' => $event->amount, 'paid_on' => $event->paidOn->toDateString()]], $event->provenance->channel->name);
|
||||
|
||||
return new IntakeDecision(IntakeOutcome::Link, ['Zahlung des Gastes laut Portal erfasst (kein Eingang auf unserem Konto).'], $case);
|
||||
}
|
||||
|
||||
private function payout(PayoutReported $event): ?IntakeDecision
|
||||
{
|
||||
$case = $this->case($event);
|
||||
if ($case === null) {
|
||||
return new IntakeDecision(IntakeOutcome::Clarify, ['Auszahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||
}
|
||||
if ($event->executed) {
|
||||
// Evidence level "laut Portal erledigt" – the receipt on our account is recorded by the landlord (O5).
|
||||
CaseLog::record($case, 'evidence', 'Auszahlung laut '.$event->provenance->channel->name.' ausgeführt: '.Money::format($event->amount).' am '.$event->paidOn->format('d.m.Y').' – Eingang auf unserem Konto noch nicht erfasst.', data: ['module' => 'portal.payout', 'level' => 'stated_by_portal', 'source' => $event->provenance->transport, 'ref' => $event->provenance->evidenceRef], actor: $event->provenance->channel->name);
|
||||
} else {
|
||||
$this->amounts->handle($case, null, [['kind' => 'payout_announced', 'amount' => $event->amount, 'due_on' => $event->paidOn->toDateString()]], [], $event->provenance->channel->name);
|
||||
}
|
||||
|
||||
return new IntakeDecision(IntakeOutcome::Link, ['Auszahlung laut Portal vermerkt.'], $case);
|
||||
}
|
||||
|
||||
/**
|
||||
* The binding case of the event: by the portal's booking reference only (no merging by dates for reports).
|
||||
*/
|
||||
private function case(ChannelEvent $event): ?Booking
|
||||
{
|
||||
$reference = $event->provenance->externalReference;
|
||||
$case = $reference === null ? null : $this->intake->caseByReference($event->provenance->channel, $reference);
|
||||
|
||||
return $case !== null && $case->isBinding() ? $case : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* A booking binding at the portal (M1/M2): its dates and reference; becomes a case only through PortalIntake's certainty rules.
|
||||
*/
|
||||
final readonly class IncomingBooking extends ChannelEvent
|
||||
{
|
||||
public function __construct(Provenance $provenance, public CarbonImmutable $arrival, public CarbonImmutable $departure, public ?int $guests = null, public ?int $total = null)
|
||||
{
|
||||
parent::__construct($provenance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* The portal reports a payment of the guest to the portal: recorded "laut Portal" (GuestViaPortal), never as money on our account.
|
||||
*/
|
||||
final readonly class PaymentReported extends ChannelEvent
|
||||
{
|
||||
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn)
|
||||
{
|
||||
parent::__construct($provenance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* The portal announces or reports a payout to us: "laut Portal" only – a received payout is recorded by the landlord (decision O5).
|
||||
*/
|
||||
final readonly class PayoutReported extends ChannelEvent
|
||||
{
|
||||
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn, public bool $executed = false)
|
||||
{
|
||||
parent::__construct($provenance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Events;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Where a channel event came from (docs/Prozessarchitektur/Architektur/02 §8.2): channel, transport and whether its
|
||||
* origin is technically authenticated (a signed webhook, an API call with credentials). It says nothing about whether a
|
||||
* business action really happened – that is evidence, which only the landlord or a checked receipt provides (M3).
|
||||
*/
|
||||
final readonly class Provenance
|
||||
{
|
||||
public const AUTHENTICATED = 'authenticated';
|
||||
|
||||
public const UNAUTHENTICATED = 'unauthenticated';
|
||||
|
||||
public function __construct(
|
||||
public Channel $channel,
|
||||
public string $transport,
|
||||
public string $authenticity,
|
||||
public ?string $externalReference,
|
||||
public string $evidenceRef,
|
||||
public CarbonImmutable $receivedAt,
|
||||
) {}
|
||||
|
||||
public function isAuthenticated(): bool
|
||||
{
|
||||
return $this->authenticity === self::AUTHENTICATED;
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ public function evaluate(BlockedPeriod $block): IntakeDecision
|
||||
$channel = $block->channel;
|
||||
$reference = self::reference($block);
|
||||
|
||||
if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) {
|
||||
if ($channel === null || ! in_array($block->source, ['channel', 'email', 'api'], true)) {
|
||||
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
|
||||
}
|
||||
if ($block->trashed()) {
|
||||
@@ -246,6 +246,15 @@ public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, Por
|
||||
return $case;
|
||||
}
|
||||
|
||||
/**
|
||||
* A report of the portal about a known case (channel events, Architektur V2: cancellation or change via an API):
|
||||
* the case gets a task and a history entry, nothing about the booking changes (E-019, stage M2 of 02 §8.2).
|
||||
*/
|
||||
public function reportToCase(Channel $channel, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source): void
|
||||
{
|
||||
$this->report($channel, $channel->case_intake ?? CaseIntakeMode::Off, $case, $outcome, $message, $key, $source);
|
||||
}
|
||||
|
||||
/**
|
||||
* A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates
|
||||
* cases; otherwise only recorded.
|
||||
@@ -292,6 +301,11 @@ public static function reference(BlockedPeriod $block): ?string
|
||||
return trim((string) $fromRules);
|
||||
}
|
||||
|
||||
// A block of a portal's API (channel events, Architektur V2) carries the reference like a booking mail.
|
||||
if ($block->source === 'api' && str_starts_with((string) $block->external_uid, 'api:')) {
|
||||
return substr((string) $block->external_uid, 4);
|
||||
}
|
||||
|
||||
if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) {
|
||||
$reference = substr((string) $block->external_uid, 6);
|
||||
|
||||
@@ -315,7 +329,7 @@ public function caseByReference(Channel $channel, string $reference): ?Booking
|
||||
}
|
||||
|
||||
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
|
||||
->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id');
|
||||
->whereIn('external_uid', [$reference, 'email:'.$reference, 'api:'.$reference])->value('linked_booking_id');
|
||||
|
||||
return $linked !== null ? Booking::query()->find($linked) : null;
|
||||
}
|
||||
@@ -346,6 +360,9 @@ private function certainty(BlockedPeriod $block, ?string $reference): ?string
|
||||
if ($block->source === 'email') {
|
||||
return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null;
|
||||
}
|
||||
if ($block->source === 'api') {
|
||||
return $reference === null ? 'Portalmeldung ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : null;
|
||||
}
|
||||
|
||||
// Classified by the landlord as a reservation booked at this portal.
|
||||
if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Process\ProcessCatalogue;
|
||||
use App\Process\ProcessPlan;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* Checks the process catalogue (docs/Prozessarchitektur/Architektur/05 §2.2) and, with --cases, that every frozen plan
|
||||
* of every case (open or finished, every landlord) can still be read: model versions and module versions registered or
|
||||
* declared compatible (requirement T3). With --matrix it writes MODULMATRIX.md.
|
||||
*/
|
||||
#[Signature('process:check {--cases : also check the frozen plans of all cases} {--matrix : write docs/Prozessarchitektur/Architektur/MODULMATRIX.md}')]
|
||||
#[Description('Check the process catalogue (modules, models, dependencies, tester-only parts) and the frozen plans of the cases')]
|
||||
class ProcessCheck extends Command
|
||||
{
|
||||
public function handle(ProcessCatalogue $catalogue): int
|
||||
{
|
||||
$problems = $catalogue->problems();
|
||||
|
||||
if ($this->option('cases')) {
|
||||
$problems = [...$problems, ...$this->cases($catalogue)];
|
||||
}
|
||||
|
||||
if ($this->option('matrix')) {
|
||||
$path = base_path('docs/Prozessarchitektur/Architektur/MODULMATRIX.md');
|
||||
file_put_contents($path, $this->matrix($catalogue));
|
||||
$this->info('Modulmatrix geschrieben: '.$path);
|
||||
}
|
||||
|
||||
foreach ($problems as $problem) {
|
||||
$this->error($problem);
|
||||
}
|
||||
if ($problems === []) {
|
||||
$this->info(count($catalogue->modules()).' Module, '.count($catalogue->modelVersions()).' Modelle: ohne Befund.');
|
||||
}
|
||||
|
||||
return $problems === [] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function cases(ProcessCatalogue $catalogue): array
|
||||
{
|
||||
$problems = [];
|
||||
Booking::withoutGlobalScopes()->select(['id', 'reference', 'profile', 'status'])->whereNotNull('profile')->lazyById()->each(function (Booking $booking) use ($catalogue, &$problems): void {
|
||||
$plan = (array) (($booking->profile ?? [])['plan'] ?? []);
|
||||
if ($plan === []) {
|
||||
return;
|
||||
}
|
||||
$frozen = ProcessPlan::fromArray($plan);
|
||||
if (! $catalogue->hasModel($frozen->model)) {
|
||||
$problems[] = "Vorgang {$booking->reference}: Modell {$frozen->model} ist nicht mehr registriert.";
|
||||
} elseif (! $catalogue->hasModel($frozen->model, $frozen->modelVersion)) {
|
||||
$problems[] = "Vorgang {$booking->reference}: Modellversion {$frozen->reference()} fehlt im Register (T3: Versionen nicht entfernen, solange Vorgänge sie tragen).";
|
||||
}
|
||||
foreach ($frozen->modules as $key => $version) {
|
||||
if (! $catalogue->serves($key, $version) && ! in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
|
||||
$problems[] = "Offener Vorgang {$booking->reference}: Modul {$key}@{$version} wird nicht mehr bedient.";
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $problems;
|
||||
}
|
||||
|
||||
private function matrix(ProcessCatalogue $catalogue): string
|
||||
{
|
||||
$models = $catalogue->models();
|
||||
$lines = [
|
||||
'# Modulmatrix (erzeugt)',
|
||||
'',
|
||||
'Erzeugt von `php artisan process:check --matrix` aus `config/process.php` – nicht von Hand ändern. Spalten: Modelle (Standardablauf; `V` = nur in einer Variante).',
|
||||
'',
|
||||
'| Modul | Version | Phase | Aktivierung | Verfügbarkeit | hart abhängig von | '.implode(' | ', array_keys($models)).' | Testgruppe |',
|
||||
'|'.str_repeat('---|', 7 + count($models)),
|
||||
];
|
||||
foreach ($catalogue->modules() as $key => $class) {
|
||||
$definition = $class::definition();
|
||||
$cells = array_map(function ($model) use ($key): string {
|
||||
if (in_array($key, $model->modules('standard'), true)) {
|
||||
return '●';
|
||||
}
|
||||
foreach ($model->variants() as $variant) {
|
||||
if (in_array($key, $model->modules($variant->key), true)) {
|
||||
return 'V';
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}, $models);
|
||||
$hard = implode(', ', array_map(fn ($dependency): string => $dependency->module, array_filter($definition->requires, fn ($dependency): bool => $dependency->hard)));
|
||||
$lines[] = "| `{$key}` | {$class::version()} | {$definition->phase} | {$definition->toggle} | {$definition->availability} | {$hard} | ".implode(' | ', $cells)." | `module:{$key}` |";
|
||||
}
|
||||
|
||||
return implode("\n", $lines)."\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Checksums of what an update must never change by itself (docs/Prozessarchitektur/Architektur/06 U-F, step 6):
|
||||
* the cases with their contract data and frozen profile, the channels' process configuration and the calendar blocks.
|
||||
* Run before and after a deployment and compare. Only reads; prints no personal data.
|
||||
*/
|
||||
#[Signature('process:fingerprint')]
|
||||
#[Description('Print checksums of cases, channel configurations and calendar blocks (compare before/after a deployment)')]
|
||||
class ProcessFingerprint extends Command
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$hash = fn ($query): string => md5($query->get()->map(fn (object $row): string => (string) json_encode($row))->implode("\n"));
|
||||
|
||||
$this->line((string) json_encode([
|
||||
'bookings' => DB::table('bookings')->count(),
|
||||
'channels' => DB::table('channels')->count(),
|
||||
'blocked_periods' => DB::table('blocked_periods')->count(),
|
||||
'h_bookings' => $hash(DB::table('bookings')->orderBy('id')->select('id', 'status', 'profile', 'total', 'quote', 'offer_terms', 'acceptance', 'arrival', 'departure', 'hold_expires_at', 'deposit_due_on', 'balance_due_on')),
|
||||
'h_overrides' => $hash(DB::table('channels')->orderBy('id')->select('id', 'process_overrides', 'booking_model', 'case_intake')),
|
||||
'h_blocks' => $hash(DB::table('blocked_periods')->orderBy('id')->select('id', 'starts_on', 'ends_on', 'source', 'channel_id', 'linked_booking_id', 'deleted_at')),
|
||||
], JSON_PRETTY_PRINT));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Channel;
|
||||
use App\Process\Modules\ContributesToPrice;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
use App\Process\ProcessCatalogue;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* Change impact of a module (docs/Prozessarchitektur/Architektur/05 §2): models and variants with their case types,
|
||||
* extension points, dependent modules, parameters, whether it reads frozen contract data, the number of channels that
|
||||
* chose an affected model (count only) and the test groups to run.
|
||||
*/
|
||||
#[Signature('process:impact {module : key of the module, e.g. offer.binding}')]
|
||||
#[Description('Show which models, case types, dependent modules, channels and test groups a change of a process module affects')]
|
||||
class ProcessImpact extends Command
|
||||
{
|
||||
public function handle(ProcessCatalogue $catalogue): int
|
||||
{
|
||||
$key = (string) $this->argument('module');
|
||||
if (! $catalogue->hasModule($key)) {
|
||||
$this->error("Unbekanntes Modul {$key}. Registriert: ".implode(', ', array_keys($catalogue->modules())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$class = $catalogue->modules()[$key];
|
||||
$definition = $class::definition();
|
||||
$uses = [];
|
||||
foreach ($catalogue->models() as $modelKey => $model) {
|
||||
foreach ($model->variants() as $variant) {
|
||||
if (in_array($key, $model->modules($variant->key), true)) {
|
||||
$uses[] = $modelKey.($variant->key === 'standard' ? '' : ':'.$variant->key).' ('.implode('/', array_map(fn ($type): string => strtoupper($type->value), $model::caseTypes())).')';
|
||||
}
|
||||
}
|
||||
}
|
||||
$dependents = array_keys(array_filter($catalogue->modules(), fn (string $other): bool => collect($other::definition()->requires)->contains(fn ($dependency): bool => $dependency->module === $key)));
|
||||
$modelKeys = array_map(fn (string $use): string => explode(' ', explode(':', $use)[0])[0], $uses);
|
||||
$channels = Channel::withoutGlobalScopes()->get(['process_overrides'])->filter(fn (Channel $channel): bool => collect((array) $channel->process_overrides)->contains(fn ($config): bool => in_array($config['model'] ?? null, $modelKeys, true)))->count();
|
||||
|
||||
$this->table(['', $key.' v'.$class::version()], [
|
||||
['Aufgabe', $definition->purpose],
|
||||
['Phase / Aktivierung', $definition->phase.' / '.$definition->toggle.' / '.$definition->availability],
|
||||
['Modelle', implode(', ', $uses) ?: '–'],
|
||||
['Erweiterungspunkte', implode(', ', $definition->points) ?: 'fester Platz im Modell'],
|
||||
['Benötigt', implode(', ', array_map(fn ($dependency): string => $dependency->module.($dependency->hard ? ' (hart)' : ' (weich)'), $definition->requires)) ?: '–'],
|
||||
['Benötigt von', implode(', ', $dependents) ?: '–'],
|
||||
['Läuft automatisch', is_subclass_of($class, RunsAutomatically::class) ? 'ja, Auslöser: '.implode(', ', $definition->triggers) : 'nein'],
|
||||
['Preisbeitrag', is_subclass_of($class, ContributesToPrice::class) ? 'ja (CasePricing, nur vor Verbindlichkeit)' : 'nein'],
|
||||
['Wertet Vertragsdaten aus', $definition->readsContractData ? 'ja – Bestandsfall-Test Pflicht (--group=ongoing)' : 'nein'],
|
||||
['Parameter', implode(', ', array_map(fn ($parameter): string => is_string($parameter) ? $parameter : $parameter->value, $definition->parameters)) ?: '–'],
|
||||
['Kanäle mit gewähltem Modell', (string) $channels],
|
||||
['Tests', "--group=module:{$key} --group=golden --group=ongoing --group=runner"],
|
||||
]);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Process\Tester\EffectLedger;
|
||||
use App\Process\Tester\ProcessSandboxDriver;
|
||||
use App\Process\Tester\SandboxBootstrapper;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Entry of a tester run – only inside the process ProcessSandbox starts for it (environment FEWO_SANDBOX_RUN, so the
|
||||
* SandboxBootstrapper has turned the process into a sandbox before anything was resolved). Reads input.json of the run
|
||||
* and writes report.json; never touches anything outside the run's directory.
|
||||
*/
|
||||
#[Signature('process:sandbox-run {run : id of the prepared run}')]
|
||||
#[Description('Play a process tester scenario inside its isolated process (started by the process tester only)')]
|
||||
class ProcessSandboxRun extends Command
|
||||
{
|
||||
public function handle(ProcessSandboxDriver $driver): int
|
||||
{
|
||||
if (! SandboxBootstrapper::active() || (string) getenv(SandboxBootstrapper::ENV) !== (string) $this->argument('run') || config('sandbox.run') !== $this->argument('run')) {
|
||||
$this->error('Nur innerhalb eines vom Prozess-Tester gestarteten Laufs.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$directory = (string) config('sandbox.directory');
|
||||
try {
|
||||
$report = $driver->run((array) json_decode((string) file_get_contents($directory.'/input.json'), true));
|
||||
} catch (Throwable $exception) {
|
||||
$report = ['aborted' => 'Lauf abgebrochen: '.class_basename($exception).': '.$exception->getMessage(), 'timeline' => [], 'violations' => EffectLedger::violations()];
|
||||
}
|
||||
file_put_contents($directory.'/report.json', json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Builds the migrated, empty SQLite template of the process tester's databases (storage/app/sandbox/template.sqlite).
|
||||
* Run at every deployment after the migrations; a run copies it instead of migrating. Touches only that file.
|
||||
*/
|
||||
#[Signature('process:sandbox-template')]
|
||||
#[Description('Build the empty, migrated SQLite template for process tester runs')]
|
||||
class ProcessSandboxTemplate extends Command
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
if (! extension_loaded('pdo_sqlite')) {
|
||||
$this->warn('pdo_sqlite fehlt – der Prozess-Tester bleibt gesperrt.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$directory = storage_path('app/sandbox');
|
||||
@mkdir($directory.'/runs', 0775, true);
|
||||
$file = $directory.'/template.building.sqlite';
|
||||
@unlink($file);
|
||||
touch($file);
|
||||
|
||||
config(['database.connections.sandbox_template' => ['driver' => 'sqlite', 'database' => $file, 'prefix' => '', 'foreign_key_constraints' => true]]);
|
||||
// `migrate --database` switches the default connection of this process and does not switch it back.
|
||||
$default = DB::getDefaultConnection();
|
||||
try {
|
||||
Artisan::call('migrate', ['--database' => 'sandbox_template', '--force' => true, '--no-interaction' => true]);
|
||||
} finally {
|
||||
DB::setDefaultConnection($default);
|
||||
DB::purge('sandbox_template');
|
||||
config(['database.connections.sandbox_template' => null]);
|
||||
}
|
||||
|
||||
rename($file, $directory.'/template.sqlite');
|
||||
$this->info('Vorlage erstellt: '.$directory.'/template.sqlite');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\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.
|
||||
}
|
||||
|
||||
@@ -13,9 +13,12 @@
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\DocumentKind;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Forms\DocumentCompositionFields;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Pricing\CaseMoney;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Process\CaseClosure;
|
||||
use App\Process\CaseLog;
|
||||
@@ -230,14 +233,37 @@ private function settleAction(): Action
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null)
|
||||
->modalHeading('Kaufmännisch abschließen')
|
||||
->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).')
|
||||
->schema([Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500)])
|
||||
->schema([
|
||||
// Decision O5: with portal collection an open payout needs its financial clarification, not only a reason.
|
||||
Select::make('clarification')->label('Wie ist die Auszahlung geklärt?')
|
||||
->options(CaseClosure::PAYOUT_CLARIFICATIONS)
|
||||
->visible(fn (): bool => $this->payoutOpen())
|
||||
->required(fn (): bool => $this->payoutOpen())
|
||||
->helperText('Eine Meldung des Portals über die Auszahlung ist kein Nachweis des Geldeingangs. „Als offene Forderung weiterführen“ legt eine Aufgabe an; der Vorgang bleibt kaufmännisch offen.'),
|
||||
Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor());
|
||||
try {
|
||||
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor(), $data['clarification'] ?? null);
|
||||
} catch (ReservationException $exception) {
|
||||
Notification::make()->title('Nicht abgeschlossen')->body($exception->getMessage())->danger()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->record->refresh();
|
||||
Notification::make()->title('Kaufmännisch abgeschlossen')->success()->send();
|
||||
Notification::make()->title($this->record->settled_at !== null ? 'Kaufmännisch abgeschlossen' : 'Als offene Forderung weitergeführt')->success()->send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the portal's payout is open or deviating (decision O5).
|
||||
*/
|
||||
private function payoutOpen(): bool
|
||||
{
|
||||
return CaseMoney::of($this->record)->collector() === Responsibility::Portal
|
||||
&& collect(CaseClosure::commercialPoints($this->record))->contains(fn (string $point): bool => str_contains($point, 'Auszahlung'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Open tasks the landlord can settle on the page (not the ones with an action of their own).
|
||||
*
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Concerns\SelectsRecordProperty;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelProcess;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelProcessTest;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
||||
use App\Filament\Resources\Channels\Pages\CreateChannel;
|
||||
use App\Filament\Resources\Channels\Pages\EditChannel;
|
||||
@@ -61,6 +63,8 @@ public static function getPages(): array
|
||||
'create' => CreateChannel::route('/create'),
|
||||
'edit' => EditChannel::route('/{record}/edit'),
|
||||
'rules' => ChannelRules::route('/{record}/rules'),
|
||||
'process' => ChannelProcess::route('/{record}/process'),
|
||||
'test' => ChannelProcessTest::route('/{record}/test'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\ConfigureChannelProcess;
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\User;
|
||||
use App\Process\ChannelProcessConfiguration;
|
||||
use App\Process\Models\ProcessModel;
|
||||
use App\Process\ProcessCatalogue;
|
||||
use App\Process\ProcessProfile;
|
||||
use App\Process\ProcessSettings;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
|
||||
use Filament\Resources\Pages\Page;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Kanal › Ablauf (docs/Prozessarchitektur/Architektur/03): per intake kind of the channel the landlord chooses an
|
||||
* admissible process model and sets up its steps right where they are – switch, mode, who carries it out, deadlines –
|
||||
* with the inherited value and its origin, the consequences in a live preview and a test of the (unsaved) draft in the
|
||||
* process tester. Saving goes through ConfigureChannelProcess; running cases keep their frozen plan (E3).
|
||||
*
|
||||
* @property Channel $record
|
||||
*/
|
||||
class ChannelProcess extends Page
|
||||
{
|
||||
use InteractsWithRecord;
|
||||
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected static ?string $title = 'Ablauf';
|
||||
|
||||
protected string $view = 'filament.resources.channels.channel-process';
|
||||
|
||||
public string $intake = 'inquiry';
|
||||
|
||||
/** @var array<string, array{model: string, variant: string, steps: array<string, array{on?: bool}>, settings: array<string, mixed>}> */
|
||||
public array $drafts = [];
|
||||
|
||||
public function mount(int|string $record): void
|
||||
{
|
||||
$this->record = $this->resolveRecord($record);
|
||||
$configuration = app(ChannelProcessConfiguration::class);
|
||||
foreach ($configuration->intakes($this->record) as $intake) {
|
||||
$current = $configuration->current($this->record, $intake);
|
||||
$stored = (array) (($this->record->process_overrides ?? [])[$intake->value] ?? []);
|
||||
$models = $configuration->admissibleModels($this->record, $intake);
|
||||
$model = array_key_exists($current['model'], $models) || $models === [] ? $current['model'] : (string) array_key_first($models);
|
||||
$this->drafts[$intake->value] = [
|
||||
'model' => $model,
|
||||
'variant' => $current['variant'],
|
||||
'steps' => (array) ($stored['steps'] ?? []),
|
||||
'settings' => array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, array_intersect_key($stored, array_flip(array_map(fn (ProcessSetting $setting): string => $setting->value, ProcessSetting::cases())))),
|
||||
'derived' => $current['derived'],
|
||||
];
|
||||
}
|
||||
$this->intake = (string) array_key_first($this->drafts);
|
||||
}
|
||||
|
||||
public function getTitle(): string
|
||||
{
|
||||
return 'Ablauf: '.$this->record->name;
|
||||
}
|
||||
|
||||
public function expert(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
return ! $user instanceof User || $user->adminMode() === AdminMode::Expert;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> intake value => tab label
|
||||
*/
|
||||
public function tabs(): array
|
||||
{
|
||||
return collect(array_keys($this->drafts))->mapWithKeys(fn (string $intake): array => [$intake => $intake === IntakeKind::Booking->value ? 'Feste Buchungen' : 'Anfragen'])->all();
|
||||
}
|
||||
|
||||
public function question(): string
|
||||
{
|
||||
return $this->intake === IntakeKind::Booking->value
|
||||
? 'Wie wird eine feste Buchung über '.$this->record->name.' abgewickelt?'
|
||||
: 'Wie wird eine Anfrage über '.$this->record->name.' abgewickelt?';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ProcessModel>
|
||||
*/
|
||||
public function models(): array
|
||||
{
|
||||
return app(ChannelProcessConfiguration::class)->admissibleModels($this->record, IntakeKind::from($this->intake));
|
||||
}
|
||||
|
||||
public function chooseModel(string $model): void
|
||||
{
|
||||
$this->drafts[$this->intake]['model'] = $model;
|
||||
$this->drafts[$this->intake]['variant'] = 'standard';
|
||||
$this->drafts[$this->intake]['steps'] = [];
|
||||
}
|
||||
|
||||
public function model(): ProcessModel
|
||||
{
|
||||
return app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']);
|
||||
}
|
||||
|
||||
public function profile(): ProcessProfile
|
||||
{
|
||||
return app(ChannelProcessConfiguration::class)->profileWith($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The step cards: preview row + controls of each step.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function steps(): array
|
||||
{
|
||||
$configuration = app(ChannelProcessConfiguration::class);
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
$model = $this->model();
|
||||
$profile = $this->profile();
|
||||
$draft = $this->drafts[$this->intake];
|
||||
|
||||
return array_map(function (array $row) use ($configuration, $catalogue, $model, $profile): array {
|
||||
$definition = $catalogue->modules()[$row['module']]::definition();
|
||||
$controls = ChannelProcessConfiguration::STEP_CONTROLS[$row['module']] ?? [];
|
||||
$parameters = array_values(array_filter($controls['parameters'] ?? [], fn (ProcessSetting $setting): bool => in_array(IntakeKind::from($this->intake), $setting->channelIntakes(), true) && ! $model::fixesSetting($setting) && ($this->expert() || in_array($setting, [ProcessSetting::HoldHours, ProcessSetting::DataRequestReminderHours, ProcessSetting::ArrivalInfoDaysBefore, ProcessSetting::ClarificationHoldAutoMinutes], true))));
|
||||
|
||||
return [...$row,
|
||||
'purpose' => $definition->purpose,
|
||||
'waits' => $definition->waits,
|
||||
'optional' => $definition->isOptional(),
|
||||
'version' => $catalogue->modules()[$row['module']]::version(),
|
||||
'mode_setting' => isset($controls['mode']) && ! $model::fixesSetting($controls['mode']) ? $controls['mode'] : null,
|
||||
'mode_options' => $configuration->modeOptions($row['module']),
|
||||
'performer_setting' => isset($controls['performer']) ? $controls['performer']['setting'] : null,
|
||||
'performer_options' => $configuration->performerOptions($model, $row['module']),
|
||||
'parameters' => array_map(fn (ProcessSetting $setting): array => $this->setting($setting, $profile), $parameters),
|
||||
];
|
||||
}, $configuration->preview($this->record, IntakeKind::from($this->intake), $draft));
|
||||
}
|
||||
|
||||
/**
|
||||
* One setting with its effective value and origin (set here, by the model, inherited from where).
|
||||
*
|
||||
* @return array{key: string, question: string, value: string, source: string, set: bool}
|
||||
*/
|
||||
public function setting(ProcessSetting $setting, ProcessProfile $profile): array
|
||||
{
|
||||
$source = $profile->source($setting);
|
||||
|
||||
return [
|
||||
'key' => $setting->value,
|
||||
'question' => $setting->question(),
|
||||
'value' => $setting === ProcessSetting::ContractTemplate ? (string) ($profile->value($setting) ?? 'Vorlage der Wohnung') : $setting->describe($profile->value($setting)),
|
||||
'source' => in_array($source, [ProcessProfile::CHANNEL, ProcessProfile::WEBSITE], true) ? 'hier gesetzt' : 'geerbt: '.ProcessProfile::sourceLabel($source),
|
||||
'set' => array_key_exists($setting->value, $this->drafts[$this->intake]['settings']) && filled($this->drafts[$this->intake]['settings'][$setting->value]),
|
||||
];
|
||||
}
|
||||
|
||||
public function inherit(string $setting): void
|
||||
{
|
||||
unset($this->drafts[$this->intake]['settings'][$setting]);
|
||||
}
|
||||
|
||||
public function toggleStep(string $module): void
|
||||
{
|
||||
$on = ($this->drafts[$this->intake]['steps'][$module]['on'] ?? true) !== false;
|
||||
$this->drafts[$this->intake]['steps'][$module] = ['on' => ! $on];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function problems(): array
|
||||
{
|
||||
return app(ChannelProcessConfiguration::class)->problems($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Running cases of this channel and intake kind (they keep their frozen plan).
|
||||
*/
|
||||
public function runningCases(): int
|
||||
{
|
||||
return Booking::query()
|
||||
->where(fn ($query) => $query->where('origin_channel_id', $this->record->id)->orWhere('import_channel_id', $this->record->id))
|
||||
->where('intake', $this->intake)
|
||||
->whereNotIn('status', ['cancelled', 'declined', 'expired', 'completed'])
|
||||
->count();
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
try {
|
||||
$this->record = app(ConfigureChannelProcess::class)->handle($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]);
|
||||
} catch (ValidationException $exception) {
|
||||
Notification::make()->title('Nicht gespeichert')->body(collect($exception->errors())->flatten()->implode(' '))->danger()->persistent()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->drafts[$this->intake]['derived'] = false;
|
||||
$running = $this->runningCases();
|
||||
Notification::make()->title('Ablauf gespeichert')->body('Gilt für neue Vorgänge.'.($running > 0 ? ' '.$running.' laufende Vorgänge behalten ihren bisherigen Ablauf.' : ''))->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the process tester with the current – also unsaved – draft of this intake kind.
|
||||
*/
|
||||
public function test(): void
|
||||
{
|
||||
session()->put('process-tester.draft.'.$this->record->id.'.'.$this->intake, $this->drafts[$this->intake]);
|
||||
$this->redirect(ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake]));
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective value a new case would get, for the landlord's comparison (expert view).
|
||||
*/
|
||||
public function standard(ProcessSetting $setting): string
|
||||
{
|
||||
$profile = app(ProcessSettings::class)->resolve($this->record->property, null, IntakeKind::from($this->intake));
|
||||
|
||||
return $setting->describe($profile->value($setting));
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('save')->label('Speichern')->action(fn () => $this->save()),
|
||||
Action::make('connection')->label('Kanaldaten')->color('gray')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ProcessTestRun;
|
||||
use App\Models\User;
|
||||
use App\Process\ChannelProcessConfiguration;
|
||||
use App\Process\Tester\ProcessSandbox;
|
||||
use App\Process\Tester\ScenarioCatalogue;
|
||||
use App\Process\Tester\Scenarios\Scenario;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
|
||||
use Filament\Resources\Pages\Page;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Ablauf testen (docs/Prozessarchitektur/Architektur/04): plays a predefined scenario with the channel's current – also
|
||||
* unsaved – process configuration in an isolated run and shows the report step by step. Nothing of a run reaches the
|
||||
* real data, mails, calendars or portals; on a server where the isolation cannot be established the tester is locked
|
||||
* and says why. Landlord administrators only (decision E8).
|
||||
*
|
||||
* @property Channel $record
|
||||
*/
|
||||
class ChannelProcessTest extends Page
|
||||
{
|
||||
use InteractsWithRecord;
|
||||
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected static ?string $title = 'Ablauf testen';
|
||||
|
||||
protected string $view = 'filament.resources.channels.channel-process-test';
|
||||
|
||||
public string $intake = 'inquiry';
|
||||
|
||||
public string $scenario = '';
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $inputs = [];
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $draft = [];
|
||||
|
||||
public int $steps = 1;
|
||||
|
||||
public ?int $runId = null;
|
||||
|
||||
public static function canAccess(array $parameters = []): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
return $user instanceof User && $user->hasRole(UserRole::Admin);
|
||||
}
|
||||
|
||||
public function mount(int|string $record): void
|
||||
{
|
||||
$this->record = $this->resolveRecord($record);
|
||||
$intakes = array_map(fn (IntakeKind $intake): string => $intake->value, app(ChannelProcessConfiguration::class)->intakes($this->record));
|
||||
$requested = (string) request()->query('intake', '');
|
||||
$this->intake = in_array($requested, $intakes, true) ? $requested : ($intakes[0] ?? 'inquiry');
|
||||
$this->draft = (array) session()->get($this->draftKey(), []);
|
||||
if ($this->draft === []) {
|
||||
$current = app(ChannelProcessConfiguration::class)->current($this->record, IntakeKind::from($this->intake));
|
||||
$stored = (array) (($this->record->process_overrides ?? [])[$this->intake] ?? []);
|
||||
$this->draft = ['model' => $current['model'], 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), 'settings' => []];
|
||||
}
|
||||
$this->scenario = (string) array_key_first($this->scenarios());
|
||||
$this->resetInputs();
|
||||
}
|
||||
|
||||
public function draftKey(): string
|
||||
{
|
||||
return 'process-tester.draft.'.$this->record->id.'.'.$this->intake;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, class-string<Scenario>>
|
||||
*/
|
||||
public function scenarios(): array
|
||||
{
|
||||
return ScenarioCatalogue::for(IntakeKind::from($this->intake), $this->record->isWebsite());
|
||||
}
|
||||
|
||||
public function updatedScenario(): void
|
||||
{
|
||||
$this->resetInputs();
|
||||
$this->runId = null;
|
||||
$this->steps = 1;
|
||||
}
|
||||
|
||||
private function resetInputs(): void
|
||||
{
|
||||
$class = $this->scenarios()[$this->scenario] ?? null;
|
||||
$this->inputs = $class === null ? [] : array_map(fn (array $input): mixed => $input['type'] === 'date' ? now()->modify((string) $input['default'])->toDateString() : $input['default'], $class::inputs());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function requirements(): array
|
||||
{
|
||||
return ProcessSandbox::requirements();
|
||||
}
|
||||
|
||||
public function start(): void
|
||||
{
|
||||
$this->steps = 1;
|
||||
$this->play();
|
||||
}
|
||||
|
||||
public function next(): void
|
||||
{
|
||||
$this->steps++;
|
||||
$this->play();
|
||||
}
|
||||
|
||||
private function play(): void
|
||||
{
|
||||
try {
|
||||
$run = app(ProcessSandbox::class)->run($this->record, IntakeKind::from($this->intake), $this->draft, $this->scenario, $this->inputs, $this->steps, auth()->user());
|
||||
$this->runId = $run->id;
|
||||
} catch (Throwable $exception) {
|
||||
Notification::make()->title('Test nicht möglich')->body($exception->getMessage())->danger()->persistent()->send();
|
||||
}
|
||||
}
|
||||
|
||||
public function run(): ?ProcessTestRun
|
||||
{
|
||||
return $this->runId === null ? null : ProcessTestRun::query()->find($this->runId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<ProcessTestRun>
|
||||
*/
|
||||
public function recent(): iterable
|
||||
{
|
||||
return ProcessTestRun::query()->where('channel_id', $this->record->id)->latest()->limit(5)->get();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('back')->label('Zurück zum Ablauf')->color('gray')->url(fn (): string => ChannelResource::getUrl('process', ['record' => $this->record])),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ class EditChannel extends EditRecord
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('process')->label('Ablauf')->url(fn (): string => ChannelResource::getUrl('process', ['record' => $this->record])),
|
||||
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record]))->visible(fn (): bool => $this->record->isPortal()),
|
||||
Action::make('analyze')->label('Kalender analysieren')->visible(fn (): bool => $this->record->isPortal())->action(function (AnalyzeChannelCalendar $analyze): void {
|
||||
try {
|
||||
@@ -38,10 +39,8 @@ protected function mutateFormDataBeforeFill(array $data): array
|
||||
|
||||
protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
// The own website's entry only keeps its settings; there is no connection to configure.
|
||||
// The own website's entry has no connection to configure; its process is set up under "Ablauf" (ChannelProcess).
|
||||
if ($record instanceof Channel && $record->isWebsite()) {
|
||||
$record->update(['process_overrides' => $data['process_overrides'] ?? []]);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,9 +8,7 @@
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Enums\ChannelStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Filament\Forms\ProcessSettingFields;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
@@ -21,6 +19,7 @@
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
@@ -68,7 +67,12 @@ public static function configure(Schema $schema, bool $selectProperty = false):
|
||||
->required()
|
||||
->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.')
|
||||
->columnSpanFull(),
|
||||
...self::processSections(),
|
||||
Select::make('settings.portal_profile')->label('Art des Portals (Kanalprofil)')
|
||||
->options(fn (): array => collect(config('channels.portal_profiles'))->except('website')->map(fn (array $profile): string => $profile['label'])->all())
|
||||
->placeholder('am Namen erkennen')
|
||||
->helperText('Legt fest, welche Ablaufmodelle für Anfragen und feste Buchungen dieses Portals wählbar sind (Kanal › Ablauf). Weitere Modelle werden nach fachlicher Prüfung im Kanalprofil freigegeben.')
|
||||
->columnSpanFull(),
|
||||
...self::processLink('Ablauf dieses Portals'),
|
||||
Select::make('connector')
|
||||
->label('Kalenderanbindung')
|
||||
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.')
|
||||
@@ -125,56 +129,27 @@ public static function configure(Schema $schema, bool $selectProperty = false):
|
||||
*/
|
||||
private static function websiteSections(): array
|
||||
{
|
||||
$defaults = (array) (Settings::tenant()?->process_defaults ?? []);
|
||||
$inherited = function (ProcessSetting $setting) use ($defaults): string {
|
||||
$value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default();
|
||||
|
||||
return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value);
|
||||
};
|
||||
$settings = array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array(IntakeKind::Inquiry, $setting->channelIntakes(), true)));
|
||||
|
||||
return [
|
||||
Section::make('Anfragen über die eigene Webseite')
|
||||
->description('Nur ausfüllen, was für Anfragen über Ihre Webseite anders sein soll als in Ihren Standardeinstellungen (System › So arbeite ich). Telefon- und E-Mail-Anfragen folgen weiter den Standardeinstellungen.')
|
||||
->columns(2)
|
||||
->description('Wie Anfragen über Ihre Webseite abgewickelt werden – Ablaufmodell, Schritte, Fristen –, stellen Sie unter „Ablauf“ ein. Telefon- und E-Mail-Anfragen folgen Ihren Standardeinstellungen (System › So arbeite ich).')
|
||||
->columnSpanFull()
|
||||
->visible(fn (?Channel $record): bool => $record?->isWebsite() ?? false)
|
||||
->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settings, $inherited)),
|
||||
->schema(self::processLink('Ablauf der Webseite')),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* What a contract template brings along, shown under the template choice.
|
||||
*/
|
||||
/**
|
||||
* Deviations of this portal from the landlord's defaults, separately for requests and for bookings that are already
|
||||
* binding when they arrive. Empty fields follow the defaults (System › So arbeite ich).
|
||||
* The process of a channel is set up step by step on its own page (Kanal › Ablauf), no longer as a flat list here.
|
||||
*
|
||||
* @return list<Section>
|
||||
* @return list<Component>
|
||||
*/
|
||||
private static function processSections(): array
|
||||
private static function processLink(string $label): array
|
||||
{
|
||||
$defaults = (array) (Settings::tenant()?->process_defaults ?? []);
|
||||
$inherited = function (ProcessSetting $setting) use ($defaults): string {
|
||||
$value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default();
|
||||
|
||||
return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value);
|
||||
};
|
||||
$settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => $setting !== ProcessSetting::FormRequiresAddress && in_array($intake, $setting->channelIntakes(), true)));
|
||||
|
||||
return [
|
||||
Section::make('Anfragen über dieses Portal')
|
||||
->description('Nur ausfüllen, was bei diesem Portal anders ist als in Ihren Standardeinstellungen.')
|
||||
->columns(2)
|
||||
->columnSpanFull()
|
||||
->collapsible()
|
||||
->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settingsFor(IntakeKind::Inquiry), $inherited)),
|
||||
Section::make('Feste Buchungen über dieses Portal')
|
||||
->description('Buchungen, die beim Portal schon verbindlich sind. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Anlagen mit.')
|
||||
->columns(2)
|
||||
->columnSpanFull()
|
||||
->collapsible()
|
||||
->schema(ProcessSettingFields::make('process_overrides.booking.', $settingsFor(IntakeKind::Booking), $inherited)),
|
||||
TextEntry::make('process_link')->hiddenLabel()->columnSpanFull()
|
||||
->state(fn (?Channel $record): string => $record === null ? 'Den Ablauf richten Sie nach dem Anlegen unter „Ablauf“ ein.' : $label.': Ablaufmodell wählen und Schritte einstellen.')
|
||||
->url(fn (?Channel $record): ?string => $record === null ? null : ChannelResource::getUrl('process', ['record' => $record]))
|
||||
->color('primary'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ class IntakeObservation extends Model
|
||||
|
||||
public const SOURCE_ADOPTION = 'adoption';
|
||||
|
||||
/** A normalised channel event of a portal's interface (Architektur V2, App\Channels\Events). */
|
||||
public const SOURCE_API = 'api';
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A stored report of the process tester: scenario, configuration (also unsaved), inputs, the report of the isolated
|
||||
* run. Contains only synthetic case data; deleted after the retention period (decision O3).
|
||||
*/
|
||||
#[Fillable(['tenant_id', 'channel_id', 'user_id', 'intake', 'scenario', 'configuration', 'inputs', 'steps', 'report', 'outcome', 'release'])]
|
||||
class ProcessTestRun extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const COMPLETED = 'completed';
|
||||
|
||||
public const ABORTED = 'aborted';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'configuration' => 'array',
|
||||
'inputs' => 'array',
|
||||
'report' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\ContributesToPrice;
|
||||
use App\Process\ProcessCatalogue;
|
||||
|
||||
/**
|
||||
* The price of a case before it is fixed (extension point BeforePriceFixing, docs/Prozessarchitektur/Architektur/02
|
||||
* §6.4): PriceCalculator unchanged, plus the lines of the modules of the case's plan that contribute to the price.
|
||||
* Without contributing modules the result is exactly PriceCalculator's. Never adds anything to a binding case – its
|
||||
* price is fixed (rule R5). Pure: reads, never writes (also used for previews).
|
||||
*/
|
||||
final class CasePricing
|
||||
{
|
||||
public function __construct(private PriceCalculator $calculator, private ProcessCatalogue $catalogue) {}
|
||||
|
||||
public function quote(Booking $booking, StayRequest $stay): PriceQuote
|
||||
{
|
||||
$quote = $this->calculator->calculate($booking->property, $stay);
|
||||
if ($booking->isBinding() || ! $booking->exists) {
|
||||
return $quote;
|
||||
}
|
||||
|
||||
$context = CaseContext::of($booking);
|
||||
foreach ($context->plan->moduleKeys() as $key) {
|
||||
if (! $this->catalogue->hasModule($key) || ! $context->plan->enabled($key)) {
|
||||
continue;
|
||||
}
|
||||
$module = $this->catalogue->module($key);
|
||||
if (! $module instanceof ContributesToPrice || ! $module->applies($context)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($module->priceLines($context, $quote) as $line) {
|
||||
$quote = $quote->withLine($line);
|
||||
}
|
||||
}
|
||||
|
||||
return $quote;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
/**
|
||||
* What one automatic advance of a case did: the steps that ran, and per step that was due but held back the reasons
|
||||
* (shown to the landlord as tasks and notes, as before).
|
||||
*/
|
||||
final class AdvanceResult
|
||||
{
|
||||
/** @var list<string> */
|
||||
public array $ran = [];
|
||||
|
||||
/** @var array<string, list<string>> module key => reasons */
|
||||
public array $held = [];
|
||||
|
||||
public function ran(string $module): bool
|
||||
{
|
||||
return in_array($module, $this->ran, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reasons of one step, or of all steps that were held back.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function reasons(?string $module = null): array
|
||||
{
|
||||
if ($module !== null) {
|
||||
return $this->held[$module] ?? [];
|
||||
}
|
||||
|
||||
return array_values(array_unique(array_merge(...array_values($this->held ?: [[]]))));
|
||||
}
|
||||
}
|
||||
@@ -3,26 +3,9 @@
|
||||
namespace App\Process;
|
||||
|
||||
use App\Actions\EndInternalCase;
|
||||
use App\Actions\PrepareStays;
|
||||
use App\Actions\SendBookingDocuments;
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\ChangeStatus;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\DataRequest;
|
||||
use App\Pricing\CaseMoney;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
@@ -39,341 +22,13 @@ class CaseActivities
|
||||
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation'];
|
||||
|
||||
/**
|
||||
* The activities of the case in the order of its frozen process plan (ProcessRunner, Architektur V2).
|
||||
*
|
||||
* @return list<Activity>
|
||||
*/
|
||||
public static function for(Booking $booking): array
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property', 'payments']);
|
||||
$profile = $booking->process();
|
||||
$closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
|
||||
$binding = $booking->isBinding();
|
||||
$inquiry = $booking->intake !== IntakeKind::Booking;
|
||||
$today = CarbonImmutable::today();
|
||||
// After the end of a case (or of its stay) what was not done before is no longer to do; open money and other
|
||||
// follow-ups are tasks and the commercial closing of their own (package 9).
|
||||
// A stay whose departure has passed counts as over for the steps before it, too.
|
||||
$over = $closed || $booking->status === BookingStatus::Completed || ($binding && $booking->departure->isBefore($today));
|
||||
$later = fn (ActivityState $state): ActivityState => $over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
|
||||
$activities = [];
|
||||
|
||||
if ($booking->isInternal()) {
|
||||
return self::internal($booking, $closed, $later);
|
||||
}
|
||||
|
||||
$activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel());
|
||||
|
||||
$needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
|
||||
if ($needsContact) {
|
||||
$hasEmail = filled($booking->guest?->email);
|
||||
// v0.11 (G2a): before the own binding offer – or the binding confirmation of a wish – every required detail.
|
||||
$action = $profile->preReservation() || $booking->offer_version > 0 ? CaseRequirements::OFFER : CaseRequirements::WISH_CONFIRMATION;
|
||||
$needsDetails = $inquiry && ! $binding && $booking->offer_version === 0 && ($action === CaseRequirements::OFFER || $booking->wish_at !== null);
|
||||
$missing = $hasEmail && $needsDetails ? CaseRequirements::missing($booking, $action) : [];
|
||||
$request = $booking->openDataRequest();
|
||||
$asked = $booking->contact_requested_at !== null || $request?->status === DataRequest::OPEN;
|
||||
$state = match (true) {
|
||||
$hasEmail && $missing === [] => ActivityState::Done,
|
||||
$asked => ActivityState::Waiting,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$title = match (true) {
|
||||
$booking->guest === null => 'Name und Kontaktdaten des Gastes eintragen',
|
||||
! $hasEmail => 'E-Mail-Adresse des Gastes eintragen',
|
||||
$missing !== [] => $action === CaseRequirements::OFFER ? 'Angaben für das Angebot vervollständigen' : 'Angaben für die Bestätigung vervollständigen',
|
||||
default => 'Kontaktdaten des Gastes',
|
||||
};
|
||||
$detail = match (true) {
|
||||
$state === ActivityState::Done => $booking->guestName(),
|
||||
$missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($request !== null ? ' · '.$request->statusLabel() : ($asked ? ' · beim Gast angefragt' : '')),
|
||||
$booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'),
|
||||
default => 'fehlt noch',
|
||||
};
|
||||
// A prepared data request waits for the landlord's release: that is the next step, otherwise entering the details.
|
||||
$draft = $needsDetails && $request?->status === DataRequest::DRAFT;
|
||||
$activities[] = new Activity('contact', $title, $later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact'));
|
||||
}
|
||||
|
||||
if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) {
|
||||
// Package 7: a request without a hold is answered with an information "unter Vorbehalt"; the guest asks for the booking.
|
||||
$informed = $booking->information_version > 0 || $binding;
|
||||
$activities[] = new Activity('information', $booking->processingMode() === ProcessingMode::Automatic ? 'Unverbindliche Auskunft senden (automatisch)' : 'Unverbindliche Auskunft prüfen und senden', $later(match (true) {
|
||||
$booking->information_version > 0 => ActivityState::Done,
|
||||
$binding => ActivityState::NotApplicable,
|
||||
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
|
||||
default => ActivityState::Later,
|
||||
}), $booking->information_version > 0 ? 'Version '.$booking->information_version.' vom '.$booking->information_sent_at?->format('d.m.Y').' · ohne Reservierung' : 'der Zeitraum wird nicht reserviert', $informed ? null : 'sendInformation');
|
||||
|
||||
$activities[] = new Activity('wish', 'Gast fragt die Buchung an', $later(match (true) {
|
||||
$booking->wish_at !== null => ActivityState::Done,
|
||||
$binding => ActivityState::NotApplicable,
|
||||
$booking->information_version > 0 && $booking->information_valid_until?->isFuture() => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->wish_at !== null => 'angefragt am '.$booking->wish_at->format('d.m.Y, H:i').' Uhr',
|
||||
$booking->information_version > 0 => 'möglich bis '.$booking->information_valid_until?->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
});
|
||||
$activities[] = new Activity('wish_check', 'Erneut prüfen und verbindlich bestätigen', $later(match (true) {
|
||||
$binding => ActivityState::Done,
|
||||
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->accepted_at !== null && ($booking->acceptance['via'] ?? null) === 'booking_wish' => 'bestätigt am '.$booking->confirmed_at?->format('d.m.Y').' ('.($booking->acceptance['confirmed_by'] ?? '').')',
|
||||
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => 'siehe Aufgabe „Buchungswunsch bestätigen?“',
|
||||
$binding => 'direkt verbindlich bestätigt (ohne Buchungswunsch)',
|
||||
default => $booking->processingMode() === ProcessingMode::Automatic ? 'automatisch, wenn alles passt' : 'durch Sie',
|
||||
});
|
||||
} elseif ($inquiry) {
|
||||
$offerDone = $booking->offer_version > 0 || $binding;
|
||||
// G2a (v0.11): without every required detail there is no offer – the step waits for the guest's answer
|
||||
// (mail, link or the landlord's entry) instead of being offered as the next step.
|
||||
$offerMissing = $offerDone ? [] : CaseRequirements::missing($booking, CaseRequirements::OFFER);
|
||||
$activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) {
|
||||
$offerDone => ActivityState::Done,
|
||||
$offerMissing !== [] => ActivityState::Later,
|
||||
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->offer_version > 0 => 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y'),
|
||||
$offerMissing !== [] => 'erst wenn alle Angaben da sind',
|
||||
$booking->hold_expires_at !== null => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
}, $offerDone || $offerMissing !== [] ? null : 'sendOffer');
|
||||
|
||||
$activities[] = new Activity('acceptance', 'Gast nimmt das Angebot an', $later(match (true) {
|
||||
$binding => ActivityState::Done,
|
||||
$booking->status === BookingStatus::OfferSent => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->accepted_at !== null => 'angenommen am '.$booking->accepted_at->format('d.m.Y'),
|
||||
$binding => 'direkt bestätigt',
|
||||
$booking->status === BookingStatus::OfferSent => 'Angebot gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
});
|
||||
} else {
|
||||
$activities[] = new Activity('binding', 'Beim Portal fest gebucht', $binding || $closed ? ActivityState::External : ActivityState::Open, $booking->portal_reference ? 'Buchungsnummer '.$booking->portal_reference : null, $binding ? null : 'confirm');
|
||||
$activities[] = new Activity('price', 'Gesamtpreis laut Portal eintragen', $later($booking->total === null ? ActivityState::Open : ActivityState::Done), $booking->total === null ? 'noch nicht bekannt' : Money::format($booking->total), $booking->total === null ? 'portalPrice' : null);
|
||||
}
|
||||
|
||||
if ($profile->documents() === Responsibility::Portal) {
|
||||
$activities[] = new Activity('documents', 'Buchungsunterlagen an den Gast', ActivityState::External);
|
||||
} else {
|
||||
$state = match (true) {
|
||||
$booking->confirmation_sent_at !== null => ActivityState::Done,
|
||||
! $binding => ActivityState::Later,
|
||||
$booking->confirmation_failed_at !== null => ActivityState::Problem,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : [];
|
||||
// What the landlord still has to confirm (unreleased texts, terms not shown to be agreed on the portal).
|
||||
$toConfirm = $binding && $state === ActivityState::Open && $missing === [] ? app(SendBookingDocuments::class)->compose($booking)->toConfirm() : [];
|
||||
$activities[] = new Activity('documents', match (true) {
|
||||
$state !== ActivityState::Open => $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden',
|
||||
$inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden',
|
||||
default => 'Buchungsunterlagen prüfen und senden',
|
||||
}, $later($missing !== [] ? ActivityState::Waiting : $state),
|
||||
match (true) {
|
||||
$booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'),
|
||||
$state === ActivityState::Problem => 'Versand fehlgeschlagen',
|
||||
$missing !== [] => 'wartet: '.implode(' ', $missing),
|
||||
$toConfirm !== [] => 'vor dem Versand zu prüfen: '.implode(' ', $toConfirm),
|
||||
default => null,
|
||||
}, match (true) {
|
||||
$state === ActivityState::Problem => 'resendConfirmation',
|
||||
$binding && $missing === [] && $booking->confirmation_sent_at === null => 'sendDocuments',
|
||||
default => null,
|
||||
});
|
||||
}
|
||||
|
||||
foreach (self::channelTasks($booking) as $task) {
|
||||
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
|
||||
}
|
||||
|
||||
if ($profile->payments() === Responsibility::Portal) {
|
||||
$portal = $booking->processChannel()?->name ?? 'das Portal';
|
||||
$viaPortal = $booking->paidViaPortal();
|
||||
$activities[] = new Activity('payment', 'Zahlung des Gastes an '.$portal, ActivityState::External, match (true) {
|
||||
$booking->total === null => 'zieht das Portal ein',
|
||||
$viaPortal > 0 => 'laut Portal bezahlt: '.Money::format($viaPortal).' von '.Money::format($booking->total).' (Angabe des Portals, kein Geld bei uns)',
|
||||
default => 'zieht das Portal ein; noch keine Zahlungsangabe',
|
||||
});
|
||||
$payout = CaseMoney::of($booking)->payout();
|
||||
$activities[] = new Activity('payout', 'Auszahlung von '.$portal.' auf unser Konto', $later(match (true) {
|
||||
! $binding => ActivityState::Later,
|
||||
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) === 0 && $payout['difference'] === 0 => ActivityState::Done,
|
||||
default => ActivityState::Waiting,
|
||||
}), trim(($payout['values'] !== [] ? 'angekündigt '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).' · ' : '').'eingegangen '.Money::format($payout['received']).($payout['difference'] > 0 ? ' · Angaben weichen um '.Money::format($payout['difference']).' ab' : '')));
|
||||
} elseif ($booking->total === null) {
|
||||
$activities[] = new Activity('payment', 'Zahlungen überwachen', $later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist');
|
||||
} else {
|
||||
$paid = $booking->paidAmount();
|
||||
$activities[] = new Activity('deposit', 'Anzahlung erhalten', $later(match (true) {
|
||||
$binding && $paid >= (int) $booking->deposit => ActivityState::Done,
|
||||
$binding => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), Money::format((int) $booking->deposit).($booking->deposit_due_on ? ', fällig '.$booking->deposit_due_on->format('d.m.Y') : ''));
|
||||
$activities[] = new Activity('balance', 'Restzahlung erhalten', $later(match (true) {
|
||||
$binding && $paid >= $booking->total => ActivityState::Done,
|
||||
$binding && $paid >= (int) $booking->deposit => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), Money::format(max(0, $booking->total - (int) $booking->deposit)).($booking->balance_due_on ? ', fällig '.$booking->balance_due_on->format('d.m.Y') : ''));
|
||||
}
|
||||
|
||||
foreach (self::tasks($booking) as $task) {
|
||||
$activities[] = self::task($task);
|
||||
}
|
||||
|
||||
foreach ($booking->changes()->where('status', ChangeStatus::Proposed)->get() as $change) {
|
||||
$activities[] = new Activity('change_proposed', 'Änderungsvorschlag liegt beim Gast', ActivityState::Waiting, $change->summary().($change->expires_at ? ' · bis '.$change->expires_at->format('d.m.Y') : ''));
|
||||
}
|
||||
|
||||
$arrived = $binding && $booking->arrival <= $today;
|
||||
$left = $binding && $booking->departure <= $today;
|
||||
$missing = PrepareStays::missingArrivalDetails($booking);
|
||||
$detailsTask = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->exists();
|
||||
if ($binding && ! $detailsTask) {
|
||||
$activities[] = new Activity('arrival_details', 'Anreisedaten', $later(match (true) {
|
||||
$missing === [] => ActivityState::Done,
|
||||
$left => ActivityState::NotApplicable,
|
||||
default => ActivityState::Later,
|
||||
}), $missing === [] ? implode(' · ', array_filter([$booking->guest?->phone ?: $booking->guest?->email, $booking->arrival_time ? 'Anreise '.$booking->arrival_time : null])) : 'es fehlt: '.implode(', ', $missing).' – wird rechtzeitig als Aufgabe gemeldet');
|
||||
}
|
||||
$activities[] = $profile->guestMessages() === Responsibility::Portal
|
||||
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen')
|
||||
: new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise');
|
||||
// v0.11: a binding booking (also from a portal) stays binding; missing administrative details are asked for
|
||||
// alongside, after the steps of the booking itself.
|
||||
if ($binding && ($bookingRequest = $booking->openDataRequest()) !== null) {
|
||||
$activities[] = new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $later($bookingRequest->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open),
|
||||
implode(', ', CaseRequirements::labels($bookingRequest->fields)).' · '.$bookingRequest->statusLabel(), $bookingRequest->status === DataRequest::OPEN ? null : 'approveDataRequest');
|
||||
}
|
||||
$activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) {
|
||||
$left => ActivityState::Done,
|
||||
$arrived => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
|
||||
if ($profile->guestMessages() === Responsibility::Landlord) {
|
||||
$activities[] = new Activity('review', 'Bitte um eine Bewertung (automatisch)', $later($booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later));
|
||||
}
|
||||
|
||||
return [...$activities, ...self::closing($booking, $closed)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The two closings of a case (package 9): the stay, and the money.
|
||||
*
|
||||
* @return list<Activity>
|
||||
*/
|
||||
private static function closing(Booking $booking, bool $closed): array
|
||||
{
|
||||
$today = CarbonImmutable::today();
|
||||
$completed = $booking->status === BookingStatus::Completed;
|
||||
$activities = [];
|
||||
|
||||
if (! $closed && ($booking->isBinding() || $completed)) {
|
||||
$blockers = $booking->isBinding() && ! $completed ? CaseClosure::stayBlockers($booking) : collect();
|
||||
$activities[] = new Activity('closure', $booking->isInternal() && $booking->internal_kind === InternalKind::Block ? 'Sperrzeit abschließen' : 'Aufenthalt abschließen', match (true) {
|
||||
$completed => ActivityState::Done,
|
||||
! $booking->isBinding() || $booking->departure > $today => ActivityState::Later,
|
||||
default => ActivityState::Waiting,
|
||||
}, match (true) {
|
||||
$completed => 'abgeschlossen am '.($booking->completed_at ?? $booking->updated_at)?->format('d.m.Y'),
|
||||
$blockers->isNotEmpty() => 'wartet auf: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', '),
|
||||
$booking->isBinding() && $booking->departure <= $today => 'geschieht automatisch über Nacht – oder jetzt von Hand',
|
||||
default => 'nach der Abreise, sobald nichts mehr für den Aufenthalt offen ist',
|
||||
}, $booking->isBinding() && ! $completed && $booking->departure <= $today ? 'closeStay' : null);
|
||||
}
|
||||
|
||||
$settlementApplies = $completed || $booking->status === BookingStatus::Cancelled;
|
||||
if ($settlementApplies || ($booking->isBinding() && ! $booking->isInternal()) || ($booking->isInternal() && (int) $booking->total > 0)) {
|
||||
$points = $settlementApplies && $booking->settled_at === null ? CaseClosure::commercialPoints($booking) : [];
|
||||
$activities[] = new Activity('settlement', 'Kaufmännisch abschließen', match (true) {
|
||||
$booking->settled_at !== null => ActivityState::Done,
|
||||
! $settlementApplies => ActivityState::Later,
|
||||
default => ActivityState::Waiting,
|
||||
}, match (true) {
|
||||
$booking->settled_at !== null => 'abgeschlossen am '.$booking->settled_at->format('d.m.Y').($booking->settled_by && $booking->settled_by !== CaseClosure::AUTOMATIC ? ' von '.$booking->settled_by : '').($booking->settled_note ? ' · '.$booking->settled_note : ''),
|
||||
! $settlementApplies => 'nach dem Aufenthalt, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind',
|
||||
default => 'offen: '.implode(' ', $points),
|
||||
}, $settlementApplies && $booking->settled_at === null && $points !== [] ? 'settle' : null);
|
||||
}
|
||||
|
||||
return $activities;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tasks shown on the case: every open one, and the done ones of the stay (services, issues, follow-ups) as its record.
|
||||
*
|
||||
* @return iterable<BookingTask>
|
||||
*/
|
||||
private static function tasks(Booking $booking): iterable
|
||||
{
|
||||
return BookingTask::query()->where('booking_id', $booking->id)
|
||||
->where(fn ($query) => $query->where('status', BookingTaskStatus::Open)
|
||||
->orWhere(fn ($done) => $done->where('status', BookingTaskStatus::Done)->whereIn('kind', [BookingTaskKind::Service, BookingTaskKind::Issue, BookingTaskKind::FollowUp, BookingTaskKind::PayoutCheck, BookingTaskKind::OpenClaim])))
|
||||
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Own use, private stay or block (A6): only what such a case has – no contract, no reminders, no reviews.
|
||||
*
|
||||
* @param callable(ActivityState): ActivityState $later
|
||||
* @return list<Activity>
|
||||
*/
|
||||
private static function internal(Booking $booking, bool $closed, callable $later): array
|
||||
{
|
||||
$kind = $booking->internal_kind;
|
||||
$activities = [new Activity('intake', ($kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
|
||||
|
||||
foreach (self::channelTasks($booking) as $task) {
|
||||
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
|
||||
}
|
||||
|
||||
if ($kind !== InternalKind::Block && filled($booking->guest?->email)) {
|
||||
$activities[] = new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $later($booking->confirmation_sent_at !== null ? ActivityState::Done : ActivityState::Later),
|
||||
$booking->confirmation_sent_at ? 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : 'nur bei Bedarf', $booking->confirmation_sent_at === null && ! $closed ? 'sendDocuments' : null);
|
||||
}
|
||||
if ($booking->total !== null && $booking->total > 0) {
|
||||
$paid = $booking->paidAmount();
|
||||
$activities[] = new Activity('payment', 'Zahlung (ohne Erinnerungen)', $later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt');
|
||||
}
|
||||
foreach (self::tasks($booking) as $task) {
|
||||
$activities[] = self::task($task);
|
||||
}
|
||||
$activities[] = new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $closed ? ActivityState::NotApplicable : ($booking->departure <= CarbonImmutable::today() ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
|
||||
|
||||
return [...$activities, ...self::closing($booking, $closed)];
|
||||
}
|
||||
|
||||
/**
|
||||
* An open task of the case and the action that settles it.
|
||||
*/
|
||||
private static function task(BookingTask $task): Activity
|
||||
{
|
||||
$action = match ($task->kind) {
|
||||
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
|
||||
BookingTaskKind::PortalChangeReported => 'change',
|
||||
BookingTaskKind::BookingWish => 'decideWish',
|
||||
BookingTaskKind::ArrivalDetails => 'arrivalDetails',
|
||||
BookingTaskKind::CancellationRequest => 'end',
|
||||
BookingTaskKind::FactConflict => 'provideContact',
|
||||
default => $task->kind->isPayment() ? null : 'completeTask',
|
||||
};
|
||||
$today = CarbonImmutable::today();
|
||||
$state = match (true) {
|
||||
$task->status === BookingTaskStatus::Done => ActivityState::Done,
|
||||
$task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting,
|
||||
$task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later,
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem,
|
||||
// v0.11 (B3): the binding confirmation waits for the missing details as well.
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && CaseRequirements::missing($task->booking, CaseRequirements::WISH_CONFIRMATION) !== [] => ActivityState::Waiting,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$detail = $task->status === BookingTaskStatus::Done
|
||||
? 'erledigt am '.$task->completed_at?->format('d.m.Y').($task->completed_by ? ' von '.$task->completed_by : '').($task->note ? ' · '.$task->note : '')
|
||||
: trim(($state === ActivityState::Problem ? 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. · ' : '').($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->responsible ? ' · zuständig: '.$task->responsible : '').($task->note ? ' · '.$task->note : ''), ' ·');
|
||||
|
||||
return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action);
|
||||
return app(ProcessRunner::class)->activities($booking);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -439,21 +94,4 @@ public static function situation(Booking $booking): string
|
||||
|
||||
return implode(' · ', array_filter([$kind, $state, $when]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Portal tasks for the dates of this case (block when it starts occupying, unblock when it ends).
|
||||
*
|
||||
* @return iterable<ChannelTask>
|
||||
*/
|
||||
private static function channelTasks(Booking $booking): iterable
|
||||
{
|
||||
return ChannelTask::query()
|
||||
->with('channel')
|
||||
->whereHas('channel', fn ($query) => $query->where('property_id', $booking->property_id))
|
||||
->whereDate('starts_on', $booking->arrival)
|
||||
->whereDate('ends_on', $booking->departure)
|
||||
->where('status', '!=', ChannelTaskStatus::Dismissed)
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -2,61 +2,24 @@
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Actions\AutoOffer;
|
||||
use App\Actions\SendBookingDocuments;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Models\Booking;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do
|
||||
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a binding booking
|
||||
* once their composition is complete and needs no confirmation (template released and, for portal bookings, confirmed
|
||||
* as the portal's terms). Whatever stops it is returned in plain
|
||||
* words; the case then shows it as a task. Never touches a case whose profile was taken over from the old data (the
|
||||
* automation did not exist for those cases before).
|
||||
* Facade of the process core (ProcessRunner, trigger 'automation') for the places that carry a case on after new
|
||||
* facts, portal amounts or the landlord's "continue automatically": only what the landlord would do next anyway and
|
||||
* only when the case is handled automatically – the offer or information of a request, the documents of a binding
|
||||
* booking (never for cases taken over from the old data). Whatever stops it is returned in plain words.
|
||||
*/
|
||||
class CaseAutomation
|
||||
{
|
||||
public function __construct(private AutoOffer $autoOffer, private SendBookingDocuments $documents) {}
|
||||
public function __construct(private ProcessRunner $runner) {}
|
||||
|
||||
/**
|
||||
* @return list<string> what keeps the case from going on automatically (empty: nothing to do or done)
|
||||
*/
|
||||
public function advance(Booking $booking): array
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
|
||||
if ($booking->processingMode() !== ProcessingMode::Automatic) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return CaseLog::context(fn (): array => $this->step($booking), actor: CaseLog::SYSTEM.' (automatisch)');
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return ['Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function step(Booking $booking): array
|
||||
{
|
||||
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0 && $booking->intake !== IntakeKind::Booking) {
|
||||
return $this->autoOffer->handle($booking);
|
||||
}
|
||||
|
||||
if ($booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord && $booking->process()->origin !== 'migration') {
|
||||
return $this->documents->automatically($booking);
|
||||
}
|
||||
|
||||
return [];
|
||||
return $this->runner->advance($booking, ProcessRunner::AUTOMATION)->reasons();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Pricing\CaseMoney;
|
||||
@@ -21,6 +23,16 @@
|
||||
*/
|
||||
final class CaseClosure
|
||||
{
|
||||
/** Kinds of financial clarification that allow settling an open portal payout (decision O5). */
|
||||
public const PAYOUT_CLARIFICATIONS = [
|
||||
'offset' => 'Verrechnung dokumentiert',
|
||||
'difference_booked' => 'Differenz geklärt und verbucht',
|
||||
'written_off' => 'Forderung ausgebucht',
|
||||
self::CLAIM_OPEN => 'Als offene Forderung weiterführen',
|
||||
];
|
||||
|
||||
public const CLAIM_OPEN = 'open_claim';
|
||||
|
||||
public const AUTOMATIC = 'automatisch';
|
||||
|
||||
/**
|
||||
@@ -92,8 +104,26 @@ public static function refresh(Booking $booking): void
|
||||
* The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial
|
||||
* tasks are closed with the same note. The reason is required and kept.
|
||||
*/
|
||||
public static function settle(Booking $booking, string $note, string $by): void
|
||||
public static function settle(Booking $booking, string $note, string $by, ?string $clarification = null): void
|
||||
{
|
||||
// Decision O5: with portal collection, an open or deviating payout is settled only after its financial
|
||||
// clarification – a reason alone is not enough, and a portal's report of a payout is no proof of the receipt.
|
||||
$payoutPoints = $booking->status !== BookingStatus::Cancelled && CaseMoney::of($booking)->collector() === Responsibility::Portal
|
||||
? self::portalMoney($booking, CaseMoney::of($booking)) : [];
|
||||
if ($payoutPoints !== [] && ! array_key_exists((string) $clarification, self::PAYOUT_CLARIFICATIONS)) {
|
||||
throw new ReservationException('Bei Inkasso durch das Portal ist der kaufmännische Abschluss erst nach finanzieller Klärung möglich: Auszahlung eingegangen, Verrechnung, verbuchte Differenz oder ausgebuchte Forderung. Offen: '.implode(' ', $payoutPoints));
|
||||
}
|
||||
if ($clarification === self::CLAIM_OPEN) {
|
||||
// The claim stays traceable: an open task of its own, the case stays commercially open.
|
||||
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::OpenClaim, 'status' => BookingTaskStatus::Open], ['tenant_id' => $booking->tenant_id, 'due_on' => today()->addDays(14), 'note' => mb_substr($note, 0, 1000)]);
|
||||
CaseLog::record($booking, 'settled', 'Als offene Forderung weitergeführt', reason: $note, data: ['open_points' => $payoutPoints, 'clarification' => $clarification], actor: $by);
|
||||
|
||||
return;
|
||||
}
|
||||
if ($clarification !== null && isset(self::PAYOUT_CLARIFICATIONS[$clarification])) {
|
||||
$note = self::PAYOUT_CLARIFICATIONS[$clarification].': '.$note;
|
||||
}
|
||||
|
||||
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
|
||||
if ($task->kind->isCommercial()) {
|
||||
$task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Models\Booking;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Everything a process module reads about one case at one moment: the case, its frozen profile and plan, the
|
||||
* parameters of the module and the time. Built fresh for every evaluation – modules keep no state of their own; the
|
||||
* state of a case stays in its data (bookings, case_facts, booking_tasks, data_requests, booking_events).
|
||||
*/
|
||||
final class CaseContext
|
||||
{
|
||||
public readonly ProcessProfile $profile;
|
||||
|
||||
public readonly bool $closed;
|
||||
|
||||
public readonly bool $binding;
|
||||
|
||||
public readonly bool $inquiry;
|
||||
|
||||
public readonly CarbonImmutable $today;
|
||||
|
||||
/** After the end of the case or of its stay: what was not done before is no longer to do. */
|
||||
public readonly bool $over;
|
||||
|
||||
public function __construct(public readonly Booking $booking, public readonly ProcessPlan $plan)
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property', 'payments']);
|
||||
$this->profile = $booking->process();
|
||||
$this->closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
|
||||
$this->binding = $booking->isBinding();
|
||||
$this->inquiry = $booking->intake !== IntakeKind::Booking;
|
||||
$this->today = CarbonImmutable::today();
|
||||
$this->over = $this->closed || $booking->status === BookingStatus::Completed || ($this->binding && $booking->departure->isBefore($this->today));
|
||||
}
|
||||
|
||||
public static function of(Booking $booking): self
|
||||
{
|
||||
return new self($booking, ProcessPlan::of($booking));
|
||||
}
|
||||
|
||||
/**
|
||||
* The central rule of the case's end (package 9): after it, an open step is no longer to do – unless it is done
|
||||
* (by us or externally). Modules apply it where the step belongs to the case's own course.
|
||||
*/
|
||||
public function later(ActivityState $state): ActivityState
|
||||
{
|
||||
return $this->over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter of a module as frozen in the plan (null when the plan does not set it).
|
||||
*/
|
||||
public function parameter(string $module, string $name): mixed
|
||||
{
|
||||
return $this->plan->parameter($module, $name);
|
||||
}
|
||||
}
|
||||
@@ -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: [
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\ChannelBookingModel;
|
||||
use App\Enums\DataRequestMode;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Models\Channel;
|
||||
use App\Process\Models\ProcessModel;
|
||||
use App\Process\Models\Responsibilities;
|
||||
|
||||
/**
|
||||
* What the channel configurator offers and checks (docs/Prozessarchitektur/Architektur/03): per channel and intake
|
||||
* kind the admissible models (portal profile, E2/O2), and per step of the chosen model its switch, mode, performer
|
||||
* and parameters – each control mapped to the existing process setting where one exists, so the inheritance landlord →
|
||||
* property → channel stays the one mechanism. Pure: reads, never writes (ConfigureChannelProcess saves).
|
||||
*/
|
||||
final class ChannelProcessConfiguration
|
||||
{
|
||||
/**
|
||||
* Controls of the steps: mode and performer stored as existing settings, parameters per module.
|
||||
*
|
||||
* @var array<string, array{mode?: ProcessSetting, performer?: array{field: string, setting: ProcessSetting}, parameters?: list<ProcessSetting>}>
|
||||
*/
|
||||
public const STEP_CONTROLS = [
|
||||
'guest.details' => ['parameters' => [ProcessSetting::FormRequiresAddress]],
|
||||
'guest.data_request' => ['mode' => ProcessSetting::DataRequest, 'parameters' => [ProcessSetting::DataRequestReminderHours, ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax, ProcessSetting::GuestLinkValidDays]],
|
||||
'hold' => ['parameters' => [ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes]],
|
||||
'offer.binding' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::HoldHours, ProcessSetting::ContractTemplate]],
|
||||
'offer.information' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::GuestLinkValidDays]],
|
||||
'documents.send' => ['mode' => ProcessSetting::Processing, 'parameters' => [ProcessSetting::ContractTemplate]],
|
||||
'arrival.info' => ['performer' => ['field' => 'guest_messages', 'setting' => ProcessSetting::GuestMessages], 'parameters' => [ProcessSetting::ArrivalInfoDaysBefore]],
|
||||
];
|
||||
|
||||
public function __construct(private ProcessCatalogue $catalogue) {}
|
||||
|
||||
/**
|
||||
* The intake kinds the channel delivers.
|
||||
*
|
||||
* @return list<IntakeKind>
|
||||
*/
|
||||
public function intakes(Channel $channel): array
|
||||
{
|
||||
if ($channel->isWebsite()) {
|
||||
return [IntakeKind::Inquiry];
|
||||
}
|
||||
|
||||
return match ($channel->booking_model) {
|
||||
ChannelBookingModel::Inquiry => [IntakeKind::Inquiry],
|
||||
ChannelBookingModel::PortalBooking => [IntakeKind::Booking],
|
||||
default => [IntakeKind::Inquiry, IntakeKind::Booking],
|
||||
};
|
||||
}
|
||||
|
||||
public function profileKey(Channel $channel): string
|
||||
{
|
||||
if ($channel->isWebsite()) {
|
||||
return 'website';
|
||||
}
|
||||
$chosen = (string) (($channel->settings ?? [])['portal_profile'] ?? '');
|
||||
$profiles = (array) config('channels.portal_profiles');
|
||||
if ($chosen !== '' && array_key_exists($chosen, $profiles)) {
|
||||
return $chosen;
|
||||
}
|
||||
|
||||
$name = mb_strtolower((string) $channel->name);
|
||||
foreach ($profiles as $key => $profile) {
|
||||
foreach ((array) ($profile['match'] ?? []) as $needle) {
|
||||
if (str_contains($name, $needle)) {
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 'generic';
|
||||
}
|
||||
|
||||
/**
|
||||
* The models the landlord may choose for this channel and intake kind.
|
||||
*
|
||||
* @return array<string, ProcessModel>
|
||||
*/
|
||||
public function admissibleModels(Channel $channel, IntakeKind $intake): array
|
||||
{
|
||||
$allowed = (array) (config('channels.portal_profiles.'.$this->profileKey($channel))[$intake->value] ?? []);
|
||||
|
||||
return array_filter($this->catalogue->admissible($intake), fn (ProcessModel $model): bool => in_array($model::key(), $allowed, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a new case of this channel and intake would follow now: the chosen one, or the one derived from the
|
||||
* settings as before (marked as derived).
|
||||
*
|
||||
* @return array{model: string, variant: string, derived: bool}
|
||||
*/
|
||||
public function current(Channel $channel, IntakeKind $intake): array
|
||||
{
|
||||
$config = ProcessPlan::configurationOf($channel, $intake);
|
||||
if (filled($config['model'] ?? null) && $this->catalogue->hasModel((string) $config['model'])) {
|
||||
return ['model' => (string) $config['model'], 'variant' => (string) ($config['variant'] ?? 'standard'), 'derived' => false];
|
||||
}
|
||||
|
||||
$property = $channel->property;
|
||||
$profile = app(ProcessSettings::class)->resolve($property, $channel, $intake);
|
||||
|
||||
return ['model' => $this->catalogue->derivedModel($profile), 'variant' => 'standard', 'derived' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowed values of the performer of a step under the model (variable responsibility), as setting values.
|
||||
*
|
||||
* @return array<string, string> value => label
|
||||
*/
|
||||
public function performerOptions(ProcessModel $model, string $module): array
|
||||
{
|
||||
$control = self::STEP_CONTROLS[$module]['performer'] ?? null;
|
||||
if ($control === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect($model::responsibilities()->allowed($control['field']))
|
||||
->mapWithKeys(fn (Responsibility $value): array => [$value->value => $value === Responsibility::Portal ? 'Portal' : ($value === Responsibility::Landlord ? 'wir (automatisch)' : $value->getLabel())])
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowed modes of a step (as values of its setting).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function modeOptions(string $module): array
|
||||
{
|
||||
return match (self::STEP_CONTROLS[$module]['mode'] ?? null) {
|
||||
ProcessSetting::Processing => collect(ProcessingMode::cases())->mapWithKeys(fn (ProcessingMode $mode): array => [$mode->value => $mode->getLabel()])->all(),
|
||||
ProcessSetting::DataRequest => collect(DataRequestMode::cases())->mapWithKeys(fn (DataRequestMode $mode): array => [$mode->value => $mode->getLabel()])->all(),
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The course a typical new case would take with the given (possibly unsaved) configuration: every step of the model
|
||||
* with whether it takes part and why not, who carries it out and how.
|
||||
*
|
||||
* @param array<string, mixed> $draft model, variant, steps, settings of channels.process_overrides[intake]
|
||||
* @return list<array{module: string, label: string, phase: string, on: bool, reason: ?string, performer: ?string, mode: ?string, toggle: string, tester_only: bool, inserted: bool}>
|
||||
*/
|
||||
public function preview(Channel $channel, IntakeKind $intake, array $draft): array
|
||||
{
|
||||
$model = $this->catalogue->model((string) ($draft['model'] ?? $this->current($channel, $intake)['model']));
|
||||
$variant = (string) ($draft['variant'] ?? 'standard');
|
||||
$profile = $this->profileWith($channel, $intake, $draft);
|
||||
$standard = $model->modules('standard');
|
||||
$rows = [];
|
||||
foreach ($model->modules($variant) as $key) {
|
||||
$class = $this->catalogue->modules()[$key];
|
||||
$definition = $class::definition();
|
||||
$on = ($draft['steps'][$key]['on'] ?? true) !== false || ! $definition->isOptional();
|
||||
$reason = match (true) {
|
||||
! $on => 'im Kanal abgeschaltet',
|
||||
$key === 'hold' && ! $profile->preReservation() => 'keine Vorreservierung in diesem Modell',
|
||||
$key === 'offer.information' && $profile->preReservation() => 'nicht in diesem Modell (verbindliches Angebot)',
|
||||
$key === 'offer.binding' && ! $profile->preReservation() => 'erst, wenn ein Angebot von Hand gesendet wird',
|
||||
$key === 'portal.payout' && $profile->payments() !== Responsibility::Portal => 'wir kassieren selbst',
|
||||
$key === 'review.request' && $profile->guestMessages() !== Responsibility::Landlord => 'das Portal schreibt dem Gast',
|
||||
$key === 'guest.details' && $intake === IntakeKind::Booking && $profile->documents() === Responsibility::Portal && $profile->payments() === Responsibility::Portal && $profile->guestMessages() === Responsibility::Portal => 'wir schreiben dem Gast nicht',
|
||||
default => null,
|
||||
};
|
||||
$mode = isset(self::STEP_CONTROLS[$key]['mode']) ? (string) $profile->value(self::STEP_CONTROLS[$key]['mode']) : (in_array('automatic', $definition->modes, true) ? 'automatic' : null);
|
||||
$performer = match ($key) {
|
||||
'documents.send' => $profile->documents()->value,
|
||||
'payments.monitor' => $profile->payments()->value,
|
||||
'arrival.info' => $profile->guestMessages()->value,
|
||||
default => $definition->performers[0] ?? null,
|
||||
};
|
||||
$rows[] = ['module' => $key, 'label' => $definition->label, 'phase' => $definition->phase, 'on' => $on && $reason === null, 'reason' => $reason,
|
||||
'performer' => $performer, 'mode' => $mode, 'toggle' => $definition->toggle, 'tester_only' => $definition->isTesterOnly(), 'inserted' => ! in_array($key, $standard, true)];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything that is not admissible in a draft (empty = it may be saved).
|
||||
*
|
||||
* @param array<string, mixed> $draft
|
||||
* @return list<string>
|
||||
*/
|
||||
public function problems(Channel $channel, IntakeKind $intake, array $draft, bool $sandbox = false): array
|
||||
{
|
||||
$problems = [];
|
||||
if (! in_array($intake, $this->intakes($channel), true)) {
|
||||
$problems[] = 'Dieser Kanal liefert keine '.($intake === IntakeKind::Booking ? 'festen Buchungen' : 'Anfragen').'.';
|
||||
}
|
||||
$key = (string) ($draft['model'] ?? '');
|
||||
$models = $this->admissibleModels($channel, $intake);
|
||||
if ($key === '' || ! array_key_exists($key, $models)) {
|
||||
return [...$problems, 'Das Ablaufmodell „'.$key.'“ ist für diesen Kanal nicht zulässig. Zulässig: '.(implode(', ', array_map(fn (ProcessModel $model): string => $model::label(), $models)) ?: 'keines').'.'];
|
||||
}
|
||||
$model = $models[$key];
|
||||
$variant = $model->variant((string) ($draft['variant'] ?? 'standard'));
|
||||
if ($variant === null) {
|
||||
return [...$problems, 'Das Modell hat diese Variante nicht.'];
|
||||
}
|
||||
if ($variant->isTesterOnly() && ! $sandbox) {
|
||||
$problems[] = 'Die Variante „'.$variant->label.'“ ist nur im Prozess-Tester verwendbar und kann nicht gespeichert werden.';
|
||||
}
|
||||
|
||||
foreach ((array) ($draft['steps'] ?? []) as $module => $step) {
|
||||
if (! $this->catalogue->hasModule($module) || ! in_array($module, $model->modules($variant->key), true)) {
|
||||
$problems[] = "Der Schritt {$module} gehört nicht zu diesem Modell.";
|
||||
|
||||
continue;
|
||||
}
|
||||
$definition = $this->catalogue->modules()[$module]::definition();
|
||||
if (($step['on'] ?? true) === false && ! $definition->isOptional()) {
|
||||
$problems[] = 'Der Schritt „'.$definition->label.'“ ist Pflicht und kann nicht abgeschaltet werden.';
|
||||
}
|
||||
if ($definition->isTesterOnly() && ! $sandbox && ($step['on'] ?? true) !== false && $variant->isTesterOnly()) {
|
||||
$problems[] = 'Der Schritt „'.$definition->label.'“ ist nur im Prozess-Tester verwendbar.';
|
||||
}
|
||||
}
|
||||
|
||||
// Responsibilities: fixed ones are set by the model; variable ones only to the values the model allows.
|
||||
$responsibilities = $model::responsibilities();
|
||||
foreach (Responsibilities::SETTINGS as $field => $setting) {
|
||||
$value = $draft['settings'][$setting->value] ?? null;
|
||||
if ($value === null || $value === '') {
|
||||
continue;
|
||||
}
|
||||
$responsibility = Responsibility::tryFrom((string) $value);
|
||||
if ($responsibility === null || ! $responsibilities->admits($setting, $responsibility)) {
|
||||
$problems[] = Responsibilities::LABELS[$field].': „'.($responsibility?->getLabel() ?? $value).'“ ist in diesem Modell nicht zulässig.';
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($problems));
|
||||
}
|
||||
|
||||
/**
|
||||
* The profile a new case would get with the draft (model fixes and setting values applied).
|
||||
*
|
||||
* @param array<string, mixed> $draft
|
||||
*/
|
||||
public function profileWith(Channel $channel, IntakeKind $intake, array $draft): ProcessProfile
|
||||
{
|
||||
$preview = clone $channel;
|
||||
$overrides = (array) ($channel->process_overrides ?? []);
|
||||
$overrides[$intake->value] = [...array_filter((array) ($draft['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== ''), 'model' => $draft['model'] ?? null, 'variant' => $draft['variant'] ?? 'standard', 'steps' => (array) ($draft['steps'] ?? [])];
|
||||
$preview->setAttribute('process_overrides', $overrides);
|
||||
|
||||
return app(ProcessSettings::class)->resolve($channel->property, $preview, $intake);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
|
||||
/**
|
||||
* A1 – request on our own way answered with an information "unter Vorbehalt" (package 7).
|
||||
*/
|
||||
final class A1InformationModel extends InquiryModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a1.information';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Unverbindliche Auskunft';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Die Anfrage reserviert nichts; der Gast erhält eine unverbindliche Auskunft, fragt die Buchung an, und wir bestätigen nach erneuter Prüfung verbindlich.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A1];
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['pre_reservation' => false];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
|
||||
/**
|
||||
* A1 – request on our own way (website, direct): reserving request, binding offer, acceptance.
|
||||
*/
|
||||
final class A1OfferModel extends InquiryModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a1.offer';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Angebot mit Vorreservierung';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Die Anfrage reserviert den Zeitraum; sind alle Angaben da, geht das verbindliche Angebot mit Vertragsentwurf an den Gast, der es annimmt.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A1];
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['pre_reservation' => true];
|
||||
}
|
||||
|
||||
public function variants(): array
|
||||
{
|
||||
return [
|
||||
Variant::make('standard', 'Angebot mit Vorreservierung'),
|
||||
Variant::make('loyalty', 'Angebot mit Stammgastrabatt (Architekturnachweis, nur im Prozess-Tester)')
|
||||
->testerOnly()
|
||||
->insert(Point::AfterGuestIdentified, 'guest.loyalty_status')
|
||||
->insert(Point::BeforePriceFixing, 'pricing.loyalty_discount'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* A2 – request of an intermediary answered with an information.
|
||||
*/
|
||||
final class A2InformationModel extends InquiryModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a2.information';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Portalanfrage mit Auskunft';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Die Anfrage eines Portals wird mit einer unverbindlichen Auskunft beantwortet; verbindlich wird erst die Bestätigung des Buchungswunsches.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A2];
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['pre_reservation' => false];
|
||||
}
|
||||
|
||||
protected static function guestMessageOptions(): array
|
||||
{
|
||||
return [Responsibility::Landlord, Responsibility::Portal];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* A2 – request of an intermediary answered with our own binding offer.
|
||||
*/
|
||||
final class A2OfferModel extends InquiryModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a2.offer';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Portalanfrage mit Angebot';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Die Anfrage eines Portals wird wie eine eigene behandelt: fehlende Angaben ergänzen, Zeitraum reservieren, verbindliches Angebot, Annahme.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A2];
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['pre_reservation' => true];
|
||||
}
|
||||
|
||||
protected static function guestMessageOptions(): array
|
||||
{
|
||||
return [Responsibility::Landlord, Responsibility::Portal];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* A3 – binding portal booking with our own handling (e.g. Destination Solutions, R08).
|
||||
*/
|
||||
final class A3PortalBookingModel extends PortalBookingModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a3.portal_booking';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Portalbuchung, eigene Abwicklung';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Das Portal bestätigt verbindlich; Vertragsunterlagen, Zahlungsforderung und -überwachung sowie Gastkommunikation übernehmen wir.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A3];
|
||||
}
|
||||
|
||||
public static function responsibilities(): Responsibilities
|
||||
{
|
||||
return Responsibilities::of(
|
||||
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Landlord, 'contract_documents' => Responsibility::Landlord],
|
||||
variable: ['guest_messages' => [Responsibility::Landlord], 'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody], 'local_services' => [Responsibility::Landlord]],
|
||||
);
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['payments' => 'landlord', 'documents' => 'landlord'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* A4 – binding portal booking with shared handling: portal collection, our contract documentation (e.g. FeWo-direkt, R09).
|
||||
*/
|
||||
final class A4PortalBookingModel extends PortalBookingModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a4.portal_booking';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Portalbuchung, Inkasso beim Portal';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Das Portal bestätigt verbindlich und zieht das Geld des Gastes ein; die Vertragsdokumentation senden wir. Kommunikation, ergänzende Unterlagen und Anreiseinformation sind wählbar; die Auszahlung prüfen wir.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A4];
|
||||
}
|
||||
|
||||
public static function responsibilities(): Responsibilities
|
||||
{
|
||||
return Responsibilities::of(
|
||||
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Portal, 'contract_documents' => Responsibility::Landlord],
|
||||
variable: ['guest_messages' => [Responsibility::Landlord, Responsibility::Portal], 'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody], 'local_services' => [Responsibility::Landlord]],
|
||||
);
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['payments' => 'portal', 'documents' => 'landlord'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* A5 – binding portal booking handled largely by the portal: collection and contract documentation at the portal.
|
||||
*/
|
||||
final class A5PortalBookingModel extends PortalBookingModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a5.portal_booking';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Portalbuchung, weitgehend beim Portal';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Das Portal bestätigt verbindlich, zieht das Geld ein und liefert die Vertragsunterlagen; wir übernehmen nur die eigenen lokalen Aufgaben und prüfen die Auszahlung.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A5];
|
||||
}
|
||||
|
||||
public static function responsibilities(): Responsibilities
|
||||
{
|
||||
return Responsibilities::of(
|
||||
fixed: ['contract' => Responsibility::Portal, 'collection' => Responsibility::Portal, 'contract_documents' => Responsibility::Portal],
|
||||
variable: ['guest_messages' => [Responsibility::Portal, Responsibility::Landlord], 'supplementary_documents' => [Responsibility::Nobody, Responsibility::Landlord], 'local_services' => [Responsibility::Landlord]],
|
||||
);
|
||||
}
|
||||
|
||||
public static function fixes(): array
|
||||
{
|
||||
return ['payments' => 'portal', 'documents' => 'portal'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\IntakeKind;
|
||||
|
||||
/**
|
||||
* A6 – own use, private stay or block (E-022/E-024): no contract, no reminders, no reviews; channels are blocked, an
|
||||
* optional stay confirmation and a payment without reminders. Has no channel configuration.
|
||||
*/
|
||||
final class A6InternalModel extends ProcessModel
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'a6.internal';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Eigenbelegung, private Überlassung, Sperre';
|
||||
}
|
||||
|
||||
public static function description(): string
|
||||
{
|
||||
return 'Eigene Nutzung, privater Aufenthalt oder Sperrzeit: Kanäle sperren, bei Bedarf Aufenthaltsbestätigung und Zahlung ohne Erinnerungen.';
|
||||
}
|
||||
|
||||
public static function caseTypes(): array
|
||||
{
|
||||
return [CaseType::A6];
|
||||
}
|
||||
|
||||
public static function intakes(): array
|
||||
{
|
||||
return [IntakeKind::Internal];
|
||||
}
|
||||
|
||||
public static function responsibilities(): Responsibilities
|
||||
{
|
||||
return Responsibilities::of([]);
|
||||
}
|
||||
|
||||
public function steps(): array
|
||||
{
|
||||
return [
|
||||
Step::module('intake.record'),
|
||||
Step::module('channels.block'),
|
||||
Step::module('documents.stay_confirmation'),
|
||||
Step::module('payments.internal'),
|
||||
Step::module('case.tasks'),
|
||||
Step::module('stay'),
|
||||
Step::module('case.closure'),
|
||||
Step::module('case.settlement'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* Common course of a request answered on our own way (A1 direct/website, A2 via an intermediary): intake, guest's
|
||||
* details, hold and availability, our answer (binding offer or information), acceptance, then the binding booking with
|
||||
* our contract documentation, payments, stay and closing. The variants of A1/A2 share it; the models differ by intake
|
||||
* channel and what they fix.
|
||||
*/
|
||||
abstract class InquiryModel extends ProcessModel
|
||||
{
|
||||
public static function intakes(): array
|
||||
{
|
||||
return [IntakeKind::Inquiry];
|
||||
}
|
||||
|
||||
public static function responsibilities(): Responsibilities
|
||||
{
|
||||
return Responsibilities::of(
|
||||
fixed: ['contract' => Responsibility::Landlord, 'collection' => Responsibility::Landlord, 'contract_documents' => Responsibility::Landlord],
|
||||
variable: [
|
||||
'guest_messages' => static::guestMessageOptions(),
|
||||
'supplementary_documents' => [Responsibility::Landlord, Responsibility::Nobody],
|
||||
'local_services' => [Responsibility::Landlord],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who may write to the guest: ourselves; via an intermediary also its messaging.
|
||||
*
|
||||
* @return list<Responsibility>
|
||||
*/
|
||||
protected static function guestMessageOptions(): array
|
||||
{
|
||||
return [Responsibility::Landlord];
|
||||
}
|
||||
|
||||
public function steps(): array
|
||||
{
|
||||
return [
|
||||
Step::module('intake.record'),
|
||||
Step::module('guest.details'),
|
||||
Step::point(Point::AfterGuestIdentified),
|
||||
Step::module('hold'),
|
||||
Step::module('availability.check'),
|
||||
Step::module('offer.information'),
|
||||
Step::point(Point::BeforePriceFixing),
|
||||
Step::module('offer.binding'),
|
||||
Step::point(Point::BeforeBindingOffer),
|
||||
Step::module('offer.acceptance'),
|
||||
Step::point(Point::AfterBinding),
|
||||
...self::bindingCourse(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* What follows once a case is binding – shared with the portal bookings.
|
||||
*
|
||||
* @return list<Step>
|
||||
*/
|
||||
public static function bindingCourse(): array
|
||||
{
|
||||
return [
|
||||
Step::module('documents.send'),
|
||||
Step::module('channels.block'),
|
||||
Step::module('payments.monitor'),
|
||||
Step::module('portal.payout'),
|
||||
Step::module('case.tasks'),
|
||||
Step::module('change.proposal'),
|
||||
Step::module('arrival.details'),
|
||||
Step::module('arrival.info'),
|
||||
Step::module('guest.data_request'),
|
||||
Step::point(Point::BeforeStay),
|
||||
Step::module('stay'),
|
||||
Step::module('review.request'),
|
||||
Step::point(Point::BeforeSettlement),
|
||||
Step::module('case.closure'),
|
||||
Step::module('case.settlement'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
/**
|
||||
* The fixed extension points of the process models (docs/Prozessarchitektur/Architektur/02 §5.1). A point guarantees
|
||||
* what a module inserted there can rely on – BeforePriceFixing: the case is not binding yet; AfterBinding: it is.
|
||||
* Adding a point changes every model that offers it (stage 4 of the module criteria, 02 §2).
|
||||
*/
|
||||
enum Point: string
|
||||
{
|
||||
case AfterGuestIdentified = 'after_guest_identified';
|
||||
case BeforePriceFixing = 'before_price_fixing';
|
||||
case BeforeBindingOffer = 'before_binding_offer';
|
||||
case AfterBinding = 'after_binding';
|
||||
case BeforeStay = 'before_stay';
|
||||
case BeforeSettlement = 'before_settlement';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::AfterGuestIdentified => 'nach der Identifikation des Gastes',
|
||||
self::BeforePriceFixing => 'vor der Preisfestlegung',
|
||||
self::BeforeBindingOffer => 'vor dem verbindlichen Angebot',
|
||||
self::AfterBinding => 'nach der Verbindlichkeit',
|
||||
self::BeforeStay => 'vor dem Aufenthalt',
|
||||
self::BeforeSettlement => 'vor dem Abschluss',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
|
||||
/**
|
||||
* Common course of a booking that is already binding at a portal (A3–A5, E-036): no second acceptance and no own
|
||||
* price – the portal's total is taken over. What follows is the binding course shared with our own requests; who
|
||||
* answers for collection and contract documentation is fixed by the concrete model (decision O1).
|
||||
*/
|
||||
abstract class PortalBookingModel extends ProcessModel
|
||||
{
|
||||
public static function intakes(): array
|
||||
{
|
||||
return [IntakeKind::Booking];
|
||||
}
|
||||
|
||||
public function steps(): array
|
||||
{
|
||||
return [
|
||||
Step::module('intake.record'),
|
||||
Step::module('guest.details'),
|
||||
Step::point(Point::AfterGuestIdentified),
|
||||
Step::module('binding.portal'),
|
||||
Step::point(Point::AfterBinding),
|
||||
...InquiryModel::bindingCourse(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessSetting;
|
||||
|
||||
/**
|
||||
* A centrally defined, versioned process model (docs/Prozessarchitektur/Architektur/02 §5): its course of steps with
|
||||
* extension points, its admissible variants and the responsibilities it fixes. The case type stays the derived
|
||||
* classification (ProcessProfile::caseTypeFor); a model only declares which case types it is admissible for.
|
||||
* The landlord chooses among models, he never defines one.
|
||||
*/
|
||||
abstract class ProcessModel
|
||||
{
|
||||
abstract public static function key(): string;
|
||||
|
||||
abstract public static function version(): int;
|
||||
|
||||
abstract public static function label(): string;
|
||||
|
||||
abstract public static function description(): string;
|
||||
|
||||
/** @return list<CaseType> */
|
||||
abstract public static function caseTypes(): array;
|
||||
|
||||
/** @return list<IntakeKind> */
|
||||
abstract public static function intakes(): array;
|
||||
|
||||
abstract public static function responsibilities(): Responsibilities;
|
||||
|
||||
/** @return list<Step> */
|
||||
abstract public function steps(): array;
|
||||
|
||||
/**
|
||||
* Settings the model fixes for its cases (e.g. the pre-reservation of the offer model).
|
||||
*
|
||||
* @return array<string, string|int|bool>
|
||||
*/
|
||||
public static function fixes(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Variant>
|
||||
*/
|
||||
public function variants(): array
|
||||
{
|
||||
return [Variant::make('standard', 'Standard')];
|
||||
}
|
||||
|
||||
public function variant(string $key): ?Variant
|
||||
{
|
||||
foreach ($this->variants() as $variant) {
|
||||
if ($variant->key === $key) {
|
||||
return $variant;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The modules of the course in order, with the variant's modules at their points.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function modules(?string $variant = 'standard'): array
|
||||
{
|
||||
$chosen = $this->variant($variant ?? 'standard');
|
||||
$modules = [];
|
||||
foreach ($this->steps() as $step) {
|
||||
if ($step->isPoint()) {
|
||||
array_push($modules, ...($chosen?->modulesAt($step->point) ?? []));
|
||||
} else {
|
||||
$modules[] = $step->module;
|
||||
}
|
||||
}
|
||||
|
||||
return $modules;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Point>
|
||||
*/
|
||||
public function points(): array
|
||||
{
|
||||
return array_values(array_map(fn (Step $step): Point => $step->point, array_filter($this->steps(), fn (Step $step): bool => $step->isPoint())));
|
||||
}
|
||||
|
||||
public static function reference(): string
|
||||
{
|
||||
return static::key().'@'.static::version();
|
||||
}
|
||||
|
||||
/** Whether the model fixes the setting (the configurator shows it, but not as a choice). */
|
||||
public static function fixesSetting(ProcessSetting $setting): bool
|
||||
{
|
||||
return array_key_exists($setting->value, static::fixes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
|
||||
/**
|
||||
* Who answers for what in a model (docs/Prozessarchitektur/Architektur/03 §2.3, decision E1/O1). The model fixes the
|
||||
* responsibilities that decide the case type – contract, collection of the guest's money, binding contract
|
||||
* documentation – and allows a set of values for the others; the configurator offers exactly these values at the step.
|
||||
*/
|
||||
final class Responsibilities
|
||||
{
|
||||
/** Responsibility fields that exist today as process settings. */
|
||||
public const SETTINGS = [
|
||||
'collection' => ProcessSetting::Payments,
|
||||
'contract_documents' => ProcessSetting::Documents,
|
||||
'guest_messages' => ProcessSetting::GuestMessages,
|
||||
];
|
||||
|
||||
public const LABELS = [
|
||||
'contract' => 'Vertragsabschluss',
|
||||
'collection' => 'Inkasso (Geld des Gastes)',
|
||||
'contract_documents' => 'Vertragsdokumentation',
|
||||
'supplementary_documents' => 'Ergänzende Gastunterlagen',
|
||||
'guest_messages' => 'Gastkommunikation und Anreiseinformation',
|
||||
'local_services' => 'Lokale Leistungen',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, Responsibility> $fixed
|
||||
* @param array<string, list<Responsibility>> $variable
|
||||
*/
|
||||
private function __construct(public readonly array $fixed, public readonly array $variable) {}
|
||||
|
||||
/**
|
||||
* @param array<string, Responsibility> $fixed
|
||||
* @param array<string, list<Responsibility>> $variable
|
||||
*/
|
||||
public static function of(array $fixed, array $variable = []): self
|
||||
{
|
||||
return new self($fixed, $variable);
|
||||
}
|
||||
|
||||
public function isFixed(string $field): bool
|
||||
{
|
||||
return array_key_exists($field, $this->fixed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The values the configurator may offer for a field (one value when the model fixes it).
|
||||
*
|
||||
* @return list<Responsibility>
|
||||
*/
|
||||
public function allowed(string $field): array
|
||||
{
|
||||
return $this->isFixed($field) ? [$this->fixed[$field]] : ($this->variable[$field] ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a setting value fits the model (used by the configurator and by the plausibility check of a plan).
|
||||
*/
|
||||
public function admits(ProcessSetting $setting, Responsibility $value): bool
|
||||
{
|
||||
$field = array_search($setting, self::SETTINGS, true);
|
||||
|
||||
return $field === false || $this->allowed($field) === [] || in_array($value, $this->allowed($field), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
/**
|
||||
* One entry of a model's course: a module or an extension point where variants insert modules.
|
||||
*/
|
||||
final readonly class Step
|
||||
{
|
||||
private function __construct(public ?string $module, public ?Point $point) {}
|
||||
|
||||
public static function module(string $key): self
|
||||
{
|
||||
return new self($key, null);
|
||||
}
|
||||
|
||||
public static function point(Point $point): self
|
||||
{
|
||||
return new self(null, $point);
|
||||
}
|
||||
|
||||
public function isPoint(): bool
|
||||
{
|
||||
return $this->point !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Models;
|
||||
|
||||
/**
|
||||
* An admissible variant of a model: further modules at its extension points, the same case type. A variant marked
|
||||
* tester-only can be configured as a draft and played through in the process tester, never frozen into a real case.
|
||||
*/
|
||||
final class Variant
|
||||
{
|
||||
/** @var array<string, list<string>> point value => module keys */
|
||||
private array $inserts = [];
|
||||
|
||||
private bool $testerOnly = false;
|
||||
|
||||
private function __construct(public readonly string $key, public readonly string $label) {}
|
||||
|
||||
public static function make(string $key, string $label): self
|
||||
{
|
||||
return new self($key, $label);
|
||||
}
|
||||
|
||||
public function insert(Point $point, string $module): self
|
||||
{
|
||||
$this->inserts[$point->value][] = $module;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function testerOnly(): self
|
||||
{
|
||||
$this->testerOnly = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isTesterOnly(): bool
|
||||
{
|
||||
return $this->testerOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function modulesAt(Point $point): array
|
||||
{
|
||||
return $this->inserts[$point->value] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function inserts(): array
|
||||
{
|
||||
return $this->inserts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Process\CaseContext;
|
||||
|
||||
/**
|
||||
* A module that adds lines to the price before it is fixed (extension point BeforePriceFixing). CasePricing asks it only
|
||||
* for cases that are not binding yet; once the offer is made the lines are frozen in the case's quote.
|
||||
*/
|
||||
interface ContributesToPrice
|
||||
{
|
||||
/**
|
||||
* @return list<QuoteLine> lines to add (empty: no contribution)
|
||||
*/
|
||||
public function priceLines(CaseContext $case, PriceQuote $quote): array;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
/**
|
||||
* A dependency of one step on another (requirement T1, docs/Prozessarchitektur/Architektur/02 §7.1).
|
||||
*
|
||||
* - **hard:** the step may only run when the other step is done. Nothing switches this off – there is no flag on the
|
||||
* other step that could lift it.
|
||||
* - **soft:** the step should run after the other one when both are due in the same round; when the other one waits,
|
||||
* fails or does not apply, the step goes on as long as its own requirements are met.
|
||||
*
|
||||
* Independent steps simply declare no dependency on each other; conditional steps express their condition in
|
||||
* {@see ProcessModule::applies()}.
|
||||
*/
|
||||
final readonly class Dependency
|
||||
{
|
||||
private function __construct(public string $module, public bool $hard) {}
|
||||
|
||||
public static function hard(string $module): self
|
||||
{
|
||||
return new self($module, true);
|
||||
}
|
||||
|
||||
public static function soft(string $module): self
|
||||
{
|
||||
return new self($module, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
|
||||
/**
|
||||
* P01/P02: the dates are free (calendar truth of AvailabilityChecker, fresh imports by CalendarClearance). Mandatory
|
||||
* and never switched off; the offer depends on it hard.
|
||||
*/
|
||||
final class AvailabilityCheck extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'availability.check';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Verfügbarkeit',
|
||||
purpose: 'Prüft, ob der Zeitraum frei ist und die Kalender der Portale aktuell sind.',
|
||||
phase: 'P01',
|
||||
effects: ['network'],
|
||||
triggers: ['intake', 'facts.applied'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->inquiry && ! $case->binding;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return app(AvailabilityChecker::class)->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking) ? StepState::Done : StepState::Problem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
|
||||
/**
|
||||
* Blocking and releasing the dates in portals that need it by hand (requires_manual_blocking): the tasks come from the
|
||||
* observers (CreateChannelTasks) and are proven per portal (ChannelTaskProof). Mandatory, never switched off.
|
||||
*/
|
||||
final class ChannelBlocks extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'channels.block';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Andere Kanäle sperren',
|
||||
purpose: 'Sperrt den Zeitraum in Portalen, die nicht automatisch abgleichen, und gibt ihn bei Ende wieder frei – mit Nachweis je Portal.',
|
||||
phase: 'P02',
|
||||
effects: ['channel_task', 'landlord_mail', 'network'],
|
||||
waits: ['landlord', 'portal'],
|
||||
triggers: ['booking.occupies', 'booking.released'],
|
||||
performers: ['landlord', 'system'],
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return ChannelTask::query()
|
||||
->with('channel')
|
||||
->whereHas('channel', fn ($query) => $query->where('property_id', $booking->property_id))
|
||||
->whereDate('starts_on', $booking->arrival)
|
||||
->whereDate('ends_on', $booking->departure)
|
||||
->where('status', '!=', ChannelTaskStatus::Dismissed)
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (ChannelTask $task): Activity => new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl()))
|
||||
->all();
|
||||
}
|
||||
|
||||
/** Listed on its own in the work list; it never holds another step back. */
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Actions\RequestCaseData;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Models\DataRequest;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
use App\Process\Modules\StepState;
|
||||
use App\Process\StepResult;
|
||||
|
||||
/**
|
||||
* P01: asks the guest for missing details by link and reminds (v0.11). It runs in its own mode (automatic / after
|
||||
* release / by hand) whatever the case's processing is, and independently of the other steps: a clarification hold
|
||||
* keeps its deadline while the request waits for the guest.
|
||||
*/
|
||||
final class GuestDataRequest extends Module implements RunsAutomatically
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'guest.data_request';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Fehlende Angaben beim Gast anfragen',
|
||||
purpose: 'Fragt fehlende Pflichtangaben per Link beim Gast an, erinnert und übergibt an Sie, wenn der Gast nicht antwortet.',
|
||||
phase: 'P01',
|
||||
requires: [Dependency::hard('intake.record')],
|
||||
effects: ['case_write', 'guest_mail'],
|
||||
waits: ['guest', 'landlord', 'time'],
|
||||
triggers: ['request.created', 'booking.taken_over', 'wish'],
|
||||
parameters: [ProcessSetting::DataRequest, ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax, ProcessSetting::DataRequestReminderHours, ProcessSetting::GuestLinkValidDays],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
performers: ['system', 'landlord'],
|
||||
modes: ['automatic', 'approval', 'manual'],
|
||||
events: ['data_request', 'mail_in', 'facts', 'fact'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown as a step of its own only for a binding booking (a request shows it inside the guest's details).
|
||||
*/
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$request = $case->binding ? $case->booking->openDataRequest() : null;
|
||||
if ($request === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $case->later($request->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open),
|
||||
implode(', ', CaseRequirements::labels($request->fields)).' · '.$request->statusLabel(), $request->status === DataRequest::OPEN ? null : 'approveDataRequest')];
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
$request = $case->booking->openDataRequest();
|
||||
|
||||
return match (true) {
|
||||
$request === null => RequestCaseData::needs($case->booking) === null ? StepState::Done : StepState::Open,
|
||||
$request->status === DataRequest::OPEN => StepState::Waiting,
|
||||
default => StepState::Open,
|
||||
};
|
||||
}
|
||||
|
||||
public function due(CaseContext $case): bool
|
||||
{
|
||||
return RequestCaseData::needs($case->booking) !== null && $case->booking->openDataRequest() === null;
|
||||
}
|
||||
|
||||
public function blockers(CaseContext $case): array
|
||||
{
|
||||
return CaseRequirements::isValid('guest.email', $case->booking->guest?->email) ? [] : ['Die E-Mail-Adresse des Gastes fehlt.'];
|
||||
}
|
||||
|
||||
public function run(CaseContext $case): StepResult
|
||||
{
|
||||
$request = app(RequestCaseData::class)->forNextStep($case->booking);
|
||||
|
||||
return $request === null ? StepResult::blocked(['Nichts anzufragen.']) : StepResult::ran();
|
||||
}
|
||||
|
||||
public function isOutward(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Models\DataRequest;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P01: who the guest is and whether every detail the next step needs is there and valid (v0.11 G2a). The details
|
||||
* themselves come in through the common fact intake (ContributeCaseFacts) from every source.
|
||||
*/
|
||||
final class GuestDetails extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'guest.details';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Angaben des Gastes',
|
||||
purpose: 'Identifiziert den Gast, führt seine Angaben aus allen Quellen zusammen und prüft, ob alles für den nächsten Schritt da ist.',
|
||||
phase: 'P01',
|
||||
requires: [Dependency::hard('intake.record')],
|
||||
effects: ['case_write'],
|
||||
waits: ['guest', 'landlord'],
|
||||
triggers: ['facts.applied'],
|
||||
parameters: [ProcessSetting::FormRequiresAddress],
|
||||
performers: ['guest', 'landlord'],
|
||||
events: ['facts', 'fact', 'guest', 'data_request', 'mail_in'],
|
||||
);
|
||||
}
|
||||
|
||||
/** We correspond with the guest ourselves (a request, or our documents, messages or payments). */
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
$profile = $case->profile;
|
||||
|
||||
return $case->inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$profile = $case->profile;
|
||||
$hasEmail = filled($booking->guest?->email);
|
||||
// v0.11 (G2a): before the own binding offer – or the binding confirmation of a wish – every required detail.
|
||||
$action = $profile->preReservation() || $booking->offer_version > 0 ? CaseRequirements::OFFER : CaseRequirements::WISH_CONFIRMATION;
|
||||
$needsDetails = $case->inquiry && ! $case->binding && $booking->offer_version === 0 && ($action === CaseRequirements::OFFER || $booking->wish_at !== null);
|
||||
$missing = $hasEmail && $needsDetails ? CaseRequirements::missing($booking, $action) : [];
|
||||
$request = $booking->openDataRequest();
|
||||
$asked = $booking->contact_requested_at !== null || $request?->status === DataRequest::OPEN;
|
||||
$state = match (true) {
|
||||
$hasEmail && $missing === [] => ActivityState::Done,
|
||||
$asked => ActivityState::Waiting,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$title = match (true) {
|
||||
$booking->guest === null => 'Name und Kontaktdaten des Gastes eintragen',
|
||||
! $hasEmail => 'E-Mail-Adresse des Gastes eintragen',
|
||||
$missing !== [] => $action === CaseRequirements::OFFER ? 'Angaben für das Angebot vervollständigen' : 'Angaben für die Bestätigung vervollständigen',
|
||||
default => 'Kontaktdaten des Gastes',
|
||||
};
|
||||
$detail = match (true) {
|
||||
$state === ActivityState::Done => $booking->guestName(),
|
||||
$missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($request !== null ? ' · '.$request->statusLabel() : ($asked ? ' · beim Gast angefragt' : '')),
|
||||
$booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'),
|
||||
default => 'fehlt noch',
|
||||
};
|
||||
// A prepared data request waits for the landlord's release: that is the next step, otherwise entering the details.
|
||||
$draft = $needsDetails && $request?->status === DataRequest::DRAFT;
|
||||
|
||||
return [new Activity('contact', $title, $case->later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact'))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Models\Booking;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
|
||||
/**
|
||||
* P01/P02: the hold of a request – clarification hold of an incomplete request or offer hold – and its deadline. It is
|
||||
* set by the intake (RequestHold under the calendar lock) and by SendOffer, it ends by ExpireReservations or the
|
||||
* release; this step only watches it. It depends on the intake alone, never on the guest's details, so a request that
|
||||
* waits for its address keeps its clarification hold running (requirement K1/T1).
|
||||
*/
|
||||
final class Hold extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'hold';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Reservierung des Zeitraums',
|
||||
purpose: 'Hält den Zeitraum während der Klärung bzw. der Angebotsfrist frei und gibt ihn nach Ablauf wieder frei.',
|
||||
phase: 'P01',
|
||||
requires: [Dependency::hard('intake.record')],
|
||||
effects: ['calendar_hold'],
|
||||
waits: ['time'],
|
||||
triggers: ['intake', 'offer.sent', 'schedule:bookings:expire-holds'],
|
||||
parameters: [ProcessSetting::PreReservation, ProcessSetting::HoldHours, ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes],
|
||||
toggle: ModuleDefinition::TOGGLE_CONDITIONAL,
|
||||
events: ['hold'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->inquiry && $case->profile->preReservation();
|
||||
}
|
||||
|
||||
/** The hold has no line of its own: the offer step and the situation show it. */
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return match (true) {
|
||||
$booking->isHoldActive() => StepState::Waiting,
|
||||
$booking->hold_expires_at === null && $booking->hold_purpose === Booking::HOLD_CLARIFICATION => StepState::NotApplicable,
|
||||
default => StepState::Done,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P01: the case came in – request, portal booking or internal occasion. Recording it (and the hold of a request,
|
||||
* under the calendar lock) is done by the intake actions; the step only shows it.
|
||||
*/
|
||||
final class IntakeRecord extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'intake.record';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Eingang',
|
||||
purpose: 'Hält den Eingang der Anfrage, Buchung oder Eigenbelegung fest und friert den Ablauf ein.',
|
||||
phase: 'P01',
|
||||
effects: ['case_write', 'calendar_hold'],
|
||||
triggers: ['intake'],
|
||||
events: ['created', 'intake', 'profile', 'hold', 'mode'],
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
if ($booking->isInternal()) {
|
||||
return [new Activity('intake', ($booking->internal_kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
|
||||
}
|
||||
|
||||
return [new Activity('intake', $case->inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Intake;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* P02 for A3–A5: the booking is binding at the portal (E-036) – no second acceptance, no own price. The guest's total
|
||||
* comes "laut Portal" (RecordPortalAmounts) and is never recalculated.
|
||||
*/
|
||||
final class PortalBinding extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'binding.portal';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Verbindlichkeit beim Portal',
|
||||
purpose: 'Stellt fest, dass die Buchung beim Portal verbindlich ist, und übernimmt den Gesamtpreis laut Portal.',
|
||||
phase: 'P02',
|
||||
requires: [Dependency::hard('intake.record')],
|
||||
effects: ['case_write'],
|
||||
waits: ['portal', 'landlord'],
|
||||
triggers: ['intake', 'portal.amounts'],
|
||||
performers: ['portal', 'landlord'],
|
||||
events: ['status', 'portal_signal', 'price', 'amount'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return ! $case->inquiry;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return [
|
||||
new Activity('binding', 'Beim Portal fest gebucht', $case->binding || $case->closed ? ActivityState::External : ActivityState::Open, $booking->portal_reference ? 'Buchungsnummer '.$booking->portal_reference : null, $case->binding ? null : 'confirm'),
|
||||
new Activity('price', 'Gesamtpreis laut Portal eintragen', $case->later($booking->total === null ? ActivityState::Open : ActivityState::Done), $booking->total === null ? 'noch nicht bekannt' : Money::format($booking->total), $booking->total === null ? 'portalPrice' : null),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Loyalty;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\ContributesToPrice;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* Architecture proof (decision E7): a returning guest's discount as a Discount line before the price is fixed. Tester
|
||||
* only. Test assumptions (E5/E6, not released business rules): a percentage of the rent with a cap; no discount when the
|
||||
* quote already has a special offer discount; once the offer is made the line is frozen in the quote and never
|
||||
* recalculated (also not when the booking changes).
|
||||
*/
|
||||
final class LoyaltyDiscount extends Module implements ContributesToPrice
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'pricing.loyalty_discount';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Stammgastrabatt',
|
||||
purpose: 'Gewährt Stammgästen einen Rabatt auf die Miete, bevor der Preis festgelegt wird (Architekturnachweis, nur im Prozess-Tester).',
|
||||
phase: 'P02',
|
||||
requires: [Dependency::hard('guest.loyalty_status')],
|
||||
effects: [],
|
||||
parameters: ['percent', 'max'],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
points: ['before_price_fixing'],
|
||||
readsContractData: true,
|
||||
availability: ModuleDefinition::AVAILABILITY_TESTER_ONLY,
|
||||
);
|
||||
}
|
||||
|
||||
public function priceLines(CaseContext $case, PriceQuote $quote): array
|
||||
{
|
||||
$status = app(LoyaltyStatusCheck::class)->status($case);
|
||||
if ($status['status'] !== LoyaltyStatusCheck::QUALIFIED || $quote->discount() > 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$percent = (int) ($case->parameter(self::key(), 'percent') ?? 5);
|
||||
$max = (int) ($case->parameter(self::key(), 'max') ?? 10000);
|
||||
$amount = min($max, (int) round($quote->rent() * $percent / 100));
|
||||
if ($amount <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [new QuoteLine(QuoteLineType::Discount, 'Stammgastrabatt '.$percent.' % ('.count($status['stays']).' frühere Aufenthalte)', 1, -$amount, -$amount)];
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$line = collect((array) ($case->booking->quote['lines'] ?? []))->first(fn (array $line): bool => str_starts_with((string) ($line['label'] ?? ''), 'Stammgastrabatt'));
|
||||
|
||||
return [new Activity('loyalty_discount', 'Stammgastrabatt', ActivityState::Done, $line !== null ? Money::format(-(int) $line['amount']).' im Angebot' : 'kein Rabatt im Angebot')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Loyalty;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
|
||||
/**
|
||||
* Architecture proof (decision E7, docs/Prozessarchitektur/Architektur/02 §6): whether the guest is a returning guest –
|
||||
* completed, not cancelled stays of the same guest e-mail at the same landlord within the look-back. Tester only: never
|
||||
* part of a real case's plan. The status is derived from the stays on every evaluation (no second truth); the rules
|
||||
* (count, look-back) are test assumptions, not released business rules.
|
||||
*/
|
||||
final class LoyaltyStatusCheck extends Module
|
||||
{
|
||||
public const QUALIFIED = 'qualified';
|
||||
|
||||
public const NOT_QUALIFIED = 'not_qualified';
|
||||
|
||||
public const UNKNOWN = 'unknown';
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'guest.loyalty_status';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Stammgaststatus feststellen',
|
||||
purpose: 'Stellt fest, ob der Gast schon bei Ihnen zu Gast war (Architekturnachweis, nur im Prozess-Tester).',
|
||||
phase: 'P01',
|
||||
requires: [Dependency::hard('guest.details')],
|
||||
triggers: ['facts.applied'],
|
||||
parameters: ['min_stays', 'lookback_years'],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
events: ['facts'],
|
||||
points: ['after_guest_identified'],
|
||||
availability: ModuleDefinition::AVAILABILITY_TESTER_ONLY,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{status: string, stays: list<string>}
|
||||
*/
|
||||
public function status(CaseContext $case): array
|
||||
{
|
||||
$email = mb_strtolower(trim((string) $case->booking->guest?->email));
|
||||
if ($email === '') {
|
||||
return ['status' => self::UNKNOWN, 'stays' => []];
|
||||
}
|
||||
|
||||
$years = (int) ($case->parameter(self::key(), 'lookback_years') ?? 5);
|
||||
$minimum = (int) ($case->parameter(self::key(), 'min_stays') ?? 1);
|
||||
$stays = Booking::query()
|
||||
->whereKeyNot($case->booking->id)
|
||||
->where('status', BookingStatus::Completed)
|
||||
->whereDate('departure', '>=', $case->today->subYears($years))
|
||||
->whereHas('guest', fn ($query) => $query->whereRaw('lower(email) = ?', [$email]))
|
||||
->orderBy('arrival')
|
||||
->get()
|
||||
->map(fn (Booking $stay): string => (string) $stay->reference)
|
||||
->all();
|
||||
|
||||
return ['status' => count($stays) >= $minimum ? self::QUALIFIED : self::NOT_QUALIFIED, 'stays' => $stays];
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$status = $this->status($case);
|
||||
|
||||
return [new Activity('loyalty_status', 'Stammgaststatus feststellen', ActivityState::Done, match ($status['status']) {
|
||||
self::QUALIFIED => 'Stammgast: '.count($status['stays']).' frühere Aufenthalte ('.implode(', ', $status['stays']).')',
|
||||
self::NOT_QUALIFIED => 'kein Stammgast',
|
||||
default => 'Status nicht feststellbar (keine E-Mail-Adresse) – kein Rabatt',
|
||||
})];
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
return StepState::Done;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Process\CaseContext;
|
||||
|
||||
/**
|
||||
* Common ground of the modules: version 1, the state of the step is the state of its (first) activity.
|
||||
*/
|
||||
abstract class Module implements ProcessModule
|
||||
{
|
||||
public static function version(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
$activity = $this->activities($case)[0] ?? null;
|
||||
|
||||
return $activity === null ? null : StepState::fromActivity($activity->state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Enums\ProcessSetting;
|
||||
|
||||
/**
|
||||
* The contract of a module as data (docs/Prozessarchitektur/Architektur/02 §3.2). Fields marked "checked" are verified
|
||||
* by `process:check` or the contract tests; the others describe and are reviewed by hand – they promise nothing a test
|
||||
* cannot verify.
|
||||
*
|
||||
* @phpstan-type Performer 'system'|'landlord'|'guest'|'portal'|'service_provider'
|
||||
*/
|
||||
final readonly class ModuleDefinition
|
||||
{
|
||||
public const TOGGLE_MANDATORY = 'mandatory';
|
||||
|
||||
public const TOGGLE_OPTIONAL = 'optional';
|
||||
|
||||
public const TOGGLE_CONDITIONAL = 'conditional';
|
||||
|
||||
public const TOGGLE_EVENT_DRIVEN = 'event_driven';
|
||||
|
||||
public const AVAILABILITY_PRODUCTION = 'production';
|
||||
|
||||
/** Only in the process tester; never part of a real case's plan (decision E7, loyalty). */
|
||||
public const AVAILABILITY_TESTER_ONLY = 'tester_only';
|
||||
|
||||
/**
|
||||
* @param string $label name of the step for the landlord (describes)
|
||||
* @param string $purpose what the step does, in plain words (describes)
|
||||
* @param string $phase P01–P05 (checked)
|
||||
* @param list<Dependency> $requires dependencies for readiness (checked: every module exists, no cycle)
|
||||
* @param list<string> $effects kinds of effects the step may cause: case_write, guest_mail, landlord_mail, document, calendar_hold, channel_task, network (checked by the contract test)
|
||||
* @param list<string> $waits whom or what the step can wait for: guest, portal, landlord, time (describes)
|
||||
* @param list<string> $triggers events after which the step is evaluated again (describes; listed in process:check)
|
||||
* @param list<ProcessSetting|string> $parameters settings or module parameters that shape the step (checked: known)
|
||||
* @param string $toggle mandatory / optional / conditional / event_driven (checked: mandatory cannot be switched off)
|
||||
* @param list<string> $performers who may carry the step out (checked against the models' responsibilities)
|
||||
* @param list<string> $modes automatic / approval / manual (checked in the configurator)
|
||||
* @param list<string> $events history types that belong to the step (shown behind the step)
|
||||
* @param list<string> $points extension points the module may be inserted at (checked; empty = fixed place in a model)
|
||||
* @param bool $readsContractData evaluates frozen contract data – needs an ongoing-case test (checked)
|
||||
*/
|
||||
public function __construct(
|
||||
public string $label,
|
||||
public string $purpose,
|
||||
public string $phase,
|
||||
public array $requires = [],
|
||||
public array $effects = [],
|
||||
public array $waits = [],
|
||||
public array $triggers = [],
|
||||
public array $parameters = [],
|
||||
public string $toggle = self::TOGGLE_MANDATORY,
|
||||
public array $performers = ['system'],
|
||||
public array $modes = [],
|
||||
public array $events = [],
|
||||
public array $points = [],
|
||||
public bool $readsContractData = false,
|
||||
public string $availability = self::AVAILABILITY_PRODUCTION,
|
||||
) {}
|
||||
|
||||
public function isOptional(): bool
|
||||
{
|
||||
return $this->toggle === self::TOGGLE_OPTIONAL;
|
||||
}
|
||||
|
||||
public function isTesterOnly(): bool
|
||||
{
|
||||
return $this->availability === self::AVAILABILITY_TESTER_ONLY;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Money;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* A6: payment of an internal occasion with a price (e.g. linen, visitor's tax) – recorded, never reminded.
|
||||
*/
|
||||
final class InternalPayment extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'payments.internal';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Zahlung (ohne Erinnerungen)',
|
||||
purpose: 'Hält fest, was bei einer Eigenbelegung oder privaten Überlassung bezahlt wurde – ohne Erinnerungen.',
|
||||
phase: 'P03',
|
||||
effects: ['case_write'],
|
||||
toggle: ModuleDefinition::TOGGLE_CONDITIONAL,
|
||||
performers: ['landlord'],
|
||||
events: ['payment'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->booking->total !== null && $case->booking->total > 0;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$paid = $booking->paidAmount();
|
||||
|
||||
return [new Activity('payment', 'Zahlung (ohne Erinnerungen)', $case->later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Money;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* P03: the guest's payments – deposit and balance when we collect (A1–A3), the portal's collection when it collects
|
||||
* (A4/A5: only "laut Portal", never money on our account). Reminders are sent by SendBookingReminders.
|
||||
*/
|
||||
final class PaymentMonitoring extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'payments.monitor';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Zahlungen des Gastes',
|
||||
purpose: 'Überwacht Anzahlung und Restzahlung und erinnert rechtzeitig – oder zeigt, was das Portal laut eigener Angabe eingezogen hat.',
|
||||
phase: 'P03',
|
||||
effects: ['case_write', 'guest_mail'],
|
||||
waits: ['guest', 'portal', 'time'],
|
||||
triggers: ['payment.recorded', 'portal.amounts', 'schedule:reminders'],
|
||||
parameters: [ProcessSetting::Payments, ProcessSetting::GuestMessages],
|
||||
performers: ['landlord', 'portal'],
|
||||
events: ['payment', 'amount'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return ! $case->booking->isInternal();
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$binding = $case->binding;
|
||||
|
||||
if ($case->profile->payments() === Responsibility::Portal) {
|
||||
$portal = $booking->processChannel()?->name ?? 'das Portal';
|
||||
$viaPortal = $booking->paidViaPortal();
|
||||
|
||||
return [new Activity('payment', 'Zahlung des Gastes an '.$portal, ActivityState::External, match (true) {
|
||||
$booking->total === null => 'zieht das Portal ein',
|
||||
$viaPortal > 0 => 'laut Portal bezahlt: '.Money::format($viaPortal).' von '.Money::format($booking->total).' (Angabe des Portals, kein Geld bei uns)',
|
||||
default => 'zieht das Portal ein; noch keine Zahlungsangabe',
|
||||
})];
|
||||
}
|
||||
|
||||
if ($booking->total === null) {
|
||||
return [new Activity('payment', 'Zahlungen überwachen', $case->later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist')];
|
||||
}
|
||||
|
||||
$paid = $booking->paidAmount();
|
||||
|
||||
return [
|
||||
new Activity('deposit', 'Anzahlung erhalten', $case->later(match (true) {
|
||||
$binding && $paid >= (int) $booking->deposit => ActivityState::Done,
|
||||
$binding => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), Money::format((int) $booking->deposit).($booking->deposit_due_on ? ', fällig '.$booking->deposit_due_on->format('d.m.Y') : '')),
|
||||
new Activity('balance', 'Restzahlung erhalten', $case->later(match (true) {
|
||||
$binding && $paid >= $booking->total => ActivityState::Done,
|
||||
$binding && $paid >= (int) $booking->deposit => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), Money::format(max(0, $booking->total - (int) $booking->deposit)).($booking->balance_due_on ? ', fällig '.$booking->balance_due_on->format('d.m.Y') : '')),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Money;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Pricing\CaseMoney;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* P03 for portal collection (A4/A5): the portal's payout on our account. Only a payout the landlord recorded as
|
||||
* received counts (PaymentKind::PortalPayout); an announced payout or a portal report is no proof (decision O5).
|
||||
*/
|
||||
final class PortalPayout extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'portal.payout';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Auszahlung des Portals',
|
||||
purpose: 'Prüft, ob die Auszahlung des Portals tatsächlich auf unserem Konto eingegangen ist und zu den Angaben passt.',
|
||||
phase: 'P03',
|
||||
effects: ['case_write'],
|
||||
waits: ['portal', 'landlord', 'time'],
|
||||
triggers: ['portal.amounts', 'payment.recorded'],
|
||||
performers: ['landlord'],
|
||||
events: ['payment', 'amount'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return ! $case->booking->isInternal() && $case->profile->payments() === Responsibility::Portal;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$portal = $booking->processChannel()?->name ?? 'das Portal';
|
||||
$payout = CaseMoney::of($booking)->payout();
|
||||
|
||||
return [new Activity('payout', 'Auszahlung von '.$portal.' auf unser Konto', $case->later(match (true) {
|
||||
! $case->binding => ActivityState::Later,
|
||||
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) === 0 && $payout['difference'] === 0 => ActivityState::Done,
|
||||
default => ActivityState::Waiting,
|
||||
}), trim(($payout['values'] !== [] ? 'angekündigt '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).' · ' : '').'eingegangen '.Money::format($payout['received']).($payout['difference'] > 0 ? ' · Angaben weichen um '.Money::format($payout['difference']).' ab' : '')))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Offer;
|
||||
|
||||
use App\Actions\AutoOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\StepResult;
|
||||
|
||||
/**
|
||||
* The automatic answer of a request (binding offer or information "unter Vorbehalt"): due while the request waits for
|
||||
* its first answer and the case is handled automatically; carried out by {@see AutoOffer}, which checks every release
|
||||
* rule (dates, contract texts, calendar clearance, document composition) itself.
|
||||
*/
|
||||
trait AnswersRequest
|
||||
{
|
||||
public function due(CaseContext $case): bool
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return $booking->processingMode() === ProcessingMode::Automatic
|
||||
&& $booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0
|
||||
&& $booking->intake !== IntakeKind::Booking;
|
||||
}
|
||||
|
||||
public function blockers(CaseContext $case): array
|
||||
{
|
||||
return app(AutoOffer::class)->blockers($case->booking);
|
||||
}
|
||||
|
||||
public function run(CaseContext $case): StepResult
|
||||
{
|
||||
$reasons = app(AutoOffer::class)->handle($case->booking);
|
||||
|
||||
return $reasons === [] ? StepResult::ran() : StepResult::blocked($reasons);
|
||||
}
|
||||
|
||||
public function isOutward(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Offer;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
|
||||
/**
|
||||
* P02: our own binding offer with the contract draft (SendOffer, versioned). The price is fixed here – extension point
|
||||
* BeforePriceFixing lies before it. Never without every required detail (hard dependency on guest.details) and never
|
||||
* for dates that are taken.
|
||||
*/
|
||||
final class BindingOffer extends Module implements RunsAutomatically
|
||||
{
|
||||
use AnswersRequest;
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'offer.binding';
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
// 2: dates taken meanwhile are a problem of the step, an expired hold is not shown as reserved (F-001, F-002).
|
||||
return 2;
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Verbindliches Angebot',
|
||||
purpose: 'Erstellt das verbindliche Angebot mit Vertragsentwurf und sendet es dem Gast; der Zeitraum ist für die Haltefrist reserviert.',
|
||||
phase: 'P02',
|
||||
requires: [Dependency::hard('guest.details'), Dependency::hard('availability.check'), Dependency::soft('guest.data_request')],
|
||||
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document', 'calendar_hold', 'network'],
|
||||
waits: ['guest', 'landlord'],
|
||||
triggers: ['automation', 'request.created', 'schedule:bookings:auto-offers'],
|
||||
parameters: [ProcessSetting::Processing, ProcessSetting::HoldHours, ProcessSetting::ContractTemplate],
|
||||
performers: ['system', 'landlord'],
|
||||
modes: ['automatic', 'manual'],
|
||||
events: ['offer', 'hold', 'mail', 'status'],
|
||||
);
|
||||
}
|
||||
|
||||
/** The binding way: the request reserves (pre-reservation) or an offer was made anyway. */
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->inquiry && ! ($case->profile->preReservation() === false && $case->booking->offer_version === 0);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$offerDone = $booking->offer_version > 0 || $case->binding;
|
||||
// G2a (v0.11): without every required detail there is no offer – the step waits for the guest's answer
|
||||
// (mail, link or the landlord's entry) instead of being offered as the next step.
|
||||
$offerMissing = $offerDone ? [] : CaseRequirements::missing($booking, CaseRequirements::OFFER);
|
||||
$open = ! $offerDone && $offerMissing === [] && $booking->status === BookingStatus::Reserved && filled($booking->guest?->email);
|
||||
$taken = $open && ! app(AvailabilityChecker::class)->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking);
|
||||
|
||||
return [new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $case->later(match (true) {
|
||||
$offerDone => ActivityState::Done,
|
||||
$offerMissing !== [] => ActivityState::Later,
|
||||
$taken => ActivityState::Problem,
|
||||
$open => ActivityState::Open,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->offer_version > 0 => 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y'),
|
||||
$offerMissing !== [] => 'erst wenn alle Angaben da sind',
|
||||
$taken => 'Der Zeitraum ist inzwischen belegt.',
|
||||
$booking->isHoldActive() => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr',
|
||||
$booking->hold_expires_at !== null => 'Reservierung abgelaufen am '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr – Zeitraum nicht reserviert',
|
||||
default => null,
|
||||
}, $offerDone || $offerMissing !== [] || $taken ? null : 'sendOffer')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Offer;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
|
||||
/**
|
||||
* P02 (package 7): a request without a hold is answered with an information "unter Vorbehalt"; the guest asks for
|
||||
* the booking (wish) and we check again and confirm bindingly.
|
||||
*/
|
||||
final class Information extends Module implements RunsAutomatically
|
||||
{
|
||||
use AnswersRequest;
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'offer.information';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Unverbindliche Auskunft und Buchungswunsch',
|
||||
purpose: 'Beantwortet die Anfrage mit einer unverbindlichen Auskunft ohne Reservierung; fragt der Gast die Buchung an, wird erneut geprüft und verbindlich bestätigt.',
|
||||
phase: 'P02',
|
||||
requires: [Dependency::hard('intake.record'), Dependency::soft('guest.data_request')],
|
||||
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document'],
|
||||
waits: ['guest', 'landlord'],
|
||||
triggers: ['automation', 'request.created', 'schedule:bookings:auto-offers'],
|
||||
parameters: [ProcessSetting::Processing, ProcessSetting::GuestLinkValidDays],
|
||||
performers: ['system', 'landlord', 'guest'],
|
||||
modes: ['automatic', 'manual'],
|
||||
events: ['information', 'mail', 'hold', 'wish', 'status'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->inquiry && ! $case->profile->preReservation() && $case->booking->offer_version === 0;
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$binding = $case->binding;
|
||||
$informed = $booking->information_version > 0 || $binding;
|
||||
|
||||
return [
|
||||
new Activity('information', $booking->processingMode() === ProcessingMode::Automatic ? 'Unverbindliche Auskunft senden (automatisch)' : 'Unverbindliche Auskunft prüfen und senden', $case->later(match (true) {
|
||||
$booking->information_version > 0 => ActivityState::Done,
|
||||
$binding => ActivityState::NotApplicable,
|
||||
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
|
||||
default => ActivityState::Later,
|
||||
}), $booking->information_version > 0 ? 'Version '.$booking->information_version.' vom '.$booking->information_sent_at?->format('d.m.Y').' · ohne Reservierung' : 'der Zeitraum wird nicht reserviert', $informed ? null : 'sendInformation'),
|
||||
new Activity('wish', 'Gast fragt die Buchung an', $case->later(match (true) {
|
||||
$booking->wish_at !== null => ActivityState::Done,
|
||||
$binding => ActivityState::NotApplicable,
|
||||
$booking->information_version > 0 && $booking->information_valid_until?->isFuture() => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->wish_at !== null => 'angefragt am '.$booking->wish_at->format('d.m.Y, H:i').' Uhr',
|
||||
$booking->information_version > 0 => 'möglich bis '.$booking->information_valid_until?->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
}),
|
||||
new Activity('wish_check', 'Erneut prüfen und verbindlich bestätigen', $case->later(match (true) {
|
||||
$binding => ActivityState::Done,
|
||||
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->accepted_at !== null && ($booking->acceptance['via'] ?? null) === 'booking_wish' => 'bestätigt am '.$booking->confirmed_at?->format('d.m.Y').' ('.($booking->acceptance['confirmed_by'] ?? '').')',
|
||||
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => 'siehe Aufgabe „Buchungswunsch bestätigen?“',
|
||||
$binding => 'direkt verbindlich bestätigt (ohne Buchungswunsch)',
|
||||
default => $booking->processingMode() === ProcessingMode::Automatic ? 'automatisch, wenn alles passt' : 'durch Sie',
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Offer;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P02: the guest accepts (AcceptOffer, acceptance record) or declines (RejectOffer); the booking becomes binding
|
||||
* (ConfirmBooking). Cannot be switched off – our own way never binds without the guest's acceptance.
|
||||
*/
|
||||
final class OfferAcceptance extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'offer.acceptance';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Annahme durch den Gast',
|
||||
purpose: 'Der Gast nimmt das Angebot an oder lehnt es ab; mit der Annahme wird die Buchung verbindlich.',
|
||||
phase: 'P02',
|
||||
requires: [Dependency::hard('offer.binding')],
|
||||
effects: ['case_write', 'guest_mail', 'landlord_mail', 'document'],
|
||||
waits: ['guest', 'time'],
|
||||
triggers: ['offer.accepted', 'offer.declined'],
|
||||
performers: ['guest'],
|
||||
events: ['offer', 'status'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return app(BindingOffer::class)->applies($case);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return [new Activity('acceptance', 'Gast nimmt das Angebot an', $case->later(match (true) {
|
||||
$case->binding => ActivityState::Done,
|
||||
$booking->status === BookingStatus::OfferSent => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), match (true) {
|
||||
$booking->accepted_at !== null => 'angenommen am '.$booking->accepted_at->format('d.m.Y'),
|
||||
$case->binding => 'direkt bestätigt',
|
||||
$booking->status === BookingStatus::OfferSent => 'Angebot gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
})];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
|
||||
/**
|
||||
* A business capability of the process (docs/Prozessarchitektur/Architektur/02 §3): it offers one step of a case's
|
||||
* course and derives where that step stands from the case's data. Reading methods never write; a module that can carry
|
||||
* its step out by itself also implements {@see RunsAutomatically}.
|
||||
*/
|
||||
interface ProcessModule
|
||||
{
|
||||
/** Stable key, e.g. 'offer.binding'. */
|
||||
public static function key(): string;
|
||||
|
||||
/** Version of the module's business behaviour (raised for every change of behaviour, not for wording). */
|
||||
public static function version(): int;
|
||||
|
||||
/** What the configurator, the impact analysis and the contract tests read (pure data, no I/O). */
|
||||
public static function definition(): ModuleDefinition;
|
||||
|
||||
/** Whether the step belongs to this case at all. */
|
||||
public function applies(CaseContext $case): bool;
|
||||
|
||||
/**
|
||||
* Where the step stands, as the landlord sees it – usually one activity, some steps show none (they only watch) or
|
||||
* several (one per portal task).
|
||||
*
|
||||
* @return list<Activity>
|
||||
*/
|
||||
public function activities(CaseContext $case): array;
|
||||
|
||||
/** The state the runner uses for dependencies (null: the step has no state of its own and never blocks). */
|
||||
public function state(CaseContext $case): ?StepState;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\StepResult;
|
||||
|
||||
/**
|
||||
* A module whose step the system may carry out by itself (docs/Prozessarchitektur/Architektur/02 §7): the runner asks
|
||||
* whether it is due, checks its hard dependencies, then runs it through the existing actions. `run` must be idempotent:
|
||||
* a second run of a step that is already carried out has no effect.
|
||||
*/
|
||||
interface RunsAutomatically
|
||||
{
|
||||
/** Whether the system may carry the step out now by itself (its mode is automatic and the step is still to do). */
|
||||
public function due(CaseContext $case): bool;
|
||||
|
||||
/**
|
||||
* What keeps the step from being carried out now (plain words; empty = it may run).
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function blockers(CaseContext $case): array;
|
||||
|
||||
/** Carries the step out by calling the existing action(s). */
|
||||
public function run(CaseContext $case): StepResult;
|
||||
|
||||
/** Whether the step speaks to the guest or a third party (suspended while a portal report is open, decision O4). */
|
||||
public function isOutward(): bool;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Actions\SendBookingDocuments;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ProcessingMode;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseAutomation;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
use App\Process\StepResult;
|
||||
|
||||
/**
|
||||
* P03: the binding contract documentation for the guest (booking confirmation with contract, or the documents of a
|
||||
* portal booking). Who is responsible for it decides the case type (decision O1): ours in A1–A4, the portal's in A5 –
|
||||
* then the step is shown as external.
|
||||
*/
|
||||
final class BookingDocuments extends Module implements RunsAutomatically
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'documents.send';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Buchungsunterlagen (Vertragsdokumentation)',
|
||||
purpose: 'Sendet dem Gast die verbindliche Buchungsbestätigung mit Vertrag bzw. die Unterlagen der Portalbuchung.',
|
||||
phase: 'P03',
|
||||
requires: [Dependency::hard('guest.details')],
|
||||
effects: ['case_write', 'guest_mail', 'document'],
|
||||
waits: ['landlord', 'portal'],
|
||||
triggers: ['automation', 'booking.taken_over'],
|
||||
parameters: [ProcessSetting::Documents, ProcessSetting::Processing, ProcessSetting::ContractTemplate],
|
||||
performers: ['system', 'landlord', 'portal'],
|
||||
modes: ['automatic', 'manual'],
|
||||
events: ['document', 'mail'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return ! $case->booking->isInternal();
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
if ($case->profile->documents() === Responsibility::Portal) {
|
||||
return [new Activity('documents', 'Buchungsunterlagen an den Gast', ActivityState::External)];
|
||||
}
|
||||
|
||||
$binding = $case->binding;
|
||||
$state = match (true) {
|
||||
$booking->confirmation_sent_at !== null => ActivityState::Done,
|
||||
! $binding => ActivityState::Later,
|
||||
$booking->confirmation_failed_at !== null => ActivityState::Problem,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : [];
|
||||
// What the landlord still has to confirm (unreleased texts, terms not shown to be agreed on the portal).
|
||||
$toConfirm = $binding && $state === ActivityState::Open && $missing === [] ? app(SendBookingDocuments::class)->compose($booking)->toConfirm() : [];
|
||||
|
||||
return [new Activity('documents', match (true) {
|
||||
$state !== ActivityState::Open => $case->inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden',
|
||||
$case->inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden',
|
||||
default => 'Buchungsunterlagen prüfen und senden',
|
||||
}, $case->later($missing !== [] ? ActivityState::Waiting : $state),
|
||||
match (true) {
|
||||
$booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'),
|
||||
$state === ActivityState::Problem => 'Versand fehlgeschlagen',
|
||||
$missing !== [] => 'wartet: '.implode(' ', $missing),
|
||||
$toConfirm !== [] => 'vor dem Versand zu prüfen: '.implode(' ', $toConfirm),
|
||||
default => null,
|
||||
}, match (true) {
|
||||
$state === ActivityState::Problem => 'resendConfirmation',
|
||||
$binding && $missing === [] && $booking->confirmation_sent_at === null => 'sendDocuments',
|
||||
default => null,
|
||||
})];
|
||||
}
|
||||
|
||||
/** The guest's e-mail and the price are what the documents need – not every detail of a request. */
|
||||
public function due(CaseContext $case): bool
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return $booking->processingMode() === ProcessingMode::Automatic
|
||||
&& $case->binding && $booking->confirmation_sent_at === null
|
||||
&& $case->profile->documents() === Responsibility::Landlord && $case->profile->origin !== 'migration';
|
||||
}
|
||||
|
||||
public function blockers(CaseContext $case): array
|
||||
{
|
||||
return app(CaseAutomation::class)->documentBlockers($case->booking);
|
||||
}
|
||||
|
||||
public function run(CaseContext $case): StepResult
|
||||
{
|
||||
$reasons = app(SendBookingDocuments::class)->automatically($case->booking);
|
||||
|
||||
return $reasons === [] ? StepResult::ran() : StepResult::blocked($reasons);
|
||||
}
|
||||
|
||||
public function isOutward(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Models\BookingTask;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Event-driven work on the case (docs/Prozessarchitektur/Architektur/02 §4.1): every open task – a portal's
|
||||
* cancellation or change report, a booking wish to decide, conflicting details, payment and service tasks – and the done
|
||||
* tasks of the stay as its record. Tasks have no fixed place in the course; the model shows them where it lists events.
|
||||
*/
|
||||
final class CaseTasks extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'case.tasks';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Aufgaben und Meldungen',
|
||||
purpose: 'Zeigt offene Aufgaben des Vorgangs – Meldungen der Portale, Entscheidungen, Zahlungs- und Leistungsaufgaben.',
|
||||
phase: 'P03',
|
||||
effects: ['case_write'],
|
||||
waits: ['landlord'],
|
||||
triggers: ['task.created', 'portal.report'],
|
||||
toggle: ModuleDefinition::TOGGLE_EVENT_DRIVEN,
|
||||
performers: ['landlord'],
|
||||
events: ['task'],
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
return BookingTask::query()->where('booking_id', $case->booking->id)
|
||||
->where(fn ($query) => $query->where('status', BookingTaskStatus::Open)
|
||||
->orWhere(fn ($done) => $done->where('status', BookingTaskStatus::Done)->whereIn('kind', [BookingTaskKind::Service, BookingTaskKind::Issue, BookingTaskKind::FollowUp, BookingTaskKind::PayoutCheck, BookingTaskKind::OpenClaim])))
|
||||
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get()
|
||||
->map(fn (BookingTask $task): Activity => self::task($task))
|
||||
->all();
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* An open task of the case and the action that settles it.
|
||||
*/
|
||||
public static function task(BookingTask $task): Activity
|
||||
{
|
||||
$action = match ($task->kind) {
|
||||
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
|
||||
BookingTaskKind::PortalChangeReported => 'change',
|
||||
BookingTaskKind::BookingWish => 'decideWish',
|
||||
BookingTaskKind::ArrivalDetails => 'arrivalDetails',
|
||||
BookingTaskKind::CancellationRequest => 'end',
|
||||
BookingTaskKind::FactConflict => 'provideContact',
|
||||
default => $task->kind->isPayment() ? null : 'completeTask',
|
||||
};
|
||||
$today = CarbonImmutable::today();
|
||||
$state = match (true) {
|
||||
$task->status === BookingTaskStatus::Done => ActivityState::Done,
|
||||
$task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting,
|
||||
$task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later,
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem,
|
||||
// v0.11 (B3): the binding confirmation waits for the missing details as well.
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && CaseRequirements::missing($task->booking, CaseRequirements::WISH_CONFIRMATION) !== [] => ActivityState::Waiting,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$detail = $task->status === BookingTaskStatus::Done
|
||||
? 'erledigt am '.$task->completed_at?->format('d.m.Y').($task->completed_by ? ' von '.$task->completed_by : '').($task->note ? ' · '.$task->note : '')
|
||||
: trim(($state === ActivityState::Problem ? 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. · ' : '').($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->responsible ? ' · zuständig: '.$task->responsible : '').($task->note ? ' · '.$task->note : ''), ' ·');
|
||||
|
||||
return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ChangeStatus;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
use App\Process\Modules\StepState;
|
||||
|
||||
/**
|
||||
* Event-driven: a change of a binding booking proposed to the guest (ChangeBooking) – shown while it waits for the guest.
|
||||
*/
|
||||
final class ChangeProposal extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'change.proposal';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Änderungsvorschlag',
|
||||
purpose: 'Zeigt einen Änderungsvorschlag, der beim Gast liegt.',
|
||||
phase: 'P03',
|
||||
effects: ['case_write', 'guest_mail'],
|
||||
waits: ['guest', 'time'],
|
||||
triggers: ['change.proposed'],
|
||||
toggle: ModuleDefinition::TOGGLE_EVENT_DRIVEN,
|
||||
performers: ['landlord', 'guest'],
|
||||
events: ['change'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$activities = [];
|
||||
foreach ($case->booking->changes()->where('status', ChangeStatus::Proposed)->get() as $change) {
|
||||
$activities[] = new Activity('change_proposed', 'Änderungsvorschlag liegt beim Gast', ActivityState::Waiting, $change->summary().($change->expires_at ? ' · bis '.$change->expires_at->format('d.m.Y') : ''));
|
||||
}
|
||||
|
||||
return $activities;
|
||||
}
|
||||
|
||||
public function state(CaseContext $case): ?StepState
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseClosure;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P05 (package 9): the commercial closing – payments, refunds and payouts cleared (CaseClosure::commercialPoints). With
|
||||
* portal collection only after financial clearance; a portal report of a payout is no proof (decision O5).
|
||||
*/
|
||||
final class CommercialSettlement extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'case.settlement';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Kaufmännisch abschließen',
|
||||
purpose: 'Schließt den Vorgang kaufmännisch ab, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind.',
|
||||
phase: 'P05',
|
||||
requires: [Dependency::soft('case.closure')],
|
||||
effects: ['case_write'],
|
||||
waits: ['landlord', 'portal'],
|
||||
triggers: ['payment.recorded', 'stay.closed'],
|
||||
performers: ['landlord', 'system'],
|
||||
events: ['settled'],
|
||||
readsContractData: true,
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$settlementApplies = $booking->status === BookingStatus::Completed || $booking->status === BookingStatus::Cancelled;
|
||||
|
||||
return $settlementApplies || ($booking->isBinding() && ! $booking->isInternal()) || ($booking->isInternal() && (int) $booking->total > 0);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$settlementApplies = $booking->status === BookingStatus::Completed || $booking->status === BookingStatus::Cancelled;
|
||||
$points = $settlementApplies && $booking->settled_at === null ? CaseClosure::commercialPoints($booking) : [];
|
||||
|
||||
return [new Activity('settlement', 'Kaufmännisch abschließen', match (true) {
|
||||
$booking->settled_at !== null => ActivityState::Done,
|
||||
! $settlementApplies => ActivityState::Later,
|
||||
default => ActivityState::Waiting,
|
||||
}, match (true) {
|
||||
$booking->settled_at !== null => 'abgeschlossen am '.$booking->settled_at->format('d.m.Y').($booking->settled_by && $booking->settled_by !== CaseClosure::AUTOMATIC ? ' von '.$booking->settled_by : '').($booking->settled_note ? ' · '.$booking->settled_note : ''),
|
||||
! $settlementApplies => 'nach dem Aufenthalt, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind',
|
||||
default => 'offen: '.implode(' ', $points),
|
||||
}, $settlementApplies && $booking->settled_at === null && $points !== [] ? 'settle' : null)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Models\BookingTask;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseClosure;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P05 (package 9): closing the stay once nothing is open for it (CaseClosure, overnight or by hand).
|
||||
*/
|
||||
final class StayClosure extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'case.closure';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Aufenthalt abschließen',
|
||||
purpose: 'Schließt den Aufenthalt ab, sobald nach der Abreise nichts mehr für ihn offen ist.',
|
||||
phase: 'P05',
|
||||
effects: ['case_write'],
|
||||
waits: ['time', 'landlord'],
|
||||
triggers: ['schedule:daily'],
|
||||
performers: ['system', 'landlord'],
|
||||
events: ['task', 'status', 'settled'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return ! $case->closed && ($case->booking->isBinding() || $case->booking->status === BookingStatus::Completed);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$today = $case->today;
|
||||
$completed = $booking->status === BookingStatus::Completed;
|
||||
$blockers = $booking->isBinding() && ! $completed ? CaseClosure::stayBlockers($booking) : collect();
|
||||
|
||||
return [new Activity('closure', $booking->isInternal() && $booking->internal_kind === InternalKind::Block ? 'Sperrzeit abschließen' : 'Aufenthalt abschließen', match (true) {
|
||||
$completed => ActivityState::Done,
|
||||
! $booking->isBinding() || $booking->departure > $today => ActivityState::Later,
|
||||
default => ActivityState::Waiting,
|
||||
}, match (true) {
|
||||
$completed => 'abgeschlossen am '.($booking->completed_at ?? $booking->updated_at)?->format('d.m.Y'),
|
||||
$blockers->isNotEmpty() => 'wartet auf: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', '),
|
||||
$booking->isBinding() && $booking->departure <= $today => 'geschieht automatisch über Nacht – oder jetzt von Hand',
|
||||
default => 'nach der Abreise, sobald nichts mehr für den Aufenthalt offen ist',
|
||||
}, $booking->isBinding() && ! $completed && $booking->departure <= $today ? 'closeStay' : null)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Settlement;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* A6: an optional stay confirmation for the guests of an own use or private stay (no rental contract).
|
||||
*/
|
||||
final class StayConfirmation extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'documents.stay_confirmation';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Aufenthaltsbestätigung',
|
||||
purpose: 'Bestätigt den Gästen einer Eigenbelegung oder privaten Überlassung den Aufenthalt – nur bei Bedarf.',
|
||||
phase: 'P03',
|
||||
effects: ['guest_mail', 'document'],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
performers: ['landlord'],
|
||||
events: ['document', 'mail'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->booking->internal_kind !== InternalKind::Block && filled($case->booking->guest?->email);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
|
||||
return [new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $case->later($booking->confirmation_sent_at !== null ? ActivityState::Done : ActivityState::Later),
|
||||
$booking->confirmation_sent_at ? 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : 'nur bei Bedarf', $booking->confirmation_sent_at === null && ! $case->closed ? 'sendDocuments' : null)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Stay;
|
||||
|
||||
use App\Actions\PrepareStays;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Models\BookingTask;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P04: contact and arrival time for the stay (PrepareStays reports missing ones in time as a task).
|
||||
*/
|
||||
final class ArrivalDetails extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'arrival.details';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Anreisedaten',
|
||||
purpose: 'Sammelt Telefon und Anreisezeit für die Übergabe und meldet rechtzeitig, was fehlt.',
|
||||
phase: 'P04',
|
||||
effects: ['case_write'],
|
||||
waits: ['guest', 'landlord', 'time'],
|
||||
triggers: ['schedule:prepare-stays'],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
performers: ['landlord', 'guest', 'service_provider'],
|
||||
events: ['task', 'services'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->binding && ! BookingTask::query()->where('booking_id', $case->booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->exists();
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$missing = PrepareStays::missingArrivalDetails($booking);
|
||||
$left = $case->binding && $booking->departure <= $case->today;
|
||||
|
||||
return [new Activity('arrival_details', 'Anreisedaten', $case->later(match (true) {
|
||||
$missing === [] => ActivityState::Done,
|
||||
$left => ActivityState::NotApplicable,
|
||||
default => ActivityState::Later,
|
||||
}), $missing === [] ? implode(' · ', array_filter([$booking->guest?->phone ?: $booking->guest?->email, $booking->arrival_time ? 'Anreise '.$booking->arrival_time : null])) : 'es fehlt: '.implode(', ', $missing).' – wird rechtzeitig als Aufgabe gemeldet')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Stay;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P04: the arrival information for the guest – sent by us (SendBookingReminders) or announced by the portal. Who sends
|
||||
* it is variable within the model (supplementary, not contract documentation; decision O1).
|
||||
*/
|
||||
final class ArrivalInformation extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'arrival.info';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Anreise-Informationen',
|
||||
purpose: 'Wegbeschreibung, Schlüssel und Kontakt vor Ort rechtzeitig vor der Anreise.',
|
||||
phase: 'P04',
|
||||
effects: ['guest_mail'],
|
||||
waits: ['time', 'portal'],
|
||||
triggers: ['schedule:reminders'],
|
||||
parameters: [ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoDaysBefore],
|
||||
performers: ['system', 'portal', 'service_provider'],
|
||||
events: ['document', 'mail'],
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
$profile = $case->profile;
|
||||
|
||||
return [$profile->guestMessages() === Responsibility::Portal
|
||||
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen')
|
||||
: new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $case->later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Stay;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Dependency;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P05: asking the guest for a review after the stay (RequestReviews). Optional; today it follows who writes to the
|
||||
* guest (GuestMessages = us).
|
||||
*/
|
||||
final class ReviewRequest extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'review.request';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Bitte um eine Bewertung',
|
||||
purpose: 'Bittet den Gast nach dem Aufenthalt um eine Bewertung.',
|
||||
phase: 'P05',
|
||||
requires: [Dependency::hard('stay')],
|
||||
effects: ['guest_mail'],
|
||||
waits: ['time'],
|
||||
triggers: ['schedule:reviews'],
|
||||
toggle: ModuleDefinition::TOGGLE_OPTIONAL,
|
||||
performers: ['system'],
|
||||
events: ['mail'],
|
||||
);
|
||||
}
|
||||
|
||||
public function applies(CaseContext $case): bool
|
||||
{
|
||||
return $case->profile->guestMessages() === Responsibility::Landlord && ! $case->booking->isInternal();
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
return [new Activity('review', 'Bitte um eine Bewertung (automatisch)', $case->later($case->booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules\Stay;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Process\Activity;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\Modules\Module;
|
||||
use App\Process\Modules\ModuleDefinition;
|
||||
|
||||
/**
|
||||
* P04: the stay itself (or the time of an internal occupation).
|
||||
*/
|
||||
final class Stay extends Module
|
||||
{
|
||||
public static function key(): string
|
||||
{
|
||||
return 'stay';
|
||||
}
|
||||
|
||||
public static function definition(): ModuleDefinition
|
||||
{
|
||||
return new ModuleDefinition(
|
||||
label: 'Aufenthalt',
|
||||
purpose: 'Der Aufenthalt vom Anreise- bis zum Abreisetag.',
|
||||
phase: 'P04',
|
||||
waits: ['time'],
|
||||
triggers: ['schedule:daily'],
|
||||
performers: ['guest', 'landlord'],
|
||||
events: ['task', 'services', 'status'],
|
||||
);
|
||||
}
|
||||
|
||||
public function activities(CaseContext $case): array
|
||||
{
|
||||
$booking = $case->booking;
|
||||
if ($booking->isInternal()) {
|
||||
$kind = $booking->internal_kind;
|
||||
|
||||
return [new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $case->closed ? ActivityState::NotApplicable : ($booking->departure <= $case->today ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'))];
|
||||
}
|
||||
|
||||
$arrived = $case->binding && $booking->arrival <= $case->today;
|
||||
$left = $case->binding && $booking->departure <= $case->today;
|
||||
|
||||
return [new Activity('stay', 'Aufenthalt', $case->later(match (true) {
|
||||
$left => ActivityState::Done,
|
||||
$arrived => ActivityState::Waiting,
|
||||
default => ActivityState::Later,
|
||||
}), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'))];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Modules;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
|
||||
/**
|
||||
* The state of a step as the runner reads it for dependencies (docs/Prozessarchitektur/Architektur/02 §7.2). Derived
|
||||
* from the case's data on every evaluation, never stored.
|
||||
*/
|
||||
enum StepState: string
|
||||
{
|
||||
/** Carried out (by us or, where the model says so, by the portal). */
|
||||
case Done = 'done';
|
||||
|
||||
/** To do now. */
|
||||
case Open = 'open';
|
||||
|
||||
/** Waits for the guest, the portal, the landlord or a deadline. */
|
||||
case Waiting = 'waiting';
|
||||
|
||||
/** Something went wrong or stands in the way (e.g. the dates are taken). */
|
||||
case Problem = 'problem';
|
||||
|
||||
/** Not yet: a previous step of the case is not there. */
|
||||
case Later = 'later';
|
||||
|
||||
/** Does not apply (any more) to this case. */
|
||||
case NotApplicable = 'not_applicable';
|
||||
|
||||
public static function fromActivity(ActivityState $state): self
|
||||
{
|
||||
return match ($state) {
|
||||
ActivityState::Done, ActivityState::External => self::Done,
|
||||
ActivityState::Open => self::Open,
|
||||
ActivityState::Waiting => self::Waiting,
|
||||
ActivityState::Problem => self::Problem,
|
||||
ActivityState::Later => self::Later,
|
||||
ActivityState::NotApplicable => self::NotApplicable,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a hard dependency on a step in this state is fulfilled. */
|
||||
public function fulfils(): bool
|
||||
{
|
||||
return $this === self::Done;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
|
||||
/**
|
||||
* Decision O4: while a portal's report of a cancellation or change is open on a case, automatic messages to the guest
|
||||
* that the report could make wrong or misleading (booking documents, payment reminders, arrival information, review
|
||||
* request) wait until the landlord has clarified the report. The report itself never changes the booking.
|
||||
*
|
||||
* Only reports that the intake reliably assigned to this case count: PortalIntake opens these tasks only for a case
|
||||
* found by its booking reference or its exact nights (E-019); unassigned portal mails never become a task on a case.
|
||||
* Internal checks, deadlines, conflict detection and tasks go on as before.
|
||||
*/
|
||||
final class OutwardSuspension
|
||||
{
|
||||
public const KINDS = [BookingTaskKind::PortalCancellationReported, BookingTaskKind::PortalChangeReported];
|
||||
|
||||
/**
|
||||
* The reason automatic messages to the guest wait, or null when they may go.
|
||||
*/
|
||||
public static function reason(Booking $booking): ?string
|
||||
{
|
||||
$task = BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', self::KINDS)->where('status', BookingTaskStatus::Open)->first();
|
||||
|
||||
return $task === null ? null : 'Automatische Nachrichten an den Gast warten, bis die Meldung „'.$task->label().'“ geklärt ist.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\CaseType;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Process\Models\ProcessModel;
|
||||
use App\Process\Modules\ProcessModule;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* The registered modules and models (config/process.php) and the checks that keep the catalogue consistent
|
||||
* (`php artisan process:check`, ProcessCatalogueTest).
|
||||
*/
|
||||
final class ProcessCatalogue
|
||||
{
|
||||
/** @var array<string, class-string<ProcessModule>>|null */
|
||||
private ?array $modules = null;
|
||||
|
||||
/**
|
||||
* @return array<string, class-string<ProcessModule>> key => class
|
||||
*/
|
||||
public function modules(): array
|
||||
{
|
||||
if ($this->modules === null) {
|
||||
$this->modules = [];
|
||||
foreach ((array) config('process.modules', []) as $class) {
|
||||
$this->modules[$class::key()] = $class;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->modules;
|
||||
}
|
||||
|
||||
public function hasModule(string $key): bool
|
||||
{
|
||||
return array_key_exists($key, $this->modules());
|
||||
}
|
||||
|
||||
public function module(string $key): ProcessModule
|
||||
{
|
||||
$class = $this->modules()[$key] ?? throw new InvalidArgumentException("Unknown process module [{$key}].");
|
||||
|
||||
return app($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the registered class can serve a plan that froze the module in the given version.
|
||||
*/
|
||||
public function serves(string $key, int $version): bool
|
||||
{
|
||||
$class = $this->modules()[$key] ?? null;
|
||||
|
||||
return $class !== null && ($class::version() === $version || in_array($version, (array) config("process.compatible.{$key}", []), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, class-string<ProcessModel>>>
|
||||
*/
|
||||
public function modelVersions(): array
|
||||
{
|
||||
return (array) config('process.models', []);
|
||||
}
|
||||
|
||||
public function hasModel(string $key, ?int $version = null): bool
|
||||
{
|
||||
$versions = $this->modelVersions()[$key] ?? [];
|
||||
|
||||
return $version === null ? $versions !== [] : array_key_exists($version, $versions);
|
||||
}
|
||||
|
||||
/**
|
||||
* A model in a version (null: the latest).
|
||||
*/
|
||||
public function model(string $key, ?int $version = null): ProcessModel
|
||||
{
|
||||
$versions = $this->modelVersions()[$key] ?? throw new InvalidArgumentException("Unknown process model [{$key}].");
|
||||
$version ??= max(array_keys($versions));
|
||||
$class = $versions[$version] ?? throw new InvalidArgumentException("Process model [{$key}] has no version {$version}.");
|
||||
|
||||
return app($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* The latest version of every model.
|
||||
*
|
||||
* @return array<string, ProcessModel>
|
||||
*/
|
||||
public function models(): array
|
||||
{
|
||||
$models = [];
|
||||
foreach (array_keys($this->modelVersions()) as $key) {
|
||||
$models[$key] = $this->model($key);
|
||||
}
|
||||
|
||||
return $models;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a case follows when nobody chose one: derived from its frozen profile exactly as the v0.11 course
|
||||
* branched (legacy mapping, docs/Prozessarchitektur/Architektur/06 §4).
|
||||
*/
|
||||
public function derivedModel(ProcessProfile $profile): string
|
||||
{
|
||||
return match ($profile->intake) {
|
||||
IntakeKind::Internal => 'a6.internal',
|
||||
IntakeKind::Inquiry => ($profile->caseType === CaseType::A2 ? 'a2' : 'a1').($profile->preReservation() ? '.offer' : '.information'),
|
||||
IntakeKind::Booking => match ($profile->caseType) {
|
||||
CaseType::A5 => 'a5.portal_booking',
|
||||
CaseType::A4 => 'a4.portal_booking',
|
||||
default => 'a3.portal_booking',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The models admissible for a case type and intake kind.
|
||||
*
|
||||
* @return array<string, ProcessModel>
|
||||
*/
|
||||
public function admissible(IntakeKind $intake, ?CaseType $caseType = null): array
|
||||
{
|
||||
return array_filter($this->models(), fn (ProcessModel $model): bool => in_array($intake, $model::intakes(), true)
|
||||
&& ($caseType === null || in_array($caseType, $model::caseTypes(), true)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything that is inconsistent in the catalogue (empty = consistent).
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function problems(): array
|
||||
{
|
||||
$problems = [];
|
||||
foreach ($this->modules() as $key => $class) {
|
||||
$definition = $class::definition();
|
||||
foreach ($definition->requires as $dependency) {
|
||||
if (! $this->hasModule($dependency->module)) {
|
||||
$problems[] = "Modul {$key}: Abhängigkeit {$dependency->module} ist nicht registriert.";
|
||||
}
|
||||
}
|
||||
if (! in_array($definition->phase, ['P01', 'P02', 'P03', 'P04', 'P05'], true)) {
|
||||
$problems[] = "Modul {$key}: unbekannte Phase {$definition->phase}.";
|
||||
}
|
||||
if (is_subclass_of($class, RunsAutomatically::class) && $definition->modes === []) {
|
||||
$problems[] = "Modul {$key}: läuft automatisch, nennt aber keine Ausführungsart.";
|
||||
}
|
||||
}
|
||||
foreach ($this->cycles() as $cycle) {
|
||||
$problems[] = 'Zyklische harte Abhängigkeit: '.implode(' → ', $cycle);
|
||||
}
|
||||
|
||||
foreach ($this->modelVersions() as $key => $versions) {
|
||||
foreach ($versions as $version => $class) {
|
||||
if ($class::key() !== $key || $class::version() !== $version) {
|
||||
$problems[] = "Modell {$key}@{$version}: Klasse {$class} meldet ".$class::key().'@'.$class::version().'.';
|
||||
}
|
||||
$model = app($class);
|
||||
foreach ($model->variants() as $variant) {
|
||||
foreach ($model->modules($variant->key) as $module) {
|
||||
if (! $this->hasModule($module)) {
|
||||
$problems[] = "Modell {$key}@{$version}, Variante {$variant->key}: Modul {$module} ist nicht registriert.";
|
||||
}
|
||||
}
|
||||
foreach ($variant->inserts() as $point => $modules) {
|
||||
if (! in_array($point, array_map(fn ($p) => $p->value, $model->points()), true)) {
|
||||
$problems[] = "Modell {$key}@{$version}, Variante {$variant->key}: Erweiterungspunkt {$point} gibt es im Modell nicht.";
|
||||
}
|
||||
foreach ($modules as $module) {
|
||||
$points = $this->hasModule($module) ? $this->modules()[$module]::definition()->points : [];
|
||||
if ($points !== [] && ! in_array($point, $points, true)) {
|
||||
$problems[] = "Modell {$key}@{$version}: Modul {$module} darf nicht an {$point} stehen.";
|
||||
}
|
||||
if ($this->hasModule($module) && $this->modules()[$module]::definition()->isTesterOnly() && ! $variant->isTesterOnly()) {
|
||||
$problems[] = "Modell {$key}@{$version}: Modul {$module} ist nur für den Prozess-Tester, Variante {$variant->key} aber nicht.";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<list<string>>
|
||||
*/
|
||||
private function cycles(): array
|
||||
{
|
||||
$edges = [];
|
||||
foreach ($this->modules() as $key => $class) {
|
||||
$edges[$key] = array_values(array_map(fn ($dependency): string => $dependency->module, array_filter($class::definition()->requires, fn ($dependency): bool => $dependency->hard)));
|
||||
}
|
||||
|
||||
$cycles = [];
|
||||
$visit = function (string $node, array $path) use (&$visit, &$cycles, $edges): void {
|
||||
if (in_array($node, $path, true)) {
|
||||
$cycles[] = [...array_slice($path, (int) array_search($node, $path, true)), $node];
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($edges[$node] ?? [] as $next) {
|
||||
$visit($next, [...$path, $node]);
|
||||
}
|
||||
};
|
||||
foreach (array_keys($edges) as $node) {
|
||||
$visit($node, []);
|
||||
}
|
||||
|
||||
return array_values(array_unique($cycles, SORT_REGULAR));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Process\Models\ProcessModel;
|
||||
use DomainException;
|
||||
|
||||
/**
|
||||
* The frozen process plan of a case (docs/Prozessarchitektur/Architektur/02 §1, §5.3): model and version, variant,
|
||||
* the versions of its modules and the step settings of the channel (on/off, mode, performer, parameters) as they were
|
||||
* when the case came in. Stored in `bookings.profile.plan`; cases without one (all before V2) get the derived plan of
|
||||
* their profile on reading, which reproduces the v0.11 course (legacy mapping). The plan also keeps the labels of its
|
||||
* steps, so a finished case stays readable even if a model definition is ever retired (requirement T3).
|
||||
*/
|
||||
final class ProcessPlan
|
||||
{
|
||||
public const DERIVED = 'derived';
|
||||
|
||||
public const CONFIGURED = 'configured';
|
||||
|
||||
public const TESTER = 'tester';
|
||||
|
||||
/**
|
||||
* @param array<string, int> $modules module key => frozen version
|
||||
* @param array<string, array{on?: bool, mode?: ?string, performer?: ?string, params?: array<string, mixed>}> $steps
|
||||
* @param array<string, string> $labels module key => label at the time of freezing
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $model,
|
||||
public readonly int $modelVersion,
|
||||
public readonly string $variant,
|
||||
public readonly array $modules,
|
||||
public readonly array $steps = [],
|
||||
public readonly string $source = self::DERIVED,
|
||||
public readonly array $labels = [],
|
||||
public readonly ?string $notice = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The plan of a case: frozen with it, or derived from its profile (never stored by reading).
|
||||
*/
|
||||
public static function of(Booking $booking): self
|
||||
{
|
||||
$data = (array) (($booking->profile ?? [])['plan'] ?? []);
|
||||
|
||||
return $data !== [] ? self::fromArray($data) : self::derive($booking->process());
|
||||
}
|
||||
|
||||
/**
|
||||
* The plan a case gets from its profile when no model was chosen for its channel.
|
||||
*/
|
||||
public static function derive(ProcessProfile $profile): self
|
||||
{
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
|
||||
return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', [], self::DERIVED);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plan frozen for a new case: the model and step settings chosen for its channel and intake kind (Kanal ›
|
||||
* Ablauf), when admissible for the case's type; otherwise the derived one with a notice. Tester-only variants or
|
||||
* modules are refused outside the process tester (decision E7).
|
||||
*
|
||||
* @param array<string, mixed> $configuration model, variant, steps of channels.process_overrides[intake]
|
||||
*/
|
||||
public static function freeze(ProcessProfile $profile, array $configuration, bool $sandbox = false): self
|
||||
{
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
// Inside a process tester run (its own process, SandboxBootstrapper) tester-only variants are allowed.
|
||||
$sandbox = $sandbox || filled(config('sandbox.run'));
|
||||
$chosen = (string) ($configuration['model'] ?? '');
|
||||
if ($chosen === '') {
|
||||
return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', (array) ($configuration['steps'] ?? []), self::DERIVED);
|
||||
}
|
||||
|
||||
if (! $catalogue->hasModel($chosen)) {
|
||||
return self::derive($profile)->withNotice("Gewähltes Modell {$chosen} ist nicht registriert – abgeleitetes Modell verwendet.");
|
||||
}
|
||||
|
||||
$model = $catalogue->model($chosen);
|
||||
if (! in_array($profile->caseType, $model::caseTypes(), true) || ! in_array($profile->intake, $model::intakes(), true)) {
|
||||
return self::derive($profile)->withNotice("Gewähltes Modell {$chosen} passt nicht zu Vorgangsart {$profile->caseType->value} – abgeleitetes Modell verwendet.");
|
||||
}
|
||||
|
||||
$variant = (string) ($configuration['variant'] ?? 'standard');
|
||||
$chosenVariant = $model->variant($variant) ?? throw new DomainException("Modell {$chosen} hat keine Variante {$variant}.");
|
||||
if (! $sandbox && $chosenVariant->isTesterOnly()) {
|
||||
throw new DomainException("Die Variante „{$chosenVariant->label}“ ist nur im Prozess-Tester verwendbar.");
|
||||
}
|
||||
foreach ($model->modules($variant) as $module) {
|
||||
if (! $sandbox && $catalogue->module($module)::definition()->isTesterOnly()) {
|
||||
throw new DomainException("Das Modul {$module} ist nur im Prozess-Tester verwendbar.");
|
||||
}
|
||||
}
|
||||
|
||||
return self::build($model, $variant, (array) ($configuration['steps'] ?? []), $sandbox ? self::TESTER : self::CONFIGURED);
|
||||
}
|
||||
|
||||
/**
|
||||
* The configuration of a channel for one intake kind as the plan reads it (model, variant, steps).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function configurationOf(?Channel $channel, IntakeKind $intake): array
|
||||
{
|
||||
if ($channel === null || $intake === IntakeKind::Internal) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_intersect_key((array) (($channel->process_overrides ?? [])[$intake->value] ?? []), array_flip(['model', 'variant', 'steps']));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $steps
|
||||
*/
|
||||
private static function build(ProcessModel $model, string $variant, array $steps, string $source): self
|
||||
{
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
$modules = [];
|
||||
$labels = [];
|
||||
foreach ($model->modules($variant) as $key) {
|
||||
$class = $catalogue->modules()[$key];
|
||||
$modules[$key] = $class::version();
|
||||
$labels[$key] = $class::definition()->label;
|
||||
}
|
||||
|
||||
return new self($model::key(), $model::version(), $variant, $modules, array_intersect_key($steps, $modules), $source, $labels);
|
||||
}
|
||||
|
||||
private function withNotice(string $notice): self
|
||||
{
|
||||
return new self($this->model, $this->modelVersion, $this->variant, $this->modules, $this->steps, $this->source, $this->labels, $notice);
|
||||
}
|
||||
|
||||
public function modelDefinition(): ProcessModel
|
||||
{
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
|
||||
// A retired version (T3): its cases stay readable through the latest definition of the same model.
|
||||
return $catalogue->hasModel($this->model, $this->modelVersion) ? $catalogue->model($this->model, $this->modelVersion) : $catalogue->model($this->model);
|
||||
}
|
||||
|
||||
public function isHistoric(): bool
|
||||
{
|
||||
return ! app(ProcessCatalogue::class)->hasModel($this->model, $this->modelVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* The module keys of the case's course, in order.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function moduleKeys(): array
|
||||
{
|
||||
return array_keys($this->modules);
|
||||
}
|
||||
|
||||
/** Whether a step is switched on (only optional steps can be switched off; mandatory ones are always on). */
|
||||
public function enabled(string $module): bool
|
||||
{
|
||||
if (($this->steps[$module]['on'] ?? true) !== false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
|
||||
return $catalogue->hasModule($module) && ! $catalogue->module($module)::definition()->isOptional();
|
||||
}
|
||||
|
||||
public function mode(string $module): ?string
|
||||
{
|
||||
return $this->steps[$module]['mode'] ?? null;
|
||||
}
|
||||
|
||||
public function performer(string $module): ?string
|
||||
{
|
||||
return $this->steps[$module]['performer'] ?? null;
|
||||
}
|
||||
|
||||
public function parameter(string $module, string $name): mixed
|
||||
{
|
||||
return $this->steps[$module]['params'][$name] ?? null;
|
||||
}
|
||||
|
||||
public function reference(): string
|
||||
{
|
||||
return $this->model.'@'.$this->modelVersion.($this->variant !== 'standard' ? ':'.$this->variant : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return array_filter([
|
||||
'model' => $this->model,
|
||||
'model_version' => $this->modelVersion,
|
||||
'variant' => $this->variant,
|
||||
'modules' => $this->modules,
|
||||
'steps' => $this->steps,
|
||||
'source' => $this->source,
|
||||
'labels' => $this->labels,
|
||||
'notice' => $this->notice,
|
||||
], fn (mixed $value): bool => $value !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
(string) $data['model'],
|
||||
(int) $data['model_version'],
|
||||
(string) ($data['variant'] ?? 'standard'),
|
||||
array_map('intval', (array) ($data['modules'] ?? [])),
|
||||
(array) ($data['steps'] ?? []),
|
||||
(string) ($data['source'] ?? self::DERIVED),
|
||||
(array) ($data['labels'] ?? []),
|
||||
isset($data['notice']) ? (string) $data['notice'] : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ final class ProcessProfile
|
||||
/** The own website's entry of the channel manager (v0.11). */
|
||||
public const WEBSITE = 'website';
|
||||
|
||||
/** Fixed by the process model chosen for the channel (Architektur V2). */
|
||||
public const MODEL = 'model';
|
||||
|
||||
/** Fixed by the case type (A6), not settable. */
|
||||
public const CASE_TYPE = 'case_type';
|
||||
|
||||
@@ -167,6 +170,7 @@ public static function sourceLabel(string $source): string
|
||||
self::CHANNEL => 'Abweichung des Portals',
|
||||
self::WEBSITE => 'Einstellung der eigenen Webseite',
|
||||
self::CASE_TYPE => 'fest für diese Vorgangsart',
|
||||
self::MODEL => 'festgelegt durch das gewählte Ablaufmodell',
|
||||
'migration' => 'aus dem bisherigen Stand übernommen',
|
||||
default => 'Grundeinstellung',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\ActivityState;
|
||||
use App\Models\Booking;
|
||||
use App\Process\Modules\ProcessModule;
|
||||
use App\Process\Modules\RunsAutomatically;
|
||||
use App\Process\Modules\StepState;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The one process core (docs/Prozessarchitektur/Architektur/02 §7): reads a case's course from its frozen plan and
|
||||
* carries it on as far as its data allows.
|
||||
*
|
||||
* - **No second truth:** every state is derived from the case's data on each evaluation; the runner stores nothing.
|
||||
* - **Readiness (requirement T1):** an automatic step is ready when it applies, is switched on, is due, its hard
|
||||
* dependencies are done and nothing blocks it. A soft dependency only orders steps due in the same round. A waiting
|
||||
* step therefore holds back exactly the steps that depend on it hard – a clarification hold runs on while the data
|
||||
* request waits for the guest.
|
||||
* - **Re-evaluation:** one step per round; after each step the case is read again and readiness is determined anew – a
|
||||
* list of runnable steps is never carried over a state change.
|
||||
* - **Triggers:** the existing places call {@see advance()} with what happened; only modules that declare the trigger
|
||||
* are considered, so every caller keeps the scope it had in v0.11.
|
||||
*/
|
||||
final class ProcessRunner
|
||||
{
|
||||
/** The trigger of the former CaseAutomation::advance (facts, portal amounts, the landlord's "continue automatically"). */
|
||||
public const AUTOMATION = 'automation';
|
||||
|
||||
/** @var array<int, true> cases being advanced in this process (a nested call returns at once) */
|
||||
private static array $running = [];
|
||||
|
||||
public function __construct(private ProcessCatalogue $catalogue) {}
|
||||
|
||||
/**
|
||||
* The activities of a case in the order of its plan, as the landlord sees them.
|
||||
*
|
||||
* @return list<Activity>
|
||||
*/
|
||||
public function activities(Booking $booking): array
|
||||
{
|
||||
$context = CaseContext::of($booking);
|
||||
$activities = [];
|
||||
|
||||
foreach ($context->plan->moduleKeys() as $key) {
|
||||
if (! $this->catalogue->hasModule($key)) {
|
||||
// A step whose module was retired (T3): the finished case stays readable with the frozen label.
|
||||
$activities[] = new Activity($key, ($context->plan->labels[$key] ?? $key).' (frühere Fassung)', ActivityState::NotApplicable);
|
||||
|
||||
continue;
|
||||
}
|
||||
$module = $this->catalogue->module($key);
|
||||
if (! $context->plan->enabled($key) || ! $module->applies($context)) {
|
||||
continue;
|
||||
}
|
||||
array_push($activities, ...$module->activities($context));
|
||||
}
|
||||
|
||||
return $activities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carries a case on by itself as far as its data allows (only steps whose mode is automatic).
|
||||
*
|
||||
* @param string $trigger what happened (a trigger the modules declare, e.g. 'request.created')
|
||||
*/
|
||||
public function advance(Booking $booking, string $trigger = self::AUTOMATION): AdvanceResult
|
||||
{
|
||||
$result = new AdvanceResult;
|
||||
if (isset(self::$running[$booking->id])) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$lock = Cache::lock('case-advance:'.$booking->id, 60);
|
||||
if (! $lock->get()) {
|
||||
// Another process is advancing this case right now and evaluates it again after each step.
|
||||
return $result;
|
||||
}
|
||||
|
||||
self::$running[$booking->id] = true;
|
||||
try {
|
||||
$this->rounds($booking, $trigger, $result);
|
||||
} finally {
|
||||
unset(self::$running[$booking->id]);
|
||||
$lock->release();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function rounds(Booking $booking, string $trigger, AdvanceResult $result): void
|
||||
{
|
||||
$attempted = [];
|
||||
$plan = ProcessPlan::of($booking);
|
||||
$limit = count($plan->modules) + 1;
|
||||
|
||||
for ($round = 0; $round < $limit; $round++) {
|
||||
$context = new CaseContext($booking->fresh() ?? $booking, $plan);
|
||||
$ready = $this->ready($context, $trigger, $attempted, $result);
|
||||
if ($ready === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$key = $ready::key();
|
||||
$attempted[$key] = true;
|
||||
/** @var ProcessModule&RunsAutomatically $ready */
|
||||
try {
|
||||
$step = CaseLog::context(fn (): StepResult => $ready->run($context), actor: CaseLog::SYSTEM.' (automatisch)');
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$step = StepResult::failed('Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.');
|
||||
}
|
||||
|
||||
if ($step->didRun()) {
|
||||
$result->ran[] = $key;
|
||||
} else {
|
||||
$result->held[$key] = $step->reasons;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The next step to carry out, determined anew from the case's current data; steps that are due but cannot run are
|
||||
* recorded with their reasons.
|
||||
*
|
||||
* @param array<string, true> $attempted
|
||||
*/
|
||||
private function ready(CaseContext $context, string $trigger, array $attempted, AdvanceResult $result): ?ProcessModule
|
||||
{
|
||||
$candidates = [];
|
||||
foreach ($context->plan->moduleKeys() as $key) {
|
||||
if (isset($attempted[$key]) || ! $this->catalogue->hasModule($key)) {
|
||||
continue;
|
||||
}
|
||||
$module = $this->catalogue->module($key);
|
||||
if (! $module instanceof RunsAutomatically || ! in_array($trigger, $module::definition()->triggers, true)) {
|
||||
continue;
|
||||
}
|
||||
if (! $context->plan->enabled($key) || ! $module->applies($context) || ! $module->due($context)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$unmet = $this->unmetHardDependencies($module, $context);
|
||||
if ($unmet !== []) {
|
||||
// Not ready: a hard requirement is missing. Its own blockers say what (e.g. the missing details).
|
||||
$result->held[$key] = $module->blockers($context) ?: array_map(fn (string $label): string => 'Wartet auf: '.$label.'.', $unmet);
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($module->isOutward() && ($reason = OutwardSuspension::reason($context->booking)) !== null) {
|
||||
$result->held[$key] = [$reason];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$candidates[$key] = $module;
|
||||
}
|
||||
|
||||
foreach ($candidates as $key => $module) {
|
||||
// A soft dependency that is ready in the same round goes first.
|
||||
$before = array_filter($module::definition()->requires, fn ($dependency): bool => ! $dependency->hard && isset($candidates[$dependency->module]));
|
||||
if ($before === []) {
|
||||
return $module;
|
||||
}
|
||||
}
|
||||
|
||||
return $candidates === [] ? null : reset($candidates);
|
||||
}
|
||||
|
||||
/**
|
||||
* Labels of the hard dependencies that are not done. A dependency on a step that is not part of the plan or does
|
||||
* not apply to the case is fulfilled (the condition does not concern this case).
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function unmetHardDependencies(ProcessModule $module, CaseContext $context): array
|
||||
{
|
||||
$unmet = [];
|
||||
foreach ($module::definition()->requires as $dependency) {
|
||||
if (! $dependency->hard || ! array_key_exists($dependency->module, $context->plan->modules) || ! $this->catalogue->hasModule($dependency->module)) {
|
||||
continue;
|
||||
}
|
||||
$required = $this->catalogue->module($dependency->module);
|
||||
if (! $context->plan->enabled($dependency->module) || ! $required->applies($context)) {
|
||||
continue;
|
||||
}
|
||||
$state = $required->state($context);
|
||||
if ($state !== null && ! $state->fulfils() && $state !== StepState::NotApplicable) {
|
||||
$unmet[] = $required::definition()->label;
|
||||
}
|
||||
}
|
||||
|
||||
return $unmet;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Models\Tenant;
|
||||
use App\Process\Models\ProcessModel;
|
||||
|
||||
/**
|
||||
* Resolves the effective process settings: built-in default → landlord default (tenant) → deviation of the property
|
||||
@@ -49,6 +50,17 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
|
||||
}
|
||||
}
|
||||
|
||||
// Architektur V2: the process model chosen for the channel and intake kind fixes some settings (e.g. the
|
||||
// pre-reservation of the offer model, the responsibilities of A3–A5); these win over every level.
|
||||
$model = $this->chosenModel($channel, $intake);
|
||||
foreach ($model === null ? [] : $model::fixes() as $key => $fixed) {
|
||||
$setting = ProcessSetting::tryFrom($key);
|
||||
if ($setting !== null) {
|
||||
$values[$key] = $setting->normalize($fixed) ?? $fixed;
|
||||
$sources[$key] = ProcessProfile::MODEL;
|
||||
}
|
||||
}
|
||||
|
||||
if ($intake === IntakeKind::Internal) {
|
||||
// Own use, private stays and blocks (A6): no rental documents, no payment reminders, no guest mails – fixed by
|
||||
// the case type, not by a setting.
|
||||
@@ -68,6 +80,21 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
|
||||
return new ProcessProfile($intake, ProcessProfile::caseTypeFor($intake, $channel?->isPortal() ?? false, $documents, $payments), $values, $sources);
|
||||
}
|
||||
|
||||
/**
|
||||
* The model chosen for the channel and intake kind (Kanal › Ablauf), when it is registered and fits the intake.
|
||||
*/
|
||||
private function chosenModel(?Channel $channel, IntakeKind $intake): ?ProcessModel
|
||||
{
|
||||
$key = (string) (ProcessPlan::configurationOf($channel, $intake)['model'] ?? '');
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
if ($key === '' || ! $catalogue->hasModel($key)) {
|
||||
return null;
|
||||
}
|
||||
$model = $catalogue->model($key);
|
||||
|
||||
return in_array($intake, $model::intakes(), true) ? $model : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings of a request from the own website: the website's entry of the channel manager is its channel level
|
||||
* (the case itself stays direct, without a channel).
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
/**
|
||||
* What happened when the runner carried out one step: it ran (the action did its work), it was held back (with the
|
||||
* reasons, shown to the landlord as before) or it failed technically.
|
||||
*/
|
||||
final readonly class StepResult
|
||||
{
|
||||
public const RAN = 'ran';
|
||||
|
||||
public const BLOCKED = 'blocked';
|
||||
|
||||
public const FAILED = 'failed';
|
||||
|
||||
/**
|
||||
* @param list<string> $reasons
|
||||
*/
|
||||
private function __construct(public string $outcome, public array $reasons = []) {}
|
||||
|
||||
public static function ran(): self
|
||||
{
|
||||
return new self(self::RAN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $reasons
|
||||
*/
|
||||
public static function blocked(array $reasons): self
|
||||
{
|
||||
return new self(self::BLOCKED, array_values($reasons));
|
||||
}
|
||||
|
||||
public static function failed(string $reason): self
|
||||
{
|
||||
return new self(self::FAILED, [$reason]);
|
||||
}
|
||||
|
||||
public function didRun(): bool
|
||||
{
|
||||
return $this->outcome === self::RAN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Tester;
|
||||
|
||||
/**
|
||||
* The record of a tester run: every simulated effect and every violation, appended line by line to a file in the
|
||||
* run's directory – it survives exceptions, and what an action swallowed is still there.
|
||||
*/
|
||||
final class EffectLedger
|
||||
{
|
||||
private static ?string $path = null;
|
||||
|
||||
public static function open(string $path): void
|
||||
{
|
||||
self::$path = $path;
|
||||
}
|
||||
|
||||
public static function isOpen(): bool
|
||||
{
|
||||
return self::$path !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function record(string $type, array $data = []): void
|
||||
{
|
||||
if (self::$path === null) {
|
||||
return;
|
||||
}
|
||||
file_put_contents(self::$path, json_encode(['type' => $type, ...$data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n", FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function entries(): array
|
||||
{
|
||||
if (self::$path === null || ! is_file(self::$path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_map(fn (string $line): array => (array) json_decode($line, true), array_filter(explode("\n", (string) file_get_contents(self::$path)))));
|
||||
}
|
||||
|
||||
public static function violations(): array
|
||||
{
|
||||
return array_values(array_filter(self::entries(), fn (array $entry): bool => ($entry['type'] ?? null) === 'violation'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Tester;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ProcessTestRun;
|
||||
use App\Models\User;
|
||||
use App\Process\ChannelProcessConfiguration;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* The process tester seen from the landlord's request (docs/Prozessarchitektur/Architektur/04 §3.2): checks that the
|
||||
* isolation can be established on this server, prepares a run (read-only snapshot, run directory), starts the run in a
|
||||
* process of its own – which knows neither the real database nor any real service – waits for its report, stores the
|
||||
* report and removes the run's directory. The landlord's request never switches into sandbox mode itself.
|
||||
*/
|
||||
final class ProcessSandbox
|
||||
{
|
||||
/** At most this many runs at the same time on the server (one per landlord). */
|
||||
public const SLOTS = 3;
|
||||
|
||||
public const TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* What keeps the tester from running safely here (empty = it may run). Checked in the request that would start it.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function requirements(): array
|
||||
{
|
||||
$missing = [];
|
||||
if (! extension_loaded('pdo_sqlite')) {
|
||||
$missing[] = 'Die PHP-Erweiterung pdo_sqlite fehlt (eigene Testdatenbank je Lauf).';
|
||||
}
|
||||
if (! is_file(storage_path('app/sandbox/template.sqlite'))) {
|
||||
$missing[] = 'Die Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).';
|
||||
}
|
||||
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
|
||||
if (! function_exists('proc_open') || in_array('proc_open', $disabled, true)) {
|
||||
$missing[] = 'Eigene Prozesse lassen sich nicht starten (proc_open gesperrt) – ohne eigenen Prozess ist keine sichere Trennung möglich.';
|
||||
}
|
||||
if (str_contains(str_replace(DIRECTORY_SEPARATOR, '/', self::php()), '/') && ! is_file(self::php())) {
|
||||
$missing[] = 'Das PHP-Programm für den Testlauf wurde nicht gefunden.';
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plays a scenario with the (possibly unsaved) draft of a channel's process and returns the stored report.
|
||||
*
|
||||
* @param array<string, mixed> $draft
|
||||
* @param array<string, mixed> $inputs
|
||||
*/
|
||||
public function run(Channel $channel, IntakeKind $intake, array $draft, string $scenario, array $inputs, int $steps, User $user): ProcessTestRun
|
||||
{
|
||||
if (($missing = self::requirements()) !== []) {
|
||||
throw new RuntimeException('Der Prozess-Tester ist auf diesem Server gesperrt: '.implode(' ', $missing));
|
||||
}
|
||||
if (ScenarioCatalogue::find($scenario) === null) {
|
||||
throw new RuntimeException('Unbekanntes Szenario.');
|
||||
}
|
||||
if (($problems = app(ChannelProcessConfiguration::class)->problems($channel, $intake, $draft, sandbox: true)) !== []) {
|
||||
throw new RuntimeException('Die Konfiguration ist nicht zulässig: '.implode(' ', $problems));
|
||||
}
|
||||
|
||||
self::prune();
|
||||
$locks = $this->slot($channel->tenant_id);
|
||||
$run = (string) Str::uuid();
|
||||
$directory = SandboxBootstrapper::directory($run);
|
||||
|
||||
try {
|
||||
File::ensureDirectoryExists($directory.'/files', 0700);
|
||||
$input = [
|
||||
'snapshot' => SandboxSnapshot::build($channel, $intake, $draft),
|
||||
'scenario' => $scenario,
|
||||
'inputs' => $inputs,
|
||||
'steps' => $steps,
|
||||
'start' => now()->startOfMinute()->toIso8601String(),
|
||||
];
|
||||
File::put($directory.'/input.json', (string) json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
$result = Process::path(base_path())
|
||||
->timeout(self::TIMEOUT_SECONDS)
|
||||
->env([SandboxBootstrapper::ENV => $run, ...self::childEnvironment(), ...(app()->environment('testing') ? (array) config('fewo.sandbox.test_environment', []) : [])])
|
||||
->run([self::php(), 'artisan', 'process:sandbox-run', $run, '--no-interaction']);
|
||||
|
||||
$report = is_file($directory.'/report.json') ? (array) json_decode((string) File::get($directory.'/report.json'), true) : [];
|
||||
if ($report === []) {
|
||||
$report = ['aborted' => 'Der Testlauf hat keinen Bericht geliefert'.($result->successful() ? '.' : ': '.mb_substr(trim($result->errorOutput() ?: $result->output()), 0, 300)), 'timeline' => [], 'violations' => []];
|
||||
}
|
||||
|
||||
return ProcessTestRun::query()->create([
|
||||
'tenant_id' => $channel->tenant_id,
|
||||
'channel_id' => $channel->id,
|
||||
'user_id' => $user->id,
|
||||
'intake' => $intake->value,
|
||||
'scenario' => $scenario,
|
||||
'configuration' => $draft,
|
||||
'inputs' => $inputs,
|
||||
'steps' => $steps,
|
||||
'report' => $report,
|
||||
'outcome' => filled($report['aborted'] ?? null) ? ProcessTestRun::ABORTED : ProcessTestRun::COMPLETED,
|
||||
'release' => self::release(),
|
||||
]);
|
||||
} finally {
|
||||
File::deleteDirectory($directory);
|
||||
foreach ($locks as $lock) {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes directories of runs that ended abnormally (older than an hour).
|
||||
*/
|
||||
public static function prune(): void
|
||||
{
|
||||
foreach (glob(storage_path('app/sandbox/runs/*'), GLOB_ONLYDIR) ?: [] as $directory) {
|
||||
if (filemtime($directory) < time() - 3600) {
|
||||
File::deleteDirectory($directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The release the report belongs to.
|
||||
*/
|
||||
public static function release(): ?string
|
||||
{
|
||||
// Releases on Strato live in releases/<timestamp>-<commit> (pipeline-manager, scripts/deploy.sh).
|
||||
$release = basename(base_path());
|
||||
|
||||
return preg_match('/^\d{14}-[0-9a-f]{7,40}$/', $release) === 1 ? $release : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The PHP command line program for the run (Strato: php-cli next to the web PHP).
|
||||
*/
|
||||
public static function php(): string
|
||||
{
|
||||
$configured = (string) config('fewo.sandbox.php', '');
|
||||
if ($configured !== '') {
|
||||
return $configured;
|
||||
}
|
||||
|
||||
return PHP_SAPI === 'cli' ? PHP_BINARY : (is_file('/opt/RZphp84/bin/php-cli') ? '/opt/RZphp84/bin/php-cli' : 'php');
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment of the run's process: what Laravel needs to boot – never database, mail or service credentials (the
|
||||
* run's configuration replaces them anyway, this keeps them out of its environment, too).
|
||||
*
|
||||
* @return array<string, string|false>
|
||||
*/
|
||||
private static function childEnvironment(): array
|
||||
{
|
||||
$blank = [];
|
||||
foreach (array_keys(getenv()) as $key) {
|
||||
if (preg_match('/^(DB_|MAIL_|REDIS_|AWS_|MAILBOX_|FEWO_MAILBOX|OPENAI|ANTHROPIC|OPENROUTER|N8N_|PIPELINE_)/', (string) $key) === 1) {
|
||||
$blank[$key] = false;
|
||||
}
|
||||
}
|
||||
|
||||
return $blank;
|
||||
}
|
||||
|
||||
/**
|
||||
* One run per landlord and at most SLOTS on the server, as file locks (they end with the process).
|
||||
*
|
||||
* @return list<resource> the held locks (landlord, slot)
|
||||
*/
|
||||
private function slot(int $tenant): array
|
||||
{
|
||||
$directory = storage_path('app/sandbox/slots');
|
||||
File::ensureDirectoryExists($directory, 0700);
|
||||
$tenantLock = fopen($directory.'/tenant-'.$tenant.'.lock', 'c');
|
||||
if ($tenantLock === false || ! flock($tenantLock, LOCK_EX | LOCK_NB)) {
|
||||
throw new RuntimeException('Für diesen Vermieter läuft bereits ein Test. Bitte einen Moment warten.');
|
||||
}
|
||||
for ($index = 1; $index <= self::SLOTS; $index++) {
|
||||
$slot = fopen($directory.'/slot-'.$index.'.lock', 'c');
|
||||
if ($slot !== false && flock($slot, LOCK_EX | LOCK_NB)) {
|
||||
return [$tenantLock, $slot];
|
||||
}
|
||||
if ($slot !== false) {
|
||||
fclose($slot);
|
||||
}
|
||||
}
|
||||
fclose($tenantLock);
|
||||
|
||||
throw new RuntimeException('Der Prozess-Tester ist gerade belegt. Bitte gleich noch einmal versuchen.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Tester;
|
||||
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\ProcessSetting;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Models\Tenant;
|
||||
use App\Process\CaseActivities;
|
||||
use App\Process\CaseContext;
|
||||
use App\Process\ProcessCatalogue;
|
||||
use App\Process\ProcessPlan;
|
||||
use App\Process\ProcessProfile;
|
||||
use App\Process\Tester\Scenarios\Scenario;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Mail\Events\MessageSent;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Symfony\Component\Mime\Email;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Plays a scenario inside the tester process (docs/Prozessarchitektur/Architektur/04 §2): seeds the run's own database
|
||||
* from the snapshot, then triggers the scenario's events through the real entry points and reads the case's course
|
||||
* after each one with the same method the case page uses. Contains no business rules of its own.
|
||||
*/
|
||||
final class ProcessSandboxDriver
|
||||
{
|
||||
public const MAX_EVENTS = 60;
|
||||
|
||||
public const MAX_SECONDS = 20;
|
||||
|
||||
private int $mailsSeen = 0;
|
||||
|
||||
private int $ledgerSeen = 0;
|
||||
|
||||
/** @var list<Email> every mail of the run (simulated: the only mailer is `array`) */
|
||||
private array $sent = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $input input.json of the run
|
||||
* @return array<string, mixed> the report
|
||||
*/
|
||||
public function run(array $input): array
|
||||
{
|
||||
$this->assertSandbox();
|
||||
$started = microtime(true);
|
||||
// Mails are collected when they are sent: the transport is rebuilt whenever the landlord context changes.
|
||||
Event::listen(MessageSent::class, function (MessageSent $event): void {
|
||||
$this->sent[] = $event->message;
|
||||
EffectLedger::record('mail', ['subject' => (string) $event->message->getSubject()]);
|
||||
});
|
||||
SandboxSnapshot::seed($input['snapshot']);
|
||||
Date::setTestNow(CarbonImmutable::parse((string) $input['start']));
|
||||
|
||||
$tenant = Tenant::query()->findOrFail($input['snapshot']['tenant_id']);
|
||||
$channel = Channel::withoutGlobalScopes()->findOrFail($input['snapshot']['channel_id']);
|
||||
$intake = IntakeKind::from((string) $input['snapshot']['intake']);
|
||||
$class = ScenarioCatalogue::find((string) $input['scenario']) ?? throw new \RuntimeException('Unbekanntes Szenario.');
|
||||
/** @var Scenario $scenario */
|
||||
$scenario = new $class;
|
||||
|
||||
return app(TenantContext::class)->run($tenant, function () use ($input, $channel, $intake, $scenario, $started): array {
|
||||
$property = Property::query()->findOrFail($channel->property_id);
|
||||
$context = new SandboxContext($channel, $intake, $property, (array) $input['inputs']);
|
||||
$events = array_slice($scenario->events($context->inputs), 0, min(self::MAX_EVENTS, max(1, (int) $input['steps'])));
|
||||
$timeline = [];
|
||||
$aborted = null;
|
||||
|
||||
if (filled(config('sandbox.probe'))) {
|
||||
// Negative tests only: a probe tries forbidden accesses before the scenario.
|
||||
rescue(fn () => app((string) config('sandbox.probe'))->handle($context), report: false);
|
||||
}
|
||||
|
||||
foreach ($events as $event) {
|
||||
$error = null;
|
||||
try {
|
||||
($event->run)($context);
|
||||
} catch (Throwable $exception) {
|
||||
$error = class_basename($exception).': '.$exception->getMessage();
|
||||
}
|
||||
$timeline[] = ['label' => $event->label, 'at' => now()->format('d.m.Y H:i'), 'error' => $error, ...$this->capture($context)];
|
||||
|
||||
if (EffectLedger::violations() !== []) {
|
||||
$aborted = 'Unzulässiger Zugriff – Lauf abgebrochen.';
|
||||
break;
|
||||
}
|
||||
if (microtime(true) - $started > self::MAX_SECONDS) {
|
||||
$aborted = 'Laufzeitgrenze erreicht – Lauf abgebrochen.';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$booking = $context->booking?->fresh();
|
||||
|
||||
return [
|
||||
'scenario' => ['key' => $scenario::key(), 'label' => $scenario::label(), 'inputs' => $context->inputs, 'available_events' => count($scenario->events($context->inputs))],
|
||||
'plan' => $booking === null ? null : $this->plan($booking),
|
||||
'timeline' => $timeline,
|
||||
'result' => $booking === null ? null : ['status' => $booking->status->getLabel(), 'situation' => CaseActivities::situation($booking), 'next' => CaseActivities::next($booking)?->label],
|
||||
'violations' => EffectLedger::violations(),
|
||||
'aborted' => $aborted ?? (EffectLedger::violations() !== [] ? 'Unzulässiger Zugriff – Lauf abgebrochen.' : null),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to run unless the process really is a sandbox (defence in depth behind SandboxBootstrapper).
|
||||
*/
|
||||
private function assertSandbox(): void
|
||||
{
|
||||
$connections = array_keys((array) config('database.connections'));
|
||||
$mailers = array_keys((array) config('mail.mailers'));
|
||||
if (config('database.default') !== 'sandbox' || $connections !== ['sandbox'] || $mailers !== ['array'] || config('cache.default') !== 'array' || blank(config('sandbox.run'))) {
|
||||
throw new \RuntimeException('Sicherheitsprüfung des Prozess-Testers fehlgeschlagen: der Prozess ist nicht isoliert ('.json_encode(['db' => config('database.default'), 'connections' => $connections, 'mailers' => $mailers, 'cache' => config('cache.default')]).').');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function plan(Booking $booking): array
|
||||
{
|
||||
$plan = ProcessPlan::of($booking);
|
||||
$profile = $booking->process();
|
||||
|
||||
return [
|
||||
'model' => $plan->model,
|
||||
'label' => $plan->modelDefinition()::label(),
|
||||
'version' => $plan->modelVersion,
|
||||
'variant' => $plan->variant,
|
||||
'modules' => $plan->modules,
|
||||
'case_type' => strtoupper($profile->caseType->value),
|
||||
'configuration' => collect(ProcessSetting::cases())->map(fn ($setting): array => ['question' => $setting->question(), 'value' => $setting->describe($profile->value($setting)), 'source' => ProcessProfile::sourceLabel($profile->source($setting))])->all(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The case after one event: its course, the skipped steps, the simulated mails and effects.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function capture(SandboxContext $context): array
|
||||
{
|
||||
$booking = $context->booking?->fresh();
|
||||
$ledger = EffectLedger::entries();
|
||||
$effects = array_slice($ledger, $this->ledgerSeen);
|
||||
$this->ledgerSeen = count($ledger);
|
||||
|
||||
if ($booking === null) {
|
||||
return ['activities' => [], 'skipped' => [], 'mails' => $this->mails(), 'effects' => $effects];
|
||||
}
|
||||
|
||||
$caseContext = CaseContext::of($booking);
|
||||
$catalogue = app(ProcessCatalogue::class);
|
||||
$skipped = [];
|
||||
foreach ($caseContext->plan->moduleKeys() as $key) {
|
||||
if (! $catalogue->hasModule($key)) {
|
||||
continue;
|
||||
}
|
||||
$module = $catalogue->module($key);
|
||||
$reason = match (true) {
|
||||
! $caseContext->plan->enabled($key) => 'übersprungen (Konfiguration)',
|
||||
! $module->applies($caseContext) => 'trifft hier nicht zu',
|
||||
default => null,
|
||||
};
|
||||
if ($reason !== null) {
|
||||
$skipped[] = ['label' => $module::definition()->label, 'reason' => $reason];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => $booking->status->getLabel(),
|
||||
'situation' => CaseActivities::situation($booking),
|
||||
'activities' => array_map(fn ($activity): array => ['label' => $activity->label, 'state' => $activity->state->getLabel(), 'state_key' => $activity->state->value, 'detail' => $activity->detail], CaseActivities::for($booking)),
|
||||
'skipped' => $skipped,
|
||||
'calendar' => ['occupying' => Booking::query()->occupying()->whereKey($booking->id)->exists(), 'hold_until' => $booking->isHoldActive() ? $booking->hold_expires_at->format('d.m.Y H:i') : null],
|
||||
'price' => ['total' => $booking->total, 'lines' => array_map(fn (array $line): array => ['label' => $line['label'] ?? '', 'amount' => $line['amount'] ?? 0], (array) ($booking->quote['lines'] ?? []))],
|
||||
'mails' => $this->mails(),
|
||||
'effects' => $effects,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mails sent since the last capture – simulated, never delivered. Links are shown as text only.
|
||||
*
|
||||
* @return list<array{subject: string, to: string, excerpt: string}>
|
||||
*/
|
||||
private function mails(): array
|
||||
{
|
||||
$new = array_slice($this->sent, $this->mailsSeen);
|
||||
$this->mailsSeen = count($this->sent);
|
||||
|
||||
return array_values(array_map(function (Email $email): array {
|
||||
$text = trim(preg_replace('/\s+/', ' ', strip_tags((string) ($email->getTextBody() ?? $email->getHtmlBody() ?? ''))) ?? '');
|
||||
|
||||
return [
|
||||
'subject' => (string) $email->getSubject(),
|
||||
'to' => implode(', ', array_map(fn ($address): string => $address->getAddress(), $email->getTo())),
|
||||
'excerpt' => mb_substr((string) preg_replace('~https?://\S+~', '[Link]', $text), 0, 400),
|
||||
];
|
||||
}, $new));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process\Tester;
|
||||
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Monolog\Handler\NullHandler;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Turns the process that runs a tester scenario into a sandbox before anything is resolved (requirement T2,
|
||||
* docs/Prozessarchitektur/Architektur/04 §3.3). Called right after the configuration is loaded and only when the
|
||||
* process was started for a run (environment FEWO_SANDBOX_RUN, set by ProcessSandbox for its child process).
|
||||
*
|
||||
* Default deny: the configuration is replaced, not amended – the only database is the run's own SQLite file, the only
|
||||
* mailer `array`, the only cache store `array`, the queue `sync`, every disk lies in the run's directory, logging goes
|
||||
* to the run's log, all secrets are blanked and the application key is a fresh one per run (links and encrypted values
|
||||
* of a run are worthless outside it). Whatever is not configured does not exist in this process.
|
||||
*/
|
||||
final class SandboxBootstrapper
|
||||
{
|
||||
public const ENV = 'FEWO_SANDBOX_RUN';
|
||||
|
||||
public static function active(): bool
|
||||
{
|
||||
return filled(getenv(self::ENV) ?: null);
|
||||
}
|
||||
|
||||
public static function directory(string $run): string
|
||||
{
|
||||
if (preg_match('/^[a-f0-9-]{36}$/', $run) !== 1) {
|
||||
throw new RuntimeException('Ungültige Laufkennung.');
|
||||
}
|
||||
|
||||
return storage_path('app/sandbox/runs/'.$run);
|
||||
}
|
||||
|
||||
public static function configure(Application $app): void
|
||||
{
|
||||
$run = (string) getenv(self::ENV);
|
||||
$directory = self::directory($run);
|
||||
if (! is_dir($directory) || ! is_file($directory.'/input.json')) {
|
||||
throw new RuntimeException('Prozess-Tester: Laufverzeichnis fehlt.');
|
||||
}
|
||||
|
||||
$config = $app['config'];
|
||||
|
||||
// The run's own database: a copy of the migrated, empty template made at deployment (process:sandbox-template).
|
||||
$template = storage_path('app/sandbox/template.sqlite');
|
||||
if (! is_file($directory.'/db.sqlite')) {
|
||||
if (! is_file($template) || ! copy($template, $directory.'/db.sqlite')) {
|
||||
throw new RuntimeException('Prozess-Tester: Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).');
|
||||
}
|
||||
}
|
||||
|
||||
$config->set('database.default', 'sandbox');
|
||||
$config->set('database.connections', ['sandbox' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => $directory.'/db.sqlite',
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => true,
|
||||
]]);
|
||||
$config->set('database.redis', []);
|
||||
|
||||
$config->set('mail.default', 'array');
|
||||
$config->set('mail.mailers', ['array' => ['transport' => 'array']]);
|
||||
$config->set('mail.from', ['address' => 'tester@sandbox.invalid', 'name' => 'Prozess-Tester']);
|
||||
$config->set('fewo.mail_redirect_to', null);
|
||||
|
||||
$config->set('cache.default', 'array');
|
||||
$config->set('cache.stores', ['array' => ['driver' => 'array', 'serialize' => false]]);
|
||||
$config->set('session.driver', 'array');
|
||||
$config->set('queue.default', 'sync');
|
||||
$config->set('queue.connections', ['sync' => ['driver' => 'sync']]);
|
||||
$config->set('queue.failed', ['driver' => 'null']);
|
||||
|
||||
$files = $directory.'/files';
|
||||
$config->set('filesystems.default', 'local');
|
||||
$config->set('filesystems.disks', [
|
||||
'local' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true],
|
||||
'private' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true],
|
||||
'public' => ['driver' => 'local', 'root' => $files.'/public', 'throw' => true],
|
||||
'media' => ['driver' => 'local', 'root' => $files.'/media', 'throw' => true],
|
||||
]);
|
||||
|
||||
$config->set('logging.default', 'sandbox');
|
||||
$config->set('logging.channels', [
|
||||
'sandbox' => ['driver' => 'single', 'path' => $directory.'/log.txt', 'level' => 'debug'],
|
||||
'null' => ['driver' => 'monolog', 'handler' => NullHandler::class],
|
||||
'emergency' => ['path' => $directory.'/log.txt'],
|
||||
]);
|
||||
|
||||
$config->set('app.key', 'base64:'.base64_encode(random_bytes(32)));
|
||||
$config->set('app.previous_keys', []);
|
||||
|
||||
// Secrets and outside services: blank. The scripted answers of the scenario replace them.
|
||||
foreach (['services', 'fewo.mailbox', 'fewo.automation', 'fewo.llm'] as $key) {
|
||||
if (is_array($config->get($key))) {
|
||||
$config->set($key, array_map(fn (mixed $value): mixed => is_array($value) ? [] : null, (array) $config->get($key)));
|
||||
}
|
||||
}
|
||||
|
||||
$config->set('sandbox', ['run' => $run, 'directory' => $directory, 'probe' => self::probe($app)]);
|
||||
// Registered after every framework provider, so its bindings replace the managers before anything resolves them.
|
||||
$config->set('app.providers', [...($config->get('app.providers') ?? ServiceProvider::defaultProviders()->toArray()), SandboxServiceProvider::class]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A probe that deliberately tries forbidden accesses – only for the negative tests of the test suite.
|
||||
*/
|
||||
private static function probe(Application $app): ?string
|
||||
{
|
||||
$probe = getenv('FEWO_SANDBOX_PROBE') ?: null;
|
||||
|
||||
return $probe !== null && $app->environment('testing') && class_exists($probe) ? $probe : null;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user