Files
fewo-stommer/app/Actions/CancelBooking.php
T
LarsandClaude Opus 5.5 40d20cb7d1 Pakete 7 und 9: Auskunft und Buchungswunsch, Aufenthalt und Abschluss (Zwischenstand)
- Haltefrist 0: unverbindliche Auskunft mit signiertem Link "Buchung anfragen",
  erneute Prüfung unter Sperre, automatische oder manuelle Bestätigung, Absage
  bei vergebenem Zeitraum, Ablauf unbeantworteter Auskünfte
- Aufenthalt: Anreisedaten, Aufgaben je Wohnung, gebuchte Leistungen,
  Abweichungen und Folgeaufgaben als Aufgaben am Vorgang
- Abschluss getrennt: Aufenthalt abgeschlossen / kaufmännisch abgeschlossen,
  Nachläufer (Forderung, Auszahlung) bleiben sichtbar
- Zahlungsstatus nur aus Geld auf unserem Konto; Altbestand per Vorschau-Befehl
- Verlauf weist Testzustellungen als solche aus
- Abnahmetests T16-T25, T23 über isolierten SMTP-Empfänger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 08:29:19 +01:00

170 lines
8.7 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\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Mail\BookingCancelled;
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Process\CaseClosure;
use App\Process\CaseLog;
use App\Support\CancellationCost;
use App\Support\Money;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The one way to cancel a binding booking (package 5). Own bookings: the dates are free again; the guest and the
* landlord are informed by e-mail – the guest's e-mail can be switched off, e.g. when the guest cancelled by phone –, the
* cancellation is recorded with who initiated it, why and who entered it, a task for the cancellation costs and – when
* the guest paid us more than the costs – a refund task are created. Open cancellation requests of the guest are done.
*
* Bookings binding on a portal (A3–A5) are cancelled where the contract was made: here the cancellation is only
* requested (task "Stornierung im Portal veranlassen bzw. prüfen", the dates stay occupied) until somebody confirms that
* it is effective on the portal ({@see confirmOnPortal()}) – nothing is released silently.
*/
class CancelBooking
{
public const INITIATORS = ['guest' => 'vom Gast', 'landlord' => 'vom Vermieter', 'portal' => 'über das Portal'];
/**
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
*
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord', ?string $reason = null, bool $confirmedOnPortal = false): bool
{
if ($booking->caseType()->isExternallyBinding() && ! $confirmedOnPortal) {
$this->requestOnPortal($booking, $by, $initiatedBy, $reason);
return true;
}
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
}
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy, $reason): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now(), 'portal_cancellation_requested_at' => null]);
app(RecordCancellation::class)->handle($booking, $initiatedBy)->update(['reason' => $reason, 'recorded_by' => $by]);
BookingTask::query()->where('booking_id', $booking->id)
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
// The stay will not take place: its preparation is no longer needed (package 9); issues and follow-ups stay.
BookingTask::query()->where('booking_id', $booking->id)
->whereIn('kind', [BookingTaskKind::ArrivalDetails, BookingTaskKind::Service, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Storniert – entfällt.', 'completed_by' => $by, 'completed_at' => now()]);
$this->refundTask($booking);
if ($costsTask) {
$cost = CancellationCost::calculate($booking);
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => $cost ? 'Vorschlag nach Stornoregel „'.$cost['policy'].'“: '.Money::format($cost['fee']).' ('.$cost['tier_text'].')' : 'Keine Stornoregel hinterlegt – Kosten von Hand festlegen.',
]);
}
});
$booking->loadMissing(['guest', 'property']);
// A cancellation without anything to settle is closed commercially at once; costs or a refund keep it open.
CaseClosure::refresh($booking->fresh());
return $this->notify($booking, $notifyGuest);
}
/**
* A booking binding on a portal was cancelled there (the landlord saw it on the portal, or the portal reported it):
* now the case is cancelled as well. The portal informs the guest; costs are a task only when we collect the money.
*
* @throws ReservationException
*/
public function confirmOnPortal(Booking $booking, string $by, string $initiatedBy = 'portal', ?string $reason = null): bool
{
return $this->handle($booking, notifyGuest: false, costsTask: $booking->process()->payments() === Responsibility::Landlord, by: $by, initiatedBy: $initiatedBy, reason: $reason, confirmedOnPortal: true);
}
/**
* @throws ReservationException
*/
private function requestOnPortal(Booking $booking, string $by, string $initiatedBy, ?string $reason): void
{
DB::transaction(function () use ($booking, $by, $initiatedBy, $reason): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$portal = $booking->processChannel()?->name ?? 'Portal';
$booking->update(['portal_cancellation_requested_at' => now()]);
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Stornierung im Portal „'.$portal.'“ veranlassen und prüfen, ob sie dort wirksam ist. Erst dann „Stornierung bestätigen“ – bis dahin bleibt der Zeitraum belegt.',
]);
CaseLog::record($booking, 'status', 'Stornierung beim Portal '.$portal.' veranlasst ('.(self::INITIATORS[$initiatedBy] ?? $initiatedBy).') – der Vorgang bleibt gebucht, bis sie bestätigt ist', $reason, actor: $by);
});
}
/**
* When the guest paid us more than the cancellation costs, the difference is a refund to check.
*/
private function refundTask(Booking $booking): void
{
if ($booking->process()->payments() !== Responsibility::Landlord || $booking->paidToUs() <= 0) {
return;
}
$cost = CancellationCost::calculate($booking);
$fee = $cost['fee'] ?? null;
$paid = $booking->paidToUs();
if ($fee !== null && $paid <= $fee) {
return;
}
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Bezahlt: '.Money::format($paid).($fee !== null ? ' · Stornokosten laut Regel: '.Money::format($fee).' · zu erstatten: '.Money::format($paid - $fee) : ' · Stornokosten von Hand festlegen, den Rest erstatten').'. Erstattung als Zahlung „Erstattung an den Gast“ erfassen.',
]);
}
private function notify(Booking $booking, bool $notifyGuest): bool
{
$informed = true;
try {
Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, cancelled: true));
} catch (Throwable $exception) {
Log::warning('Stornomitteilung an den Vermieter nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
if ($notifyGuest) {
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, cancelled: true));
} catch (Throwable $exception) {
$informed = false;
Log::warning('Stornomail an den Gast nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
return $informed;
}
}