Files
fewo-stommer/app/Process/CaseActivities.php
T
LarsandClaude Opus 5.5 3a039e5c50
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m10s
v0.11: Angebot wartet sichtbar auf Pflichtangaben; Postfach prüfen; Eingangsmails am Vorgang
- Vorgang: „Angebot prüfen und senden“ wird erst angeboten, wenn alle
  Pflichtangaben da sind („erst wenn alle Angaben da sind“); ebenso wartet
  „Buchungswunsch bestätigen?“. Die harte Sperre in SendOffer, AutoOffer
  und DecideBookingWish bestand bereits; jetzt stimmt auch die Anzeige.
- System › Betrieb: „Postfach prüfen“ (Verbindung, Anzahl Nachrichten der
  letzten Tage, nichts wird gelesen oder markiert) und Stand des Abrufs.
- Posteingang zeigt letzten erfolgreichen Abruf und letzten Fehler.
- Vorgang: neuer Bereich „Eingegangene E-Mails“ mit Lesen und Erkanntem;
  „Mailverlauf“ heißt jetzt „Gesendete E-Mails“.

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

460 lines
31 KiB
PHP
Raw 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\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;
/**
* 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();
// 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);
}
/**
* 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 => match (true) {
$booking->isHoldActive() => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr',
$booking->wish_at !== null => 'Buchungswunsch liegt vor – noch nicht verbindlich, Zeitraum nicht reserviert',
$booking->information_version > 0 => 'unverbindliche Auskunft gesendet, Zeitraum nicht reserviert',
default => '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 => $booking->settled_at !== null ? 'Aufenthalt und Kaufmännisches abgeschlossen' : 'Aufenthalt abgeschlossen, kaufmännisch noch offen',
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();
}
}