Files
fewo-stommer/app/Actions/SendInformation.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

187 lines
9.5 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\Availability\AvailabilityChecker;
use App\Documents\DocumentComposer;
use App\Documents\OfferTerms;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\InformationSent;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Inbox;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Package 7 (E-026, P02 "Haltefrist = 0"): answers a request that reserves nothing with an information "unter Vorbehalt" –
* price and availability as checked now, no reservation and no acceptance link that could conclude a contract. The guest
* gets a signed link to ask for the booking ({@see SubmitBookingWish}); everything is checked again then.
*
* Sending again replaces the previous information: older links stop working and a booking wish made on them is void.
*/
class SendInformation
{
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private Inbox $inbox,
) {}
/**
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>, acknowledged?: bool, expected_version?: ?int} $changes
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
{
if ($sendMail && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
$toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Information, $changes)->toConfirm();
if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) {
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm));
}
DB::transaction(function () use ($booking, $changes): void {
$booking->lockForTransition();
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true) || $booking->isHoldActive()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Auskunft beantwortet');
}
if (isset($changes['expected_version']) && $booking->information_version !== (int) $changes['expected_version']) {
throw new ReservationException('Inzwischen wurde schon eine Auskunft gesendet (Version '.$booking->information_version.'). Es wurde nichts erneut gesendet.');
}
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$promoCode = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->offer->quoteFor($booking, $stay, $adjustment, $adjustmentLabel);
if (filled($changes['guest'] ?? null)) {
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
}
$validUntil = filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours());
$booking->update([
'status' => BookingStatus::Reserved,
'hold_expires_at' => null,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $stay->guests,
'promo_code' => $quote->promoCodeApplied ? $promoCode : null,
'price_adjustment' => $adjustment !== 0 ? $adjustment : null,
'price_adjustment_label' => $adjustment !== 0 ? $adjustmentLabel : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'information_version' => $booking->information_version + 1,
'information_sent_at' => now(),
'information_valid_until' => $validUntil,
'offer_message' => $changes['offer_message'] ?? null,
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
// A wish on an older information is void; the guest asks again on the new one.
'wish_at' => null,
'wish' => null,
]);
$booking->refresh();
$booking->update(['information' => [
'version' => $booking->information_version,
'sent_at' => $booking->information_sent_at?->toIso8601String(),
'valid_until' => $validUntil->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => self::quoteHash($booking),
'terms_sha256' => hash('sha256', json_encode($booking->offer_terms['texts'] ?? [])),
]]);
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Durch eine neue Auskunft ersetzt.', 'completed_at' => now(), 'completed_by' => CaseLog::actor()]);
});
$booking->refresh();
CaseLog::record($booking, 'document', 'Auskunft unter Vorbehalt Version '.$booking->information_version.' erstellt (Preis '.Money::format((int) $booking->total).', ohne Reservierung)', data: array_filter([
'kind' => DocumentKind::Information->value,
'template' => $booking->offer_terms['template'] ?? null,
'information' => $booking->information,
'confirmed' => $toConfirm,
]));
if ($sendMail) {
$this->deliver($booking);
}
return $booking;
}
/**
* Sends the information mail; a failing mail server keeps the saved information and is reported in the inbox.
*
* @throws ReservationException
*/
public function deliver(Booking $booking): void
{
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new InformationSent($booking, $this->informationUrl($booking)));
} catch (Throwable $exception) {
Log::warning('Auskunft nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$this->inbox->post(
InboxMessageKind::OfferMailFailed,
'booking-'.$booking->id.':i'.$booking->information_version,
'Auskunft '.$booking->reference.' nicht zugestellt',
'Die Auskunft ist gespeichert, aber die E-Mail konnte nicht versendet werden. Auf der Vorgangsseite kann der Link kopiert und dem Gast anders übermittelt werden.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
throw new ReservationException('Die Auskunft wurde gespeichert, aber die E-Mail konnte nicht versendet werden.');
}
}
/**
* The guest's link to the information page; valid while the information is valid and only for this version.
*/
public function informationUrl(Booking $booking): string
{
$parameters = ['booking' => $booking, 'v' => $booking->information_version];
$until = $booking->information_valid_until ?? now()->addDay();
return $booking->website()?->temporarySignedRoute('information.show', $until, $parameters)
?? URL::temporarySignedRoute('information.show', $until, $parameters);
}
/**
* Fingerprint of the price lines the guest was told.
*/
public static function quoteHash(Booking $booking): string
{
return hash('sha256', json_encode([$booking->quote['lines'] ?? [], $booking->total, $booking->arrival?->toDateString(), $booking->departure?->toDateString(), $booking->guests]));
}
}