Files
fewo-stommer/app/Process/CaseActivities.php
LarsandClaude Opus 5.5 3bcfc09417
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
- Paket 8: Zahlungsarten (Gast an uns, laut Portal, Auszahlung, Erstattung),
  Portalbeträge als Angaben mit Quelle, Übersicht nach Zuständigkeit (R09).
- Paket 5: Ändern mit Folgenvorschau, vereinbart oder dem Gast vorgeschlagen
  (signierter Link), ein Stornoweg mit Grund und Erstattung, Portalstorno erst
  nach Bestätigung.
- Paket 6: eigene Nutzung, Besuch und Sperre als Vorgang mit Kurabgabe und
  Aufenthaltsbestätigung; Bestandsübernahme der Sperren mit identischem Export.
- Wirksame Einstellungen (Expertenansicht), Abnahmekatalog T01–T14, Ergebnis-,
  Abnahme- und Konfigurationsdokument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:16:47 +01:00

292 lines
18 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Process;
use App\Actions\EndInternalCase;
use App\Actions\SendBookingDocuments;
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\Support\Money;
use Carbon\CarbonImmutable;
/**
* The activities of a case derived from its process profile and its data (docs/Prozessarchitektur, P01–P05): which
* apply, which are done (by us or by the portal), what is waiting for somebody else and what the landlord has to do
* next. Nothing here is stored; the gates G1–G5 are these states, not an extra status machine.
*/
class CaseActivities
{
/** Activities that are listed on their own in the work list (they are not "the" next step of a case). */
private const LISTED_SEPARATELY = ['channel_block'];
/** Activities that are the next step whatever else is open. */
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation'];
/**
* @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();
$later = fn (ActivityState $state): ActivityState => $closed && ! 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);
$state = match (true) {
$hasEmail => ActivityState::Done,
$booking->contact_requested_at !== null => ActivityState::Waiting,
default => ActivityState::Open,
};
$activities[] = new Activity('contact', $booking->guest === null ? 'Name und Kontaktdaten des Gastes eintragen' : 'E-Mail-Adresse des Gastes eintragen', $later($state),
$hasEmail ? $booking->guestName() : ($booking->contact_requested_at ? 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlt noch'),
$hasEmail ? null : 'provideContact');
}
if ($inquiry) {
$offerDone = $booking->offer_version > 0 || $binding;
$activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) {
$offerDone => ActivityState::Done,
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
default => ActivityState::Later,
}), $booking->offer_version > 0 ? 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y') : ($booking->hold_expires_at ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : null), $offerDone ? 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) {
$activities[] = new Activity('payment', 'Zahlung des Gastes', ActivityState::External, 'läuft über das Portal');
} 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 (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() 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;
$activities[] = $profile->guestMessages() === Responsibility::Portal
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External)
: 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');
$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;
}
/**
* 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 (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() 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;
}
/**
* 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::RefundCheck => null,
default => $task->kind->isPayment() ? null : 'end',
};
return new Activity('task_'.$task->kind->value, $task->kind->getLabel(), ActivityState::Open, trim(($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->note ? ' · '.$task->note : ''), ' ·'), $action);
}
/**
* What the landlord should do next on this case, or null when nothing is up to him.
*/
public static function next(Booking $booking): ?Activity
{
$activities = self::for($booking);
// A report of the portal (cancellation, other dates) comes before everything else on the case.
usort($activities, fn (Activity $a, Activity $b): int => (int) in_array($b->key, self::URGENT, true) <=> (int) in_array($a->key, self::URGENT, true));
foreach ($activities as $activity) {
if ($activity->state->needsAction() && ! in_array($activity->key, self::LISTED_SEPARATELY, true)) {
return $activity;
}
}
return null;
}
/**
* The state of the case in one sentence of plain words.
*/
public static function situation(Booking $booking): string
{
$today = CarbonImmutable::today();
if ($booking->isInternal()) {
return implode(' · ', array_filter([
$booking->internal_kind?->getLabel() ?? 'Eigene Belegung',
$booking->occasion,
$booking->status === BookingStatus::Cancelled ? EndInternalCase::label($booking) : ($booking->departure <= $today ? 'beendet am '.$booking->departure->format('d.m.Y') : $booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')),
]));
}
if ($booking->portal_cancellation_requested_at !== null && $booking->isBinding()) {
return 'Gebucht über '.($booking->processChannel()?->name ?? 'ein Portal').' · Stornierung beim Portal veranlasst – bleibt gebucht, bis sie bestätigt ist';
}
$channel = $booking->processChannel()?->name;
$kind = $booking->intake === IntakeKind::Booking ? 'Gebucht über '.($channel ?? 'ein Portal') : ($channel ? 'Anfrage über '.$channel : ($booking->source === 'website' ? 'Anfrage über die Webseite' : 'Anfrage'));
$state = match ($booking->status) {
BookingStatus::Reserved => $booking->isHoldActive() ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr' : 'Zeitraum nicht reserviert',
BookingStatus::OfferSent => $booking->isHoldActive() ? 'Angebot liegt beim Gast bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr' : 'Angebot abgelaufen',
BookingStatus::Confirmed => 'fest gebucht',
BookingStatus::DepositPaid => 'fest gebucht, Anzahlung erhalten',
BookingStatus::Paid => 'fest gebucht, bezahlt',
BookingStatus::Completed => 'abgeschlossen',
BookingStatus::Declined => 'ohne Buchung beendet',
BookingStatus::Expired => 'Frist abgelaufen, ohne Buchung beendet',
BookingStatus::Cancelled => 'storniert',
};
$when = match (true) {
! $booking->isBinding() => null,
$booking->departure <= $today => 'abgereist am '.$booking->departure->format('d.m.Y'),
$booking->arrival <= $today => 'Gast ist vor Ort bis '.$booking->departure->format('d.m.Y'),
default => 'Anreise in '.(int) $today->diffInDays($booking->arrival).' Tagen',
};
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();
}
}