From 40d20cb7d1427b9ad18d89687b742afbddb7124d Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 2 Nov 2026 08:29:19 +0100 Subject: [PATCH] Pakete 7 und 9: Auskunft und Buchungswunsch, Aufenthalt und Abschluss (Zwischenstand) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- app/Actions/AutoOffer.php | 24 +- app/Actions/CancelBooking.php | 8 + app/Actions/CloseStay.php | 126 ++++ app/Actions/DecideBookingWish.php | 109 +++ app/Actions/ExpireReservations.php | 9 +- app/Actions/PrepareStays.php | 151 +++++ app/Actions/RecordPayment.php | 99 ++- app/Actions/SendBookingReminders.php | 16 +- app/Actions/SendInformation.php | 186 ++++++ app/Actions/SubmitBookingWish.php | 248 +++++++ app/Console/Commands/RecheckPaymentStatus.php | 58 ++ .../Commands/SendPendingAutoOffers.php | 7 +- app/Documents/DocumentComposer.php | 38 +- app/Enums/BookingTaskKind.php | 51 +- app/Enums/DocumentKind.php | 9 +- app/Enums/ProcessSetting.php | 2 +- .../Forms/DocumentCompositionFields.php | 4 +- app/Filament/Forms/ProcessSettingFields.php | 2 +- .../Pages/Concerns/HandlesWishAndStay.php | 272 ++++++++ .../Resources/Bookings/Pages/ViewBooking.php | 16 +- .../Properties/Schemas/PropertyForm.php | 31 + .../Controllers/InformationController.php | 71 ++ app/Listeners/LogBookingMail.php | 4 +- app/Livewire/BookingRequest.php | 11 + app/Mail/BookingWishAnswered.php | 36 + app/Mail/BookingWishNotice.php | 36 + app/Mail/InformationSent.php | 35 + app/Models/Booking.php | 18 + app/Models/BookingMessage.php | 2 +- app/Models/BookingTask.php | 41 +- app/Models/Payment.php | 4 +- app/Models/Property.php | 32 + app/Process/CaseActivities.php | 151 ++++- app/Process/CaseAutomation.php | 2 +- app/Process/CaseClosure.php | 142 ++++ app/Process/CaseRecorder.php | 27 +- app/Process/WorkList.php | 5 +- ...eate_information_wish_and_stay_closure.php | 68 ++ resources/views/information.blade.php | 84 +++ .../views/livewire/booking-request.blade.php | 8 +- .../views/mail/booking-confirmed.blade.php | 4 +- .../mail/booking-wish-answered.blade.php | 32 + .../views/mail/booking-wish-notice.blade.php | 21 + .../views/mail/information-sent.blade.php | 33 + .../views/mail/reservation-expired.blade.php | 8 + .../views/mail/reservation-received.blade.php | 4 + routes/web.php | 4 + tests/Feature/AutoOfferTest.php | 6 +- tests/Feature/CaseIntakeTest.php | 2 +- tests/Feature/EndToEndStayAcceptanceTest.php | 624 ++++++++++++++++++ .../TestOperationSmtpAcceptanceTest.php | 189 ++++++ tests/Support/smtp-sink.php | 115 ++++ 52 files changed, 3196 insertions(+), 89 deletions(-) create mode 100644 app/Actions/CloseStay.php create mode 100644 app/Actions/DecideBookingWish.php create mode 100644 app/Actions/PrepareStays.php create mode 100644 app/Actions/SendInformation.php create mode 100644 app/Actions/SubmitBookingWish.php create mode 100644 app/Console/Commands/RecheckPaymentStatus.php create mode 100644 app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php create mode 100644 app/Http/Controllers/InformationController.php create mode 100644 app/Mail/BookingWishAnswered.php create mode 100644 app/Mail/BookingWishNotice.php create mode 100644 app/Mail/InformationSent.php create mode 100644 app/Process/CaseClosure.php create mode 100644 database/migrations/2026_11_05_090000_create_information_wish_and_stay_closure.php create mode 100644 resources/views/information.blade.php create mode 100644 resources/views/mail/booking-wish-answered.blade.php create mode 100644 resources/views/mail/booking-wish-notice.blade.php create mode 100644 resources/views/mail/information-sent.blade.php create mode 100644 tests/Feature/EndToEndStayAcceptanceTest.php create mode 100644 tests/Feature/TestOperationSmtpAcceptanceTest.php create mode 100644 tests/Support/smtp-sink.php diff --git a/app/Actions/AutoOffer.php b/app/Actions/AutoOffer.php index 5449a5f..ae394df 100644 --- a/app/Actions/AutoOffer.php +++ b/app/Actions/AutoOffer.php @@ -19,6 +19,9 @@ * Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every * release rule is met, otherwise leaves the request untouched for manual processing and says why. * + * A request without a hold (pre-reservation "no") gets the information "unter Vorbehalt" instead of the offer (package 7); + * its rules are the same except the reservation. + * * Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract * texts released by the landlord (not the sample text; skipped while mails only go to the test recipient), * the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an @@ -30,6 +33,7 @@ public function __construct( private SendOffer $sendOffer, private CalendarClearance $clearance, private AvailabilityChecker $availability, + private SendInformation $sendInformation, ) {} public function applies(Booking $booking): bool @@ -44,11 +48,12 @@ public function blockers(Booking $booking): array { $property = $booking->property; $reasons = []; + $information = ! $booking->process()->preReservation(); - if (! $booking->process()->preReservation()) { - $reasons[] = 'Anfragen reservieren den Zeitraum nicht (Einstellung „Vorreservierung“); ohne Sperre im Kalender wird kein Angebot automatisch erteilt.'; + if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) { + $reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.'; } - if ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive()) { + if (! $information && ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive())) { $reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).'; } if (blank($booking->guest?->email)) { @@ -61,10 +66,11 @@ public function blockers(Booking $booking): array $reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).'; } - // Status, e-mail, dates and the missing reservation are checked above; the composition adds what concerns the document. - $reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])]; + // Status, e-mail and dates are checked above; the composition adds what concerns the document. + $reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, $information ? DocumentKind::Information : DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])]; - return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)]; + // An information reserves nothing and binds nobody: the calendar is checked again when the guest asks for the booking. + return $information ? $reasons : [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)]; } /** @@ -86,7 +92,11 @@ public function handle(Booking $booking): array } try { - $this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]); + if (! $booking->process()->preReservation()) { + $this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]); + } else { + $this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]); + } } catch (QuoteException|ReservationException $exception) { // A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link. return [$exception->getMessage()]; diff --git a/app/Actions/CancelBooking.php b/app/Actions/CancelBooking.php index a099e97..b957d4e 100644 --- a/app/Actions/CancelBooking.php +++ b/app/Actions/CancelBooking.php @@ -11,6 +11,7 @@ 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; @@ -65,6 +66,11 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa ->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); @@ -79,6 +85,8 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa }); $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); } diff --git a/app/Actions/CloseStay.php b/app/Actions/CloseStay.php new file mode 100644 index 0000000..71e6f29 --- /dev/null +++ b/app/Actions/CloseStay.php @@ -0,0 +1,126 @@ +whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid]) + ->whereDate('departure', '<', CarbonImmutable::today()) + ->with(['guest', 'property', 'payments', 'importChannel', 'originChannel']) + ->get(); + + foreach ($stays as $booking) { + // After the departure the arrival details are of no use any more. + foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->get() as $task) { + $task->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Nach der Abreise nicht mehr nötig.', 'completed_by' => CaseLog::SYSTEM, 'completed_at' => now()]); + } + + if (CaseClosure::stayBlockers($booking)->isNotEmpty()) { + continue; + } + + CaseLog::context(fn () => $this->close($booking), actor: CaseLog::SYSTEM.' (automatisch)'); + $closed++; + } + + return $closed; + } + + /** + * The landlord closes the stay; open tasks of the stay are marked as done or handed over with the note. + * + * @throws ReservationException + */ + public function byHand(Booking $booking, string $by, ?string $note = null): void + { + if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgeschlossen'); + } + if ($booking->departure->isAfter(CarbonImmutable::today())) { + throw new ReservationException('Der Aufenthalt endet erst am '.$booking->departure->format('d.m.Y').'.'); + } + + CaseLog::context(function () use ($booking, $by, $note): void { + foreach (CaseClosure::stayBlockers($booking) as $task) { + $task->complete($by, filled($note) ? $note : 'Mit dem Abschluss des Aufenthalts erledigt bzw. übergeben.'); + } + BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open) + ->update(['status' => BookingTaskStatus::Dismissed, 'completed_by' => $by, 'completed_at' => now()]); + $this->close($booking); + }, actor: $by, reason: $note); + } + + private function close(Booking $booking): void + { + DB::transaction(function () use ($booking): void { + $booking->lockForTransition(); + if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) { + return; + } + $booking->update(['status' => BookingStatus::Completed, 'completed_at' => now()]); + $this->followUps($booking); + }); + + CaseClosure::refresh($booking->fresh()); + } + + /** + * Open money becomes a follow-up of the closed stay, so it stays visible and assigned. + */ + private function followUps(Booking $booking): void + { + $booking->unsetRelation('payments'); + $money = CaseMoney::of($booking); + + if ($money->collector() === Responsibility::Landlord && $money->openForUs() > 0) { + $chasing = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()->contains(fn (BookingTask $task): bool => $task->kind->isPayment()); + if (! $chasing) { + BookingTask::openOnce($booking, BookingTaskKind::OpenClaim, '', ['due_on' => today(), 'note' => 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.']); + } + } + + if ($money->collector() === Responsibility::Portal) { + $payout = $money->payout(); + if ($payout['received'] === 0 || ($payout['outstanding'] ?? 0) > 0) { + $portal = $booking->processChannel()?->name ?? 'des Portals'; + BookingTask::openOnce($booking, BookingTaskKind::PayoutCheck, '', [ + 'due_on' => $booking->departure->addDays(14), + 'responsible' => $booking->processChannel()?->name, + 'note' => match (true) { + $payout['values'] !== [] => 'Angekündigt: '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).'; erhalten: '.Money::format($payout['received']).'.', + default => 'Auszahlung von '.$portal.' noch nicht erfasst.', + }, + ]); + } + } + } +} diff --git a/app/Actions/DecideBookingWish.php b/app/Actions/DecideBookingWish.php new file mode 100644 index 0000000..cbd04bf --- /dev/null +++ b/app/Actions/DecideBookingWish.php @@ -0,0 +1,109 @@ +guest?->email)) { + throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.'); + } + + DB::transaction(function () use ($booking, $useTodaysPrice): void { + $booking->lockForTransition(); + + if ($booking->status !== BookingStatus::Reserved || $booking->wish_at === null) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Buchungswunsch bestätigt'); + } + + if ($useTodaysPrice) { + $quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, (string) ($booking->price_adjustment_label ?: 'Zuschlag')); + if ($quote->total() > (int) $booking->total) { + throw new ReservationException('Der heutige Preis ist höher als der Preis der Auskunft. Ohne Zustimmung des Gastes geht das nicht – bitte eine neue Auskunft senden.'); + } + $booking->update(['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()]); + } + + $this->confirm->bind($booking); + $booking->update([ + 'accepted_at' => $booking->wish_at, + 'acceptance' => [ + 'via' => 'booking_wish', + 'information_version' => $booking->wish['information_version'] ?? $booking->information_version, + 'wish_at' => $booking->wish_at?->toIso8601String(), + 'total' => $booking->total, + 'quote_sha256' => SendInformation::quoteHash($booking), + 'terms_sha256' => $booking->wish['terms_sha256'] ?? null, + 'confirmed_by' => CaseLog::actor(), + 'confirmed_at' => now()->toIso8601String(), + ], + ]); + $this->closeTasks($booking, 'Bestätigt.'); + }); + + $booking->refresh(); + CaseLog::record($booking, 'wish', 'Buchungswunsch bestätigt – Buchung verbindlich'); + + return $this->confirm->deliver($booking, $notifyGuest); + } + + /** + * @throws ReservationException + */ + public function decline(Booking $booking, ?string $reason = null, bool $notifyGuest = true): void + { + DB::transaction(function () use ($booking): void { + $booking->lockForTransition(); + if ($booking->status !== BookingStatus::Reserved) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgesagt'); + } + $booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'us', 'hold_expires_at' => null]); + $this->closeTasks($booking, 'Abgesagt.'); + }); + + CaseLog::record($booking, 'wish', 'Buchungswunsch abgesagt', reason: $reason); + + if ($notifyGuest && filled($booking->guest?->email)) { + try { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking->fresh(), 'declined')); + } catch (Throwable $exception) { + Log::warning('Absage zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + } + } + + private function closeTasks(Booking $booking, string $note): void + { + foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)->get() as $task) { + $task->complete(CaseLog::actor(), $note); + } + } +} diff --git a/app/Actions/ExpireReservations.php b/app/Actions/ExpireReservations.php index 7079704..62ad619 100644 --- a/app/Actions/ExpireReservations.php +++ b/app/Actions/ExpireReservations.php @@ -9,7 +9,8 @@ use Illuminate\Support\Facades\Mail; /** - * Marks reservations whose hold time is over as expired and tells the landlord. + * Marks reservations whose hold time is over – and information without a hold whose link expired unanswered – as + * expired and tells the landlord. * The calendar already treats them as free once the hold time is over; this only updates the status. */ class ExpireReservations @@ -18,7 +19,11 @@ public function handle(): int { $expired = Booking::query() ->whereIn('status', BookingStatus::holding()) - ->where('hold_expires_at', '<=', now()) + ->where(fn ($query) => $query + ->where('hold_expires_at', '<=', now()) + // An information without a hold (package 7) ends when its link expires and the guest did not ask for the booking. + ->orWhere(fn ($information) => $information->where('status', BookingStatus::Reserved)->whereNull('hold_expires_at') + ->where('information_valid_until', '<=', now())->whereNull('wish_at'))) ->with(['guest', 'property']) ->get(); diff --git a/app/Actions/PrepareStays.php b/app/Actions/PrepareStays.php new file mode 100644 index 0000000..bf818d7 --- /dev/null +++ b/app/Actions/PrepareStays.php @@ -0,0 +1,151 @@ + 0, 'stay_tasks' => 0]; + + $stays = Booking::query() + ->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid]) + ->whereDate('arrival', '<=', $today->addDays(self::LEAD_DAYS)) + ->whereDate('departure', '>=', $today) + ->with(['guest', 'property', 'importChannel', 'originChannel']) + ->get(); + + foreach ($stays as $booking) { + $created['arrival_details'] += $this->arrivalDetails($booking, $today) ? 1 : 0; + $created['stay_tasks'] += $this->stayTasks($booking); + } + + return $created; + } + + /** + * What is still missing for the arrival, in plain words (empty: nothing). + * + * @return list + */ + public static function missingArrivalDetails(Booking $booking): array + { + if ($booking->isInternal()) { + return []; + } + + return array_values(array_filter([ + $booking->guest === null ? 'Name und Kontakt des Gastes' : null, + $booking->guest !== null && blank($booking->guest->email) && blank($booking->guest->phone) ? 'eine E-Mail-Adresse oder Telefonnummer des Gastes' : null, + $booking->property?->asks_arrival_time && blank($booking->arrival_time) ? 'die Anreisezeit' : null, + ])); + } + + /** + * Opens (or closes) the task for missing arrival details. + */ + private function arrivalDetails(Booking $booking, CarbonImmutable $today): bool + { + $missing = self::missingArrivalDetails($booking); + $open = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->first(); + + if ($missing === []) { + $open?->complete(CaseLog::SYSTEM, 'Die Angaben liegen jetzt vor.'); + + return false; + } + + $checkFrom = $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore() + self::DETAILS_BEFORE_INFO); + if ($today->lessThan($checkFrom)) { + return false; + } + + $portal = $booking->caseType()->isExternallyBinding() ? ' (ggf. im Portal '.($booking->processChannel()?->name ?? '').' nachsehen)' : ''; + $task = BookingTask::openOnce($booking, BookingTaskKind::ArrivalDetails, '', [ + 'due_on' => $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore()), + 'note' => 'Es fehlt: '.implode(', ', $missing).$portal.'.', + ]); + + return $task->wasRecentlyCreated; + } + + /** + * Opens the configured stay tasks and the tasks for booked services; returns how many were opened now. + */ + private function stayTasks(Booking $booking): int + { + $kind = match (true) { + ! $booking->isInternal() => 'rental', + $booking->internal_kind === InternalKind::PrivateStay => 'private', + $booking->internal_kind === InternalKind::OwnUse => 'own', + default => 'block', + }; + $opened = 0; + + foreach ($booking->property?->stayTaskDefinitions() ?? [] as $definition) { + if (! in_array($kind, $definition['applies_to'], true)) { + continue; + } + $due = match ($definition['when']) { + 'after_departure' => $booking->departure, + 'on_arrival' => $booking->arrival, + default => $booking->arrival->subDays($definition['days']), + }; + $task = BookingTask::openOnce($booking, BookingTaskKind::Service, $definition['key'], [ + 'title' => $definition['title'], + 'responsible' => $definition['responsible'], + 'due_on' => $due, + ]); + // Dates of the stay may have changed since the task was opened. + if (! $task->wasRecentlyCreated && $task->status === BookingTaskStatus::Open && ! $task->due_on?->equalTo($due)) { + $task->update(['due_on' => $due]); + } + $opened += $task->wasRecentlyCreated ? 1 : 0; + } + + // Booked services of our own price (a portal's extras are not known item by item). + if (($booking->quote['source'] ?? null) !== 'portal') { + $extras = array_filter((array) ($booking->extras ?? []), fn ($quantity): bool => (int) $quantity > 0); + foreach (Extra::query()->whereIn('id', array_keys($extras))->get() as $extra) { + $task = BookingTask::openOnce($booking, BookingTaskKind::Service, 'extra:'.$extra->id, [ + 'title' => 'Bereitstellen: '.((int) $extras[$extra->id] > 1 ? $extras[$extra->id].' × ' : '').$extra->name, + 'due_on' => $booking->arrival->subDay(), + ]); + $opened += $task->wasRecentlyCreated ? 1 : 0; + } + } + + return $opened; + } +} diff --git a/app/Actions/RecordPayment.php b/app/Actions/RecordPayment.php index 27aabf0..2bf2235 100644 --- a/app/Actions/RecordPayment.php +++ b/app/Actions/RecordPayment.php @@ -3,17 +3,27 @@ namespace App\Actions; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; +use App\Enums\BookingTaskStatus; use App\Enums\PaymentKind; use App\Enums\PaymentMethod; use App\Models\Booking; +use App\Models\BookingTask; use App\Models\Payment; +use App\Pricing\CaseMoney; +use App\Process\CaseClosure; +use App\Process\CaseLog; +use App\Support\Money; use Carbon\CarbonInterface; use Illuminate\Support\Facades\DB; /** * Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the - * portal paid out to us, or we refunded the guest. Only the guest's payments move the booking along - * (Bestätigt → Anzahlung erhalten → Bezahlt); a refund is stored as a negative amount. + * portal paid out to us, or we refunded the guest. A refund is stored as a negative amount. + * + * Only money of the guest that arrived on our account moves the booking along (Bestätigt → Anzahlung erhalten → + * Bezahlt). "Paid according to the portal" and a payout of the portal are facts of their own: they appear in the money + * overview and the history with their own words, never as "Anzahlung erhalten" (package 9, Abschnitt 5). */ class RecordPayment { @@ -21,7 +31,7 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P { $amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount; - return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment { + $payment = DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment { $payment = $booking->payments()->create([ 'amount' => $amount, 'paid_on' => $paidOn->toDateString(), @@ -34,27 +44,84 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P $booking->unsetRelation('payments'); $this->updateStatus($booking); + $this->settleTasks($booking, $kind, $recordedBy ?? CaseLog::actor()); return $payment; }); + + CaseClosure::refresh($booking->fresh()); + + return $payment; } public function updateStatus(Booking $booking): void { - $paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid]; - if (! in_array($booking->status, $paymentStatuses, true)) { - return; - } - - $paid = $booking->paidAmount(); - $status = match (true) { - $paid >= $booking->total => BookingStatus::Paid, - $paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid, - default => BookingStatus::Confirmed, - }; - - if ($status !== $booking->status) { + $status = self::statusFor($booking); + if ($status !== null && $status !== $booking->status) { $booking->update(['status' => $status]); } } + + /** + * The payment status the booking should have by the guest's money on our account, or null when payments do not move + * this booking (not binding, closed, cancelled). + */ + public static function statusFor(Booking $booking): ?BookingStatus + { + if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) { + return null; + } + + $paid = $booking->paidToUs(); + + return match (true) { + $booking->total !== null && $booking->total > 0 && $paid >= $booking->total => BookingStatus::Paid, + $booking->deposit !== null && $paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid, + default => BookingStatus::Confirmed, + }; + } + + /** + * The history line in the words of what really happened. + */ + public static function summary(Booking $booking, PaymentKind $kind, int $amount, CarbonInterface $paidOn, ?string $source): string + { + $portal = $source ?: ($booking->processChannel()?->name ?? 'Portal'); + + return match ($kind) { + PaymentKind::Guest => 'Zahlung des Gastes auf unserem Konto eingegangen: '.Money::format($amount), + PaymentKind::GuestViaPortal => 'Laut '.$portal.' hat der Gast '.Money::format($amount).' an das Portal gezahlt – noch kein Geld bei uns', + PaymentKind::PortalPayout => 'Auszahlung von '.$portal.' auf unserem Konto eingegangen: '.Money::format($amount), + PaymentKind::Refund => 'Erstattung an den Gast: '.Money::format(abs($amount)), + }.' (vom '.$paidOn->format('d.m.Y').')'; + } + + /** + * Tasks that the payment settles: the payout check once nothing is outstanding, the claim after the stay once the + * guest owes nothing more. + */ + private function settleTasks(Booking $booking, PaymentKind $kind, string $by): void + { + $money = CaseMoney::of($booking); + $open = fn (BookingTaskKind $taskKind) => BookingTask::query()->where('booking_id', $booking->id)->where('kind', $taskKind)->where('status', BookingTaskStatus::Open)->get(); + + if ($kind === PaymentKind::PortalPayout) { + $payout = $money->payout(); + if (($payout['outstanding'] ?? 0) === 0) { + $open(BookingTaskKind::PayoutCheck)->each->complete($by, 'Auszahlung erfasst: '.Money::format($payout['received']).'.'); + } + } + + if (in_array($kind, [PaymentKind::Guest, PaymentKind::GuestViaPortal], true)) { + // A reminder that is no longer needed is closed by the payment itself. + if ($booking->openDeposit() === 0) { + $open(BookingTaskKind::DepositReminder)->each->complete($by, 'Anzahlung eingegangen.'); + } + if ($booking->openAmount() === 0) { + foreach ([BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim] as $settled) { + $open($settled)->each->complete($by, 'Betrag vollständig erhalten.'); + } + } + } + } } diff --git a/app/Actions/SendBookingReminders.php b/app/Actions/SendBookingReminders.php index 39ee109..e5a717d 100644 --- a/app/Actions/SendBookingReminders.php +++ b/app/Actions/SendBookingReminders.php @@ -17,7 +17,8 @@ * Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord * (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click * ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured - * number of days before arrival. Completion after departure. + * number of days before arrival. Preparation of the stays and their closing after departure ({@see PrepareStays}, + * {@see CloseStay}). */ class SendBookingReminders { @@ -27,7 +28,7 @@ class SendBookingReminders private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14; /** - * @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int} + * @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int, prepared: int} */ public function handle(): array { @@ -68,18 +69,17 @@ public function handle(): array $booking->update(['arrival_info_sent_at' => now()]); } - $completed = Booking::query() - ->where('status', BookingStatus::Paid) - ->whereDate('departure', '<', $today) - ->get(); - $completed->each->update(['status' => BookingStatus::Completed]); + // Package 9: prepare the coming stays, close the stays whose departure has passed (open money stays as follow-up). + $prepared = app(PrepareStays::class)->handle(); + $completed = app(CloseStay::class)->due(); return [ 'deposit_overdue' => $depositTasks, 'balance_request' => $requestTasks, 'balance_overdue' => $overdueTasks, 'arrival_info' => $arrivals->count(), - 'completed' => $completed->count(), + 'completed' => $completed, + 'prepared' => $prepared['arrival_details'] + $prepared['stay_tasks'], ]; } diff --git a/app/Actions/SendInformation.php b/app/Actions/SendInformation.php new file mode 100644 index 0000000..14d6429 --- /dev/null +++ b/app/Actions/SendInformation.php @@ -0,0 +1,186 @@ +, guest?: array, 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])); + } +} diff --git a/app/Actions/SubmitBookingWish.php b/app/Actions/SubmitBookingWish.php new file mode 100644 index 0000000..6684f06 --- /dev/null +++ b/app/Actions/SubmitBookingWish.php @@ -0,0 +1,248 @@ +loadMissing(['guest', 'property']); + if ($this->alreadyAsked($booking, $version)) { + return self::ALREADY; + } + $this->ensureCurrent($booking, $version); + + // Network access (calendar imports) stays outside the transaction. + rescue(fn () => $this->clearance->refresh($booking->property), report: false); + $stale = $this->clearance->staleImports($booking->property)->pluck('name')->all(); + + $outcome = DB::transaction(function () use ($booking, $version, $ip, $stale): string { + $booking->lockForTransition(); + + if ($this->alreadyAsked($booking, $version)) { + return self::ALREADY; + } + $this->ensureCurrent($booking, $version); + + $record = [ + 'information_version' => $version, + 'at' => now()->toIso8601String(), + 'ip_hash' => $ip !== null ? hash('sha256', $ip.config('app.key')) : null, + 'total_told' => $booking->information['total'] ?? $booking->total, + 'terms_sha256' => $booking->information['terms_sha256'] ?? null, + 'via' => 'information_link', + ]; + + if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) { + $booking->update([ + 'wish_at' => now(), + 'wish' => [...$record, 'outcome' => self::UNAVAILABLE, 'findings' => ['Der Zeitraum ist inzwischen vergeben.']], + 'status' => BookingStatus::Declined, + 'declined_by' => 'us', + ]); + + return self::UNAVAILABLE; + } + + $findings = $this->findings($booking, $stale); + $automatic = $booking->processingMode() === ProcessingMode::Automatic; + $booking->update([ + 'wish_at' => now(), + 'wish' => [...$record, 'total_now' => $findings['total_now'], 'findings' => $findings['findings'], 'outcome' => $automatic && $findings['findings'] === [] ? self::CONFIRMED : self::PENDING], + ]); + + if ($automatic && $findings['findings'] === []) { + $this->confirm->bind($booking); + $booking->update([ + 'accepted_at' => now(), + 'acceptance' => [ + 'via' => 'booking_wish', + 'information_version' => $version, + 'wish_at' => $booking->wish_at?->toIso8601String(), + 'total' => $booking->total, + 'quote_sha256' => SendInformation::quoteHash($booking), + 'terms_sha256' => $record['terms_sha256'], + 'confirmed_by' => 'automatisch nach erneuter Prüfung', + ], + ]); + + return self::CONFIRMED; + } + + BookingTask::openOnce($booking, BookingTaskKind::BookingWish, 'v'.$version, [ + 'due_on' => today(), + 'note' => $findings['findings'] === [] ? 'Zeitraum frei, Preis unverändert.' : implode(' ', $findings['findings']), + ]); + + return self::PENDING; + }); + + $booking->refresh(); + CaseLog::record($booking, 'wish', match ($outcome) { + self::CONFIRMED => 'Buchungswunsch des Gastes – automatisch geprüft und verbindlich bestätigt', + self::PENDING => 'Buchungswunsch des Gastes eingegangen – wartet auf Ihre Bestätigung', + self::UNAVAILABLE => 'Buchungswunsch des Gastes – Zeitraum inzwischen vergeben, keine Buchung', + default => 'Buchungswunsch wiederholt (ohne Wirkung)', + }, data: $outcome === self::ALREADY ? [] : ['wish' => $booking->wish], actor: CaseLog::GUEST); + + $this->notify($booking, $outcome); + + return $outcome; + } + + /** + * Checks that the page shows the form for: the information is the current one, still valid and the request open. + * + * @throws ReservationException + */ + public function ensureCurrent(Booking $booking, int $version): void + { + if ($booking->information_version === 0 || $version !== $booking->information_version) { + throw new ReservationException('Diese Auskunft ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.'); + } + if ($booking->wish_at !== null) { + throw new ReservationException('Zu dieser Auskunft liegt Ihr Buchungswunsch bereits vor.'); + } + if ($booking->status !== BookingStatus::Reserved) { + throw new ReservationException(in_array($booking->status, BookingStatus::occupying(), true) + ? 'Ihre Buchung ist bereits verbindlich bestätigt – Sie müssen nichts weiter tun.' + : 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.'); + } + if (! $booking->information_valid_until?->isFuture()) { + throw new ReservationException('Diese Auskunft ist abgelaufen. Gern können Sie über unsere Webseite neu anfragen; wir prüfen dann Preis und Verfügbarkeit erneut.'); + } + } + + /** + * Everything that keeps the wish from being confirmed automatically, and the price of today. + * + * @param list $stale names of portals whose calendar is not current + * @return array{findings: list, total_now: ?int} + */ + public function findings(Booking $booking, array $stale = []): array + { + $findings = []; + $totalNow = null; + try { + $label = (string) ($booking->price_adjustment_label ?: 'Zuschlag'); + $quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, $label); + $totalNow = $quote->total(); + $told = (int) ($booking->information['total'] ?? $booking->total); + if ($totalNow !== $told) { + $findings[] = 'Der Preis hat sich seit der Auskunft geändert: damals '.Money::format($told).', heute '.Money::format($totalNow).'.'; + } + } catch (QuoteException $exception) { + $findings[] = 'Der Preis lässt sich heute nicht berechnen: '.$exception->getMessage(); + } + + if ($stale !== []) { + $findings[] = 'Der Kalenderstand von '.implode(', ', $stale).' ist nicht aktuell.'; + } + + $findings = [...$findings, ...app(CaseAutomation::class)->documentBlockers($booking)]; + + // What the confirmation with the contract would need to be confirmed by the landlord (unreleased texts, gaps). + foreach (app(DocumentComposer::class)->compose($booking, DocumentKind::Confirmation)->toConfirm() as $point) { + $findings[] = $point; + } + + return ['findings' => array_values(array_unique($findings)), 'total_now' => $totalNow]; + } + + private function alreadyAsked(Booking $booking, int $version): bool + { + return $booking->wish_at !== null && ($booking->wish['information_version'] ?? null) === $version; + } + + /** + * Mails after the commit; none of them can undo what was decided. + */ + private function notify(Booking $booking, string $outcome): void + { + if ($outcome === self::ALREADY) { + return; + } + + if ($outcome === self::CONFIRMED) { + $this->confirm->deliver($booking); + } + + try { + if ($outcome !== self::CONFIRMED && filled($booking->guest?->email)) { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking, $outcome)); + } + Mail::to(Settings::notificationRecipients())->send(new BookingWishNotice($booking, $outcome)); + } catch (Throwable $exception) { + Log::warning('Mail zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + + if ($outcome === self::UNAVAILABLE) { + $this->inbox->post( + InboxMessageKind::OfferRejected, + 'wish-'.$booking->id.':i'.$booking->information_version, + 'Buchungswunsch '.$booking->reference.': Zeitraum inzwischen vergeben', + 'Der Gast hat aus der Auskunft die Buchung angefragt, aber der Zeitraum ist inzwischen belegt. Es ist keine Buchung entstanden; der Gast hat eine freundliche Absage erhalten.', + actionUrl: BookingResource::getUrl('view', ['record' => $booking]), + propertyId: $booking->property_id, + ); + } + } +} diff --git a/app/Console/Commands/RecheckPaymentStatus.php b/app/Console/Commands/RecheckPaymentStatus.php new file mode 100644 index 0000000..3330ffc --- /dev/null +++ b/app/Console/Commands/RecheckPaymentStatus.php @@ -0,0 +1,58 @@ +option('apply'); + $rows = []; + + $succeeded = $runner->each(function (Tenant $tenant) use ($apply, &$rows): void { + $cases = Booking::query()->with(['payments', 'property', 'importChannel', 'originChannel']) + ->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])->get(); + + foreach ($cases as $booking) { + $target = RecordPayment::statusFor($booking); + if ($target === null || $target === $booking->status) { + continue; + } + $rows[] = [$tenant->name, $booking->reference, $booking->status->getLabel(), $target->getLabel(), $apply ? 'korrigiert' : 'Vorschau']; + if ($apply) { + CaseLog::context(fn () => $booking->update(['status' => $target]), actor: CaseLog::SYSTEM, reason: 'Zahlungsstatus nach neuer Regel: „laut Portal bezahlt“ ist kein Eingang auf unserem Konto (cases:recheck-payment-status).'); + } + } + }); + + if ($rows === []) { + $this->info('Kein Vorgang mit abweichendem Zahlungsstatus.'); + } else { + $this->table(['Vermieter', 'Vorgang', 'bisher', 'nach neuer Regel', 'Ergebnis'], $rows); + if (! $apply) { + $this->comment('Nur Vorschau. Mit --apply werden die Status korrigiert und im Verlauf vermerkt.'); + } + } + + if ($succeeded < $runner->tenants()->count()) { + $this->error('Für mindestens einen Vermieter ist die Prüfung fehlgeschlagen (siehe Log).'); + + return self::FAILURE; + } + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/SendPendingAutoOffers.php b/app/Console/Commands/SendPendingAutoOffers.php index aa45eac..bef4684 100644 --- a/app/Console/Commands/SendPendingAutoOffers.php +++ b/app/Console/Commands/SendPendingAutoOffers.php @@ -25,10 +25,13 @@ public function handle(AutoOffer $autoOffer, TenantRunner $runner): int $pending = Booking::query() ->where('status', BookingStatus::Reserved) ->where('offer_version', 0) - ->where('hold_expires_at', '>', now()) + ->where('information_version', 0) + // Held requests while their hold runs; requests without a hold (information, package 7) for two weeks. + ->where(fn ($query) => $query->where('hold_expires_at', '>', now())->orWhere(fn ($open) => $open->whereNull('hold_expires_at')->where('created_at', '>', now()->subDays(14)))) + ->where(fn ($query) => $query->whereNull('intake')->orWhere('intake', 'inquiry')) ->with(['property', 'guest', 'importChannel', 'originChannel']) ->get() - ->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && $booking->process()->preReservation()); + ->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && ($booking->isHoldActive() || ! $booking->process()->preReservation())); $sent = 0; foreach ($pending as $booking) { diff --git a/app/Documents/DocumentComposer.php b/app/Documents/DocumentComposer.php index 12de141..bff9d75 100644 --- a/app/Documents/DocumentComposer.php +++ b/app/Documents/DocumentComposer.php @@ -2,6 +2,7 @@ namespace App\Documents; +use App\Actions\SendInformation; use App\Actions\SendOffer; use App\Availability\AvailabilityChecker; use App\Enums\BookingStatus; @@ -55,11 +56,12 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha $draft = clone $booking; $draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null); - if ($kind === DocumentKind::Offer) { - $findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes)]; + $quoted = in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true); + if ($quoted) { + $findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes, $kind)]; } - $frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms))); + $frozen = ! $quoted && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms))); $explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null); $template = match (true) { $kind === DocumentKind::StayConfirmation => null, @@ -99,17 +101,19 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha } /** - * Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will. + * Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} (and the information + * of a request without a hold, {@see SendInformation}) will. * * @param array $changes * @return list */ - private function prepareOffer(Booking $booking, Booking $draft, array $changes): array + private function prepareOffer(Booking $booking, Booking $draft, array $changes, DocumentKind $kind = DocumentKind::Offer): array { $findings = []; + $information = $kind === DocumentKind::Information; - if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) { - $findings[] = DocumentFinding::blocker('Für diesen Vorgang ist kein Angebot mehr möglich ('.$booking->status->getLabel().').'); + if (! in_array($booking->status, $information ? [BookingStatus::Reserved, BookingStatus::Expired] : [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) { + $findings[] = DocumentFinding::blocker('Für diesen Vorgang ist '.($information ? 'keine Auskunft' : 'kein Angebot').' mehr möglich ('.$booking->status->getLabel().').'); } try { @@ -141,6 +145,20 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes): $findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.'); } + if ($information) { + $draft->forceFill([ + 'information_valid_until' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()), + 'information_version' => $booking->information_version + 1, + 'offer_message' => $changes['offer_message'] ?? $booking->offer_message, + ]); + $findings[] = DocumentFinding::info('Unverbindliche Auskunft: Der Zeitraum wird nicht reserviert, und der Gast kann nicht direkt annehmen. Fragt er die Buchung an, wird erneut geprüft.'); + if ($booking->information_version > 0) { + $findings[] = DocumentFinding::info('Ersetzt Auskunft Version '.$booking->information_version.'; deren Link wird ungültig.'); + } + + return $findings; + } + $draft->forceFill([ 'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()), 'offer_version' => $booking->offer_version + 1, @@ -149,7 +167,7 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes): ]); if (! $booking->process()->preReservation()) { - $findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Ein Angebot mit Annahmelink reserviert ihn trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen. Eine Auskunft ohne Reservierung gibt es erst in einem späteren Ausbauschritt.', DocumentFinding::HOLD_ZERO); + $findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht; vorgesehen ist eine unverbindliche Auskunft. Ein Angebot mit Annahmelink reserviert den Zeitraum für diesen Vorgang trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen.', DocumentFinding::HOLD_ZERO); } if ($booking->offer_version > 0) { $findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.'); @@ -176,7 +194,7 @@ private function commonFindings(Booking $booking, Booking $draft, DocumentKind $ } elseif (blank($draft->guest->email)) { $findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.'); } - if ($kind !== DocumentKind::Offer && $booking->total === null) { + if (! in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) && $booking->total === null) { $findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.'); } if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) { @@ -249,7 +267,7 @@ private function priceSource(Booking $booking, Booking $draft, DocumentKind $kin return match (true) { $draft->total === null => 'noch nicht bekannt', ($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet', - $kind === DocumentKind::Offer => 'aus Ihren Preisen berechnet', + in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) => 'aus Ihren Preisen berechnet', $booking->accepted_at !== null => 'wie im angenommenen Angebot', default => 'aus Ihren Preisen berechnet', }; diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index a299fd9..9ce05a4 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -8,6 +8,10 @@ /** * What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is * sent to the guest until the landlord has checked the payment and chooses to send the mail. + * + * Package 9 sorts every task into what it holds up: tasks of the stay ({@see self::blocksStay()}) keep the stay from + * being closed, commercial tasks ({@see self::isCommercial()}) keep the case from being settled, follow-ups hold up + * neither and simply stay on the case until they are done. */ enum BookingTaskKind: string implements HasLabel { @@ -20,6 +24,13 @@ enum BookingTaskKind: string implements HasLabel case PortalCancellationReported = 'portal_cancel_reported'; case PortalChangeReported = 'portal_change_reported'; case RefundCheck = 'refund_check'; + case BookingWish = 'booking_wish'; + case ArrivalDetails = 'arrival_details'; + case Service = 'service'; + case Issue = 'issue'; + case FollowUp = 'follow_up'; + case PayoutCheck = 'payout_check'; + case OpenClaim = 'open_claim'; public function getLabel(): string { @@ -33,12 +44,48 @@ public function getLabel(): string self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen', self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen', self::RefundCheck => 'Erstattung an den Gast prüfen', + self::BookingWish => 'Buchungswunsch bestätigen?', + self::ArrivalDetails => 'Anreisedaten beim Gast erfragen', + self::Service => 'Leistung vorbereiten', + self::Issue => 'Abweichung oder Problem klären', + self::FollowUp => 'Folgeaufgabe', + self::PayoutCheck => 'Auszahlung des Portals prüfen', + self::OpenClaim => 'Offenen Betrag nach der Abreise klären', }; } + /** + * Whether this is a payment reminder task (created by the daily run, settled by a payment or a reminder mail). + */ public function isPayment(): bool { - return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck], true); + return in_array($this, [self::DepositReminder, self::BalanceRequest, self::BalanceReminder], true); + } + + /** + * Whether an open task of this kind keeps the stay from being closed (it belongs to the stay itself). + */ + public function blocksStay(): bool + { + return in_array($this, [self::Service, self::Issue, self::PortalChangeReported], true); + } + + /** + * Whether an open task of this kind keeps the case from being commercially settled. + */ + public function isCommercial(): bool + { + return $this->isPayment() || in_array($this, [self::CancellationFee, self::RefundCheck, self::PayoutCheck, self::OpenClaim], true); + } + + /** + * Kinds the landlord adds by hand on a case (several per case, each with its own title). + * + * @return list + */ + public static function manual(): array + { + return [self::Service, self::Issue, self::FollowUp]; } /** @@ -52,7 +99,7 @@ public function reminder(): ?array self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'], self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'], self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'], - self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck => null, + default => null, }; } } diff --git a/app/Enums/DocumentKind.php b/app/Enums/DocumentKind.php index 4b3b8e4..259539e 100644 --- a/app/Enums/DocumentKind.php +++ b/app/Enums/DocumentKind.php @@ -9,8 +9,8 @@ * The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case * type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the * confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation - * without an acceptance link (E-004). Information "unter Vorbehalt" (package 7) and the stay confirmation of A6 - * (package 6) are prepared as working drafts but cannot be sent yet. + * without an acceptance link (E-004), a request without a hold gets the information "unter Vorbehalt" with the link to + * ask for the booking (package 7, E-026). */ enum DocumentKind: string implements HasLabel { @@ -40,7 +40,7 @@ public function description(): string { return match ($this) { self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.', - self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit ohne Zusage; der Gast kann die Buchung anfragen. Folgt mit Paket 7.', + self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit zum Zeitpunkt der Prüfung, ohne Reservierung und ohne Zusage. Der Gast kann daraus die Buchung anfragen; verbindlich wird sie erst mit Ihrer (oder der automatischen) Bestätigung nach erneuter Prüfung.', self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.', self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.', self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.', @@ -59,6 +59,7 @@ public static function forCase(Booking $booking): ?self $booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal, $booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord, $booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation, + ! $profile->preReservation() => self::Information, default => self::Offer, }; } @@ -84,7 +85,7 @@ public function containsContract(): bool */ public function isAvailable(): bool { - return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true); + return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true); } /** diff --git a/app/Enums/ProcessSetting.php b/app/Enums/ProcessSetting.php index 1006f3f..6a4736a 100644 --- a/app/Enums/ProcessSetting.php +++ b/app/Enums/ProcessSetting.php @@ -41,7 +41,7 @@ public function question(): string return match ($this) { self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?', self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?', - self::HoldHours => 'Wie lange gilt ein Angebot (und bleibt der Zeitraum reserviert)?', + self::HoldHours => 'Wie lange gilt ein Angebot bzw. eine unverbindliche Auskunft (mit Reservierung: so lange bleibt der Zeitraum reserviert)?', self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?', self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?', self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?', diff --git a/app/Filament/Forms/DocumentCompositionFields.php b/app/Filament/Forms/DocumentCompositionFields.php index ba643a9..cc0bd6a 100644 --- a/app/Filament/Forms/DocumentCompositionFields.php +++ b/app/Filament/Forms/DocumentCompositionFields.php @@ -9,6 +9,7 @@ use App\Enums\DocumentKind; use App\Mail\BookingConfirmed; use App\Mail\BookingDocumentation; +use App\Mail\InformationSent; use App\Mail\OfferMade; use App\Mail\StayConfirmed; use App\Models\Booking; @@ -86,6 +87,7 @@ private static function mailPreview(DocumentComposition $composition): string try { return match ($composition->kind) { DocumentKind::Offer => (new OfferMade($draft, '#'))->render(), + DocumentKind::Information => (new InformationSent($draft, '#'))->render(), DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(), DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(), default => (new BookingConfirmed($draft))->render(), @@ -100,7 +102,7 @@ private static function mailPreview(DocumentComposition $composition): string private static function documentPreview(DocumentComposition $composition): string { try { - [$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer); + [$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: in_array($composition->kind, [DocumentKind::Offer, DocumentKind::Information], true)); return view($view, $data)->render(); } catch (Throwable $exception) { diff --git a/app/Filament/Forms/ProcessSettingFields.php b/app/Filament/Forms/ProcessSettingFields.php index 0c29ae7..863364c 100644 --- a/app/Filament/Forms/ProcessSettingFields.php +++ b/app/Filament/Forms/ProcessSettingFields.php @@ -34,7 +34,7 @@ public static function field(string $name, ProcessSetting $setting, string $inhe return (match ($setting) { ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder) ->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'), - ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – eine Anfrage reserviert nichts'])->placeholder($placeholder), + ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – der Gast erhält eine unverbindliche Auskunft und kann daraus die Buchung anfragen (erneute Prüfung vor der Bestätigung)'])->placeholder($placeholder), ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder), ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder), ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder), diff --git a/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php b/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php new file mode 100644 index 0000000..1b2e092 --- /dev/null +++ b/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php @@ -0,0 +1,272 @@ +label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden') + ->icon(Heroicon::OutlinedPaperAirplane) + ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking + && ! $this->record->process()->preReservation() && $this->record->offer_version === 0 && ! $this->record->isHoldActive()) + ->modalHeading('Unverbindliche Auskunft an den Gast') + ->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.') + ->modalSubmitActionLabel('Senden') + ->modalWidth('4xl') + ->fillForm(fn (): array => [ + 'expected_version' => $this->record->information_version, + 'arrival' => $this->record->arrival->toDateString(), + 'departure' => $this->record->departure->toDateString(), + 'guests' => $this->record->guests, + 'promo_code' => $this->record->promo_code, + 'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null, + 'price_adjustment_label' => $this->record->price_adjustment_label, + 'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'), + 'offer_message' => $this->record->offer_message, + ]) + ->schema([ + Hidden::make('expected_version'), + ...DocumentCompositionFields::make($this->record, DocumentKind::Information, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message']))), + Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true), + Section::make('Anpassen')->description('Zeitraum, Preis und wie lange der Gast die Buchung anfragen kann.')->collapsed()->schema([ + Section::make('Termin')->columns(3)->schema([ + DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true), + DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true), + TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true), + ]), + Section::make('Preis')->columns(3)->schema([ + TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true), + TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true), + TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true), + ]), + DateTimePicker::make('valid_until')->label('Buchung anfragen bis')->helperText('Der Zeitraum bleibt bis dahin trotzdem frei buchbar für andere.')->seconds(false)->after('now')->required()->live(onBlur: true), + ]), + ]) + ->action(fn (array $data, SendInformation $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Auskunft gesendet')); + } + + private function decideWishAction(): Action + { + return Action::make('decideWish') + ->label('Buchungswunsch bestätigen oder absagen …') + ->icon(Heroicon::OutlinedCheckCircle) + ->visible(fn (): bool => $this->record->status === BookingStatus::Reserved && $this->record->wish_at !== null) + ->modalHeading('Buchungswunsch des Gastes') + ->modalDescription(fn (): string => 'Angefragt am '.$this->record->wish_at?->format('d.m.Y, H:i').' Uhr. Bei „Bestätigen“ wird die Verfügbarkeit noch einmal geprüft; der Gast erhält die Buchungsbestätigung mit dem Mietvertrag.') + ->modalSubmitActionLabel('Ausführen') + ->schema(fn (): array => [ + Text::make($this->wishCheckText()), + Radio::make('decision')->label('Entscheidung')->required()->default('confirm')->live()->options(array_filter([ + 'confirm' => 'Bestätigen zum Preis der Auskunft ('.Money::format((int) $this->record->total).')', + 'confirm_today' => $this->todaysTotal() !== null && $this->todaysTotal() < (int) $this->record->total ? 'Bestätigen zum heutigen, niedrigeren Preis ('.Money::format((int) $this->todaysTotal()).')' : null, + 'decline' => 'Absagen – der Gast erhält eine freundliche Absage', + ])), + Textarea::make('reason')->label('Grund (nur für den Verlauf)')->rows(2)->visible(fn (Get $get): bool => $get('decision') === 'decline'), + ]) + ->action(function (array $data, DecideBookingWish $decide): void { + $this->runWorkflow(fn () => match ($data['decision']) { + 'decline' => $decide->decline($this->record, $data['reason'] ?? null), + default => $decide->confirm($this->record, $data['decision'] === 'confirm_today'), + }, $data['decision'] === 'decline' ? 'Abgesagt' : 'Buchung bestätigt'); + }); + } + + private function arrivalDetailsAction(): Action + { + return Action::make('arrivalDetails') + ->label('Anreisedaten eintragen') + ->icon(Heroicon::OutlinedClock) + ->visible(fn (): bool => $this->record->isBinding() && ! $this->record->isInternal() && $this->record->departure->isFuture()) + ->modalHeading('Anreisedaten') + ->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Was fehlt, steht in der Aufgabe; nur Bekanntes eintragen.') + ->fillForm(fn (): array => ['arrival_time' => $this->record->arrival_time, 'email' => $this->record->guest?->email, 'phone' => $this->record->guest?->phone]) + ->schema([ + TextInput::make('arrival_time')->label('Anreisezeit')->placeholder('z. B. gegen 16 Uhr')->maxLength(40), + TextInput::make('phone')->label('Telefon des Gastes')->tel()->maxLength(50)->visible(fn (): bool => $this->record->guest !== null), + TextInput::make('email')->label('E-Mail des Gastes')->email()->maxLength(255)->visible(fn (): bool => $this->record->guest !== null), + ]) + ->action(function (array $data): void { + $this->record->update(['arrival_time' => filled($data['arrival_time'] ?? null) ? trim((string) $data['arrival_time']) : null]); + if ($this->record->guest !== null) { + $this->record->guest->update(array_filter(['phone' => $data['phone'] ?? null, 'email' => isset($data['email']) ? mb_strtolower(trim((string) $data['email'])) : null], fn ($value): bool => filled($value))); + } + app(PrepareStays::class)->handle(); + $this->record->refresh(); + Notification::make()->title('Gespeichert')->success()->send(); + }); + } + + private function completeTaskAction(): Action + { + return Action::make('completeTask') + ->label('Aufgabe erledigen …') + ->icon(Heroicon::OutlinedCheck) + ->visible(fn (): bool => $this->openTasks() !== []) + ->modalHeading('Aufgabe erledigen') + ->modalDescription('Erledigt oder an jemanden übergeben (z. B. Reinigung, Portal, Steuerberater). Die Notiz steht im Verlauf.') + ->fillForm(fn (): array => ['task' => array_key_first($this->openTasks()), 'outcome' => 'done']) + ->schema([ + Select::make('task')->label('Aufgabe')->options(fn (): array => $this->openTasks())->required(), + Radio::make('outcome')->label('Ergebnis')->required()->options([ + 'done' => 'Erledigt', + 'handed_over' => 'Übergeben – jemand anderes kümmert sich', + 'dismissed' => 'Entfällt', + ])->live(), + TextInput::make('handed_to')->label('Übergeben an')->maxLength(120)->required(fn (Get $get): bool => $get('outcome') === 'handed_over')->visible(fn (Get $get): bool => $get('outcome') === 'handed_over'), + Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000), + ]) + ->action(function (array $data): void { + $task = BookingTask::query()->where('booking_id', $this->record->id)->whereKey($data['task'])->where('status', BookingTaskStatus::Open)->first(); + if ($task === null) { + Notification::make()->title('Diese Aufgabe ist schon erledigt.')->warning()->send(); + + return; + } + $note = trim(implode(' · ', array_filter([$data['outcome'] === 'handed_over' ? 'Übergeben an '.$data['handed_to'] : null, $data['note'] ?? null]))); + if ($data['outcome'] === 'dismissed') { + $task->update(['status' => BookingTaskStatus::Dismissed, 'note' => $note !== '' ? $note : $task->note, 'completed_by' => CaseLog::actor(), 'completed_at' => now()]); + } else { + if ($data['outcome'] === 'handed_over') { + $task->responsible = (string) $data['handed_to']; + } + $task->complete(CaseLog::actor(), $note !== '' ? $note : null); + } + $this->record->refresh(); + Notification::make()->title('Aufgabe vermerkt')->success()->send(); + }); + } + + private function addTaskAction(): Action + { + return Action::make('addTask') + ->label('Abweichung oder Aufgabe festhalten …') + ->icon(Heroicon::OutlinedPencilSquare) + ->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying(), BookingStatus::Cancelled], true)) + ->modalHeading('Abweichung oder Aufgabe festhalten') + ->modalDescription('Zum Aufenthalt (z. B. späte Anreise, defekte Kaffeemaschine, Schaden) – als Aufgabe am Vorgang, keine eigene Verwaltung.') + ->schema([ + Radio::make('kind')->label('Art')->required()->default(BookingTaskKind::Issue->value)->options([ + BookingTaskKind::Issue->value => 'Abweichung oder Problem beim Aufenthalt – muss vor dem Abschluss des Aufenthalts geklärt sein', + BookingTaskKind::Service->value => 'Leistung vorbereiten (z. B. Kinderbett, zusätzliche Reinigung)', + BookingTaskKind::FollowUp->value => 'Folgeaufgabe nach dem Aufenthalt (z. B. Schaden abrechnen, Reparatur) – hält den Abschluss nicht auf', + ]), + TextInput::make('title')->label('Was?')->required()->maxLength(200), + TextInput::make('responsible')->label('Wer kümmert sich? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120), + DatePicker::make('due_on')->label('Bis wann? (optional)'), + Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000), + ]) + ->action(function (array $data): void { + BookingTask::openOnce($this->record, BookingTaskKind::from($data['kind']), 'manual:'.now()->format('YmdHisv'), [ + 'title' => trim((string) $data['title']), + 'responsible' => filled($data['responsible'] ?? null) ? trim((string) $data['responsible']) : null, + 'due_on' => $data['due_on'] ?? null, + 'note' => $data['note'] ?? null, + ]); + $this->record->refresh(); + Notification::make()->title('Festgehalten')->success()->send(); + }); + } + + private function closeStayAction(): Action + { + return Action::make('closeStay') + ->label(fn (): string => $this->record->isInternal() ? 'Abschließen …' : 'Aufenthalt abschließen …') + ->icon(Heroicon::OutlinedFlag) + ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true) && ! $this->record->departure->isFuture()) + ->modalHeading('Aufenthalt abschließen') + ->modalDescription(fn (): string => ($blockers = CaseClosure::stayBlockers($this->record))->isEmpty() + ? 'Für den Aufenthalt ist nichts mehr offen. Offene Zahlungen oder Auszahlungen bleiben als kaufmännische Punkte am Vorgang.' + : 'Noch offen für den Aufenthalt: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', ').'. Mit dem Abschluss werden sie als erledigt bzw. übergeben vermerkt.') + ->schema([Textarea::make('note')->label('Notiz (z. B. „Reinigung erledigt, Schlüssel zurück“)')->rows(2)->maxLength(500)]) + ->action(fn (array $data, CloseStay $close) => $this->runWorkflow(fn () => $close->byHand($this->record, CaseLog::actor(), $data['note'] ?? null), 'Aufenthalt abgeschlossen')); + } + + private function settleAction(): Action + { + return Action::make('settle') + ->label('Kaufmännisch abschließen …') + ->icon(Heroicon::OutlinedBanknotes) + ->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)]) + ->action(function (array $data): void { + CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor()); + $this->record->refresh(); + Notification::make()->title('Kaufmännisch abgeschlossen')->success()->send(); + }); + } + + /** + * Open tasks the landlord can settle on the page (not the ones with an action of their own). + * + * @return array + */ + private function openTasks(): array + { + return BookingTask::query()->where('booking_id', $this->record->id)->where('status', BookingTaskStatus::Open) + ->whereNotIn('kind', [BookingTaskKind::BookingWish, BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder]) + ->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get() + ->mapWithKeys(fn (BookingTask $task): array => [$task->id => $task->label().($task->due_on ? ' (fällig '.$task->due_on->format('d.m.Y').')' : '')])->all(); + } + + private function wishCheckText(): string + { + $wish = (array) ($this->record->wish ?? []); + $findings = (array) ($wish['findings'] ?? []); + $available = app(AvailabilityChecker::class)->isAvailable($this->record->property, $this->record->arrival, $this->record->departure, ignore: $this->record); + + return ($available ? 'Der Zeitraum ist im Moment frei. ' : 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. ') + .($findings === [] ? 'Bei der Prüfung des Wunsches war alles in Ordnung.' : 'Bei der Prüfung des Wunsches fiel auf: '.implode(' ', $findings)); + } + + private function todaysTotal(): ?int + { + try { + return app(SendOffer::class)->quoteFor($this->record, new StayRequest($this->record->arrival, $this->record->departure, $this->record->guests, $this->record->extras ?? [], $this->record->promo_code), (int) $this->record->price_adjustment, (string) ($this->record->price_adjustment_label ?: 'Zuschlag'))->total(); + } catch (Throwable) { + return null; + } + } +} diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index aa1f477..8e232f7 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -31,6 +31,7 @@ use App\Filament\Forms\Components\EuroInput; use App\Filament\Forms\DocumentCompositionFields; use App\Filament\Resources\Bookings\BookingResource; +use App\Filament\Resources\Bookings\Pages\Concerns\HandlesWishAndStay; use App\Models\Booking; use App\Models\BookingChange; use App\Models\BookingTask; @@ -79,6 +80,8 @@ */ class ViewBooking extends ViewRecord { + use HandlesWishAndStay; + protected static string $resource = BookingResource::class; /** Actions for the expert view only. */ @@ -97,8 +100,15 @@ public function getSubheading(): string|Htmlable|null protected function getHeaderActions(): array { $actions = collect([ + $this->sendInformationAction(), + $this->decideWishAction(), $this->sendOfferAction(), $this->provideContactAction(), + $this->arrivalDetailsAction(), + $this->completeTaskAction(), + $this->addTaskAction(), + $this->closeStayAction(), + $this->settleAction(), $this->requestContactAction(), AssignGuestAction::make(), $this->confirmAction(), @@ -143,7 +153,11 @@ private function isExpert(): bool private function sendOfferAction(): Action { return Action::make('sendOffer') - ->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot prüfen und senden') + ->label(fn (): string => match (true) { + $this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden', + ! $this->record->process()->preReservation() => 'Stattdessen verbindliches Angebot mit Reservierung senden', + default => 'Angebot prüfen und senden', + }) ->icon(Heroicon::OutlinedPaperAirplane) ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking) ->modalHeading('Angebot an den Gast') diff --git a/app/Filament/Resources/Properties/Schemas/PropertyForm.php b/app/Filament/Resources/Properties/Schemas/PropertyForm.php index 51d8dbc..9d0328b 100644 --- a/app/Filament/Resources/Properties/Schemas/PropertyForm.php +++ b/app/Filament/Resources/Properties/Schemas/PropertyForm.php @@ -13,7 +13,9 @@ use App\Models\Site; use App\Models\User; use App\Support\Settings; +use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\KeyValue; +use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TimePicker; @@ -144,6 +146,35 @@ public static function configure(Schema $schema): Schema ->placeholder('Texte der Webseite') ->helperText('Wird bei neuen Angeboten verwendet, sofern das Portal keine eigene Vorlage hat.'), ]), + Section::make('Aufenthalt vorbereiten und abschließen') + ->description('Was bei jedem Aufenthalt in dieser Wohnung zu tun ist. Jede Zeile wird rechtzeitig zur Aufgabe am Vorgang – keine Personalplanung. Gebuchte Leistungen (z. B. Wäschepaket) kommen automatisch dazu.') + ->collapsed() + ->schema([ + Toggle::make('asks_arrival_time') + ->label('Anreisezeit erfragen') + ->helperText('Fehlt sie wenige Tage vor der Anreise, erscheint die Aufgabe „Anreisedaten beim Gast erfragen“. Kontaktdaten werden immer geprüft.'), + Repeater::make('stay_tasks') + ->label('Aufgaben je Aufenthalt') + ->addActionLabel('Aufgabe hinzufügen') + ->defaultItems(0) + ->columns(4) + ->schema([ + TextInput::make('title')->label('Was?')->placeholder('z. B. Endreinigung')->required()->maxLength(120)->columnSpan(2), + Select::make('when')->label('Wann?')->required()->default('before_arrival')->live()->options([ + 'before_arrival' => 'vor der Anreise', + 'on_arrival' => 'am Anreisetag', + 'after_departure' => 'am Abreisetag', + ]), + TextInput::make('days')->label('Tage vorher')->integer()->minValue(0)->maxValue(14)->default(1)->visible(fn (Get $get): bool => $get('when') === 'before_arrival'), + TextInput::make('responsible')->label('Wer? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120)->columnSpan(2), + CheckboxList::make('applies_to')->label('Bei')->required()->default(['rental'])->columns(4)->columnSpan(2)->options([ + 'rental' => 'Gästebuchungen', + 'private' => 'Familie/Freunde', + 'own' => 'eigener Nutzung', + 'block' => 'Sperren', + ]), + ]), + ]), Section::make('Abweichende Abwicklung dieser Wohnung') ->description('Nur nötig, wenn diese Wohnung anders bearbeitet wird als in „So arbeite ich“ eingestellt. Leere Felder folgen Ihren Standardeinstellungen.') ->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert) diff --git a/app/Http/Controllers/InformationController.php b/app/Http/Controllers/InformationController.php new file mode 100644 index 0000000..a4ce750 --- /dev/null +++ b/app/Http/Controllers/InformationController.php @@ -0,0 +1,71 @@ +loadMissing(['guest', 'property']); + $version = (int) $request->query('v'); + + $problem = null; + try { + $wish->ensureCurrent($booking, $version); + } catch (ReservationException $exception) { + $problem = $exception->getMessage(); + } + + return view('information', [ + 'booking' => $booking, + 'problem' => $problem, + 'canAsk' => $problem === null, + 'wishUrl' => $this->signed($booking, 'information.wish', $booking->information_valid_until?->isFuture() ? $booking->information_valid_until : now()->addHour(), $version), + ]); + } + + public function wish(Request $request, Booking $booking, SubmitBookingWish $wish): RedirectResponse + { + $request->validate(['terms' => ['accepted']], ['terms.accepted' => 'Bitte bestätigen Sie, dass Sie die Angaben und Bedingungen gelesen haben.']); + $version = (int) $request->query('v'); + $back = $this->signed($booking, 'information.show', now()->addDays(30), $version); + + try { + $outcome = $wish->handle($booking, $version, $request->ip()); + } catch (ReservationException $exception) { + return redirect()->to($back)->with('information.error', $exception->getMessage()); + } + + $booking->refresh(); + + return redirect()->to($back)->with('information.success', match ($outcome) { + SubmitBookingWish::CONFIRMED => $booking->confirmation_sent_at !== null + ? 'Vielen Dank! Wir haben Verfügbarkeit und Preis geprüft – Ihre Buchung ist verbindlich bestätigt. Die Bestätigung mit dem Mietvertrag haben wir Ihnen per E-Mail gesendet.' + : 'Vielen Dank! Ihre Buchung ist verbindlich bestätigt. Die Bestätigung mit dem Mietvertrag erhalten Sie in Kürze per E-Mail.', + SubmitBookingWish::PENDING => 'Vielen Dank – Ihr Buchungswunsch ist eingegangen. Wir prüfen ihn und melden uns in Kürze. Die Buchung ist noch nicht verbindlich; sie wird es erst mit unserer Buchungsbestätigung.', + SubmitBookingWish::UNAVAILABLE => 'Leider ist der Zeitraum inzwischen vergeben. Es ist keine Buchung zustande gekommen. Vielleicht passt ein anderer Termin?', + default => 'Ihr Buchungswunsch liegt uns bereits vor – Sie müssen nichts weiter tun.', + }); + } + + private function signed(Booking $booking, string $name, DateTimeInterface $expiration, int $version): string + { + $parameters = ['booking' => $booking, 'v' => $version]; + + return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters) + ?? URL::temporarySignedRoute($name, $expiration, $parameters); + } +} diff --git a/app/Listeners/LogBookingMail.php b/app/Listeners/LogBookingMail.php index bece040..9241936 100644 --- a/app/Listeners/LogBookingMail.php +++ b/app/Listeners/LogBookingMail.php @@ -25,7 +25,9 @@ public function handle(MessageSent $event): void $recipients = collect($event->message->getTo())->map(fn ($address): string => mb_strtolower($address->getAddress())); $guest = mb_strtolower((string) $booking->guest?->email); - $audience = ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord'); + // A redirected mail carries the original recipients (EnforceMailTestMode); it never reached them. + $redirected = $event->message->getHeaders()->has(EnforceMailTestMode::ORIGINAL_RECIPIENTS_HEADER); + $audience = $redirected || ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord'); BookingMessage::query()->create([ 'booking_id' => $booking->id, diff --git a/app/Livewire/BookingRequest.php b/app/Livewire/BookingRequest.php index 8d8efbf..86d577b 100644 --- a/app/Livewire/BookingRequest.php +++ b/app/Livewire/BookingRequest.php @@ -6,6 +6,7 @@ use App\Actions\RequestMarketingConsent; use App\Availability\AvailabilityChecker; use App\Enums\BookingStatus; +use App\Enums\IntakeKind; use App\Enums\ReferralSource; use App\Exceptions\ReservationException; use App\Models\Booking; @@ -15,6 +16,7 @@ use App\Pricing\PriceQuote; use App\Pricing\QuoteException; use App\Pricing\StayRequest; +use App\Process\ProcessSettings; use App\Tenancy\TenantContext; use Carbon\CarbonImmutable; use Illuminate\Contracts\View\View; @@ -104,6 +106,15 @@ public function property(): Property return Property::findOrFail($this->propertyId); } + /** + * Whether a request on the website reserves the dates (else it is answered with an information, package 7). + */ + #[Computed] + public function reservesDates(): bool + { + return app(ProcessSettings::class)->resolve($this->property, null, IntakeKind::Inquiry)->preReservation(); + } + /** * @return Collection */ diff --git a/app/Mail/BookingWishAnswered.php b/app/Mail/BookingWishAnswered.php new file mode 100644 index 0000000..d4dec46 --- /dev/null +++ b/app/Mail/BookingWishAnswered.php @@ -0,0 +1,36 @@ +outcome === 'pending' ? 'Ihr Buchungswunsch ist eingegangen' : 'Ihr Buchungswunsch').' – '.$this->booking->reference, + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.booking-wish-answered'); + } +} diff --git a/app/Mail/BookingWishNotice.php b/app/Mail/BookingWishNotice.php new file mode 100644 index 0000000..3665dfc --- /dev/null +++ b/app/Mail/BookingWishNotice.php @@ -0,0 +1,36 @@ +outcome) { + 'confirmed' => 'Buchungswunsch automatisch bestätigt', + 'unavailable' => 'Buchungswunsch – Zeitraum inzwischen vergeben', + default => 'Buchungswunsch bitte bestätigen', + }.' '.$this->booking->reference.': '.$this->booking->guestName().', '.$this->booking->arrival->format('d.m.').'–'.$this->booking->departure->format('d.m.Y')); + } + + public function content(): Content + { + return new Content(markdown: 'mail.booking-wish-notice', with: ['caseUrl' => BookingResource::getUrl('view', ['record' => $this->booking])]); + } +} diff --git a/app/Mail/InformationSent.php b/app/Mail/InformationSent.php new file mode 100644 index 0000000..7016d76 --- /dev/null +++ b/app/Mail/InformationSent.php @@ -0,0 +1,35 @@ +booking->reference, + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.information-sent'); + } +} diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 57b6fa7..695e826 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -99,6 +99,17 @@ 'tourist_tax_note', 'portal_cancellation_requested_at', 'export_uid', + 'information_version', + 'information_sent_at', + 'information_valid_until', + 'information', + 'wish_at', + 'wish', + 'arrival_time', + 'completed_at', + 'settled_at', + 'settled_note', + 'settled_by', ])] class Booking extends Model { @@ -187,6 +198,13 @@ protected function casts(): array 'archived_at' => 'immutable_datetime', 'internal_kind' => InternalKind::class, 'portal_cancellation_requested_at' => 'immutable_datetime', + 'information_sent_at' => 'immutable_datetime', + 'information_valid_until' => 'immutable_datetime', + 'information' => 'array', + 'wish_at' => 'immutable_datetime', + 'wish' => 'array', + 'completed_at' => 'immutable_datetime', + 'settled_at' => 'immutable_datetime', ]; } diff --git a/app/Models/BookingMessage.php b/app/Models/BookingMessage.php index 2e05a8b..8e0254b 100644 --- a/app/Models/BookingMessage.php +++ b/app/Models/BookingMessage.php @@ -25,7 +25,7 @@ protected static function booted(): void CaseLog::record($message->booking, 'mail', 'E-Mail '.match ($message->audience) { 'guest' => 'an den Gast', 'landlord' => 'an uns', - default => '(Testbetrieb)', + default => 'im Testbetrieb an die Testadresse (nicht an den Gast)', }.': '.$message->subject, actor: CaseLog::SYSTEM, at: $message->sent_at); } }); diff --git a/app/Models/BookingTask.php b/app/Models/BookingTask.php index 0d20daf..c68e918 100644 --- a/app/Models/BookingTask.php +++ b/app/Models/BookingTask.php @@ -5,6 +5,7 @@ use App\Enums\BookingTaskKind; use App\Enums\BookingTaskStatus; use App\Models\Concerns\BelongsToTenant; +use App\Process\CaseClosure; use App\Process\CaseLog; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Scope; @@ -16,7 +17,7 @@ * Something the landlord has to do about a booking. One task per booking and kind; a finished or * dismissed task is never created again. */ -#[Fillable(['booking_id', 'kind', 'status', 'due_on', 'note', 'completed_by', 'completed_at'])] +#[Fillable(['booking_id', 'kind', 'subject', 'title', 'responsible', 'status', 'due_on', 'note', 'completed_by', 'completed_at'])] class BookingTask extends Model { use BelongsToTenant; @@ -25,12 +26,19 @@ protected static function booted(): void { static::created(function (BookingTask $task): void { if ($task->booking !== null) { - CaseLog::record($task->booking, 'task', 'Aufgabe: '.$task->kind->getLabel()); + CaseLog::record($task->booking, 'task', 'Aufgabe: '.$task->label().($task->responsible ? ' (zuständig: '.$task->responsible.')' : '')); + if ($task->kind->isCommercial() && $task->status === BookingTaskStatus::Open) { + CaseClosure::refresh($task->booking); + } } }); static::updated(function (BookingTask $task): void { if ($task->wasChanged('status') && $task->status !== BookingTaskStatus::Open && $task->booking !== null) { - CaseLog::record($task->booking, 'task', 'Aufgabe '.($task->status === BookingTaskStatus::Done ? 'erledigt' : 'verworfen').': '.$task->kind->getLabel(), actor: $task->completed_by); + CaseLog::record($task->booking, 'task', 'Aufgabe '.($task->status === BookingTaskStatus::Done ? 'erledigt' : 'verworfen').': '.$task->label().($task->wasChanged('note') && filled($task->note) ? ' – '.$task->note : ''), actor: $task->completed_by); + } + // Money tasks decide the commercial closing of the case (package 9). + if ($task->wasChanged('status') && $task->booking !== null && $task->kind->isCommercial()) { + CaseClosure::refresh($task->booking); } }); } @@ -68,8 +76,31 @@ protected function open(Builder $query): Builder return $query->where('status', BookingTaskStatus::Open); } - public function complete(string $by): void + public function complete(string $by, ?string $note = null): void { - $this->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]); + $this->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now(), ...($note !== null && $note !== '' ? ['note' => mb_substr($note, 0, 1000)] : [])]); + } + + /** + * What the task is about in plain words: its own title (services, issues, follow-ups) or the label of its kind. + */ + public function label(): string + { + return filled($this->title) ? (string) $this->title : $this->kind->getLabel(); + } + + /** + * Opens the task of this kind and subject for the case once; a task that was done or dismissed is not opened again. + * + * @param array $attributes + */ + public static function openOnce(Booking $booking, BookingTaskKind $kind, string $subject = '', array $attributes = []): self + { + $task = static::withoutGlobalScope('tenant')->firstOrNew(['booking_id' => $booking->id, 'kind' => $kind, 'subject' => $subject]); + if (! $task->exists) { + $task->forceFill(['tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, ...$attributes])->save(); + } + + return $task; } } diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 6943c53..d751f3c 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -2,11 +2,11 @@ namespace App\Models; +use App\Actions\RecordPayment; use App\Enums\PaymentKind; use App\Enums\PaymentMethod; use App\Models\Concerns\BelongsToTenant; use App\Process\CaseLog; -use App\Support\Money; use Database\Factories\PaymentFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -27,7 +27,7 @@ protected static function booted(): void { static::created(function (Payment $payment): void { if ($payment->booking !== null) { - CaseLog::record($payment->booking, 'payment', ($payment->kind ?? PaymentKind::Guest)->getLabel().': '.Money::format(abs($payment->amount)).($payment->source ? ' ('.$payment->source.')' : ''), data: ['payment_id' => $payment->id]); + CaseLog::record($payment->booking, 'payment', RecordPayment::summary($payment->booking, $payment->kind ?? PaymentKind::Guest, (int) $payment->amount, $payment->paid_on, $payment->source), data: ['payment_id' => $payment->id, 'kind' => ($payment->kind ?? PaymentKind::Guest)->value]); } }); } diff --git a/app/Models/Property.php b/app/Models/Property.php index 0b44e70..e6785b8 100644 --- a/app/Models/Property.php +++ b/app/Models/Property.php @@ -13,6 +13,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; +use Illuminate\Support\Str; /** * A rentable holiday apartment. All money amounts are stored in euro cents. @@ -47,6 +48,8 @@ 'min_stay_absolute', 'is_active', 'process_overrides', + 'stay_tasks', + 'asks_arrival_time', ])] class Property extends Model { @@ -85,6 +88,8 @@ protected function casts(): array 'free_cancellation_days' => 'integer', 'contract_data' => 'array', 'process_overrides' => 'array', + 'stay_tasks' => 'array', + 'asks_arrival_time' => 'boolean', 'min_stay_fill_gaps' => 'boolean', 'min_stay_until_changeover' => 'boolean', 'changeover_weekday' => 'integer', @@ -188,4 +193,31 @@ public function extras(): HasMany { return $this->hasMany(Extra::class)->orderBy('sort_order'); } + + /** + * The stay tasks of this property (package 9): local services and provider jobs such as cleaning, linen or the key + * handover, each with when it is due and for which kinds of stays it applies. No staff planning – a task per case. + * + * @return list}> + */ + public function stayTaskDefinitions(): array + { + $definitions = []; + foreach ((array) ($this->stay_tasks ?? []) as $task) { + $title = trim((string) ($task['title'] ?? '')); + if ($title === '') { + continue; + } + $definitions[] = [ + 'key' => 'stay:'.mb_substr(Str::slug($title), 0, 70), + 'title' => $title, + 'when' => in_array($task['when'] ?? null, ['before_arrival', 'on_arrival', 'after_departure'], true) ? $task['when'] : 'before_arrival', + 'days' => max(0, (int) ($task['days'] ?? 1)), + 'responsible' => filled($task['responsible'] ?? null) ? trim((string) $task['responsible']) : null, + 'applies_to' => array_values(array_filter((array) ($task['applies_to'] ?? ['rental']))) ?: ['rental'], + ]; + } + + return $definitions; + } } diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index 2d4b17b..d487d1f 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -3,7 +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; @@ -18,6 +20,7 @@ use App\Models\Booking; use App\Models\BookingTask; use App\Models\ChannelTask; +use App\Pricing\CaseMoney; use App\Support\Money; use Carbon\CarbonImmutable; @@ -45,7 +48,10 @@ public static function for(Booking $booking): array $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; + // 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). + $over = $closed || $booking->status === BookingStatus::Completed; + $later = fn (ActivityState $state): ActivityState => $over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state; $activities = []; if ($booking->isInternal()) { @@ -67,7 +73,34 @@ public static function for(Booking $booking): array $hasEmail ? null : 'provideContact'); } - if ($inquiry) { + 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) { + $informed => ActivityState::Done, + $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) { + $binding || $booking->wish_at !== null => ActivityState::Done, + $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?“', + default => $booking->processingMode() === ProcessingMode::Automatic ? 'automatisch, wenn alles passt' : 'durch Sie', + }); + } elseif ($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, @@ -125,7 +158,19 @@ public static function for(Booking $booking): array } if ($profile->payments() === Responsibility::Portal) { - $activities[] = new Activity('payment', 'Zahlung des Gastes', ActivityState::External, 'läuft über das 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 { @@ -142,7 +187,7 @@ public static function for(Booking $booking): array }), 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) { + foreach (self::tasks($booking) as $task) { $activities[] = self::task($task); } @@ -152,8 +197,17 @@ public static function for(Booking $booking): array $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) + ? 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'); $activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) { $left => ActivityState::Done, @@ -164,9 +218,64 @@ public static function for(Booking $booking): array $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 + */ + 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 + */ + 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. * @@ -190,12 +299,12 @@ private static function internal(Booking $booking, bool $closed, callable $later $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) { + 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; + return [...$activities, ...self::closing($booking, $closed)]; } /** @@ -206,11 +315,24 @@ 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', + BookingTaskKind::BookingWish => 'decideWish', + BookingTaskKind::ArrivalDetails => 'arrivalDetails', + BookingTaskKind::CancellationRequest => 'end', + 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, + 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->kind->getLabel(), ActivityState::Open, trim(($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->note ? ' · '.$task->note : ''), ' ·'), $action); + return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action); } /** @@ -251,12 +373,17 @@ public static function situation(Booking $booking): string $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::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 => 'abgeschlossen', + 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', diff --git a/app/Process/CaseAutomation.php b/app/Process/CaseAutomation.php index d7e71d7..fa7d3cc 100644 --- a/app/Process/CaseAutomation.php +++ b/app/Process/CaseAutomation.php @@ -48,7 +48,7 @@ public function advance(Booking $booking): array */ private function step(Booking $booking): array { - if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->intake !== IntakeKind::Booking) { + if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0 && $booking->intake !== IntakeKind::Booking) { return $this->autoOffer->handle($booking); } diff --git a/app/Process/CaseClosure.php b/app/Process/CaseClosure.php new file mode 100644 index 0000000..b09b070 --- /dev/null +++ b/app/Process/CaseClosure.php @@ -0,0 +1,142 @@ + + */ + public static function stayBlockers(Booking $booking): Collection + { + return BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() + ->filter(fn (BookingTask $task): bool => $task->kind->blocksStay())->values(); + } + + /** + * What is still open commercially, in plain words (empty: nothing open). Only cases whose stay is closed or that were + * cancelled have a commercial closing; for all others the money is simply still running. + * + * @return list + */ + public static function commercialPoints(Booking $booking): array + { + $points = []; + $tasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() + ->filter(fn (BookingTask $task): bool => $task->kind->isCommercial()); + + if ($booking->status !== BookingStatus::Cancelled) { + $money = CaseMoney::of($booking); + $points = match ($money->collector()) { + Responsibility::Landlord => self::ourMoney($booking, $money), + Responsibility::Portal => self::portalMoney($booking, $money), + default => $booking->total !== null && $booking->total > 0 && $booking->paidAmount() < $booking->total + ? ['Vereinbarte Zahlung noch offen: '.Money::format($booking->total - $booking->paidAmount()).' (ohne Erinnerungen).'] + : [], + }; + } + + foreach ($tasks as $task) { + $points[] = 'Aufgabe offen: '.$task->label().'.'; + } + + return array_values(array_unique($points)); + } + + /** + * Closes or reopens the commercial side after anything that may have changed it (payment, task, stay closed). + * A settlement the landlord made by hand stays unless a commercial task is opened again. + */ + public static function refresh(Booking $booking): void + { + if (! in_array($booking->status, [BookingStatus::Completed, BookingStatus::Cancelled], true)) { + return; + } + + $booking->unsetRelation('payments'); + $points = self::commercialPoints($booking); + $openTasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() + ->contains(fn (BookingTask $task): bool => $task->kind->isCommercial()); + + if ($booking->settled_at === null && $points === []) { + $booking->forceFill(['settled_at' => now(), 'settled_by' => self::AUTOMATIC, 'settled_note' => null])->save(); + CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen – nichts mehr offen'); + } elseif ($booking->settled_at !== null && ($openTasks || ($booking->settled_by === self::AUTOMATIC && $points !== []))) { + $booking->forceFill(['settled_at' => null, 'settled_by' => null, 'settled_note' => null])->save(); + CaseLog::record($booking, 'settled', 'Kaufmännischer Abschluss wieder geöffnet: '.implode(' ', $points)); + } + } + + /** + * 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 + { + 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); + } + } + $points = self::commercialPoints($booking); + $booking->forceFill(['settled_at' => now(), 'settled_by' => $by, 'settled_note' => mb_substr($note, 0, 500)])->save(); + CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen (von Hand)', reason: $note, data: ['open_points' => $points], actor: $by); + } + + /** + * @return list + */ + private static function ourMoney(Booking $booking, CaseMoney $money): array + { + if ($booking->total === null) { + return ['Der Preis ist nicht bekannt.']; + } + + $paid = $booking->paidAmount(); + + return array_values(array_filter([ + $money->openForUs() > 0 ? 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.' : null, + $paid > $booking->total ? 'Überzahlung von '.Money::format($paid - $booking->total).' – Erstattung klären.' : null, + ])); + } + + /** + * @return list + */ + private static function portalMoney(Booking $booking, CaseMoney $money): array + { + $portal = $booking->processChannel()?->name ?? 'dem Portal'; + if ($booking->total === null) { + return ['Der Gesamtpreis laut '.$portal.' fehlt.']; + } + + $payout = $money->payout(); + + return array_values(array_filter([ + $payout['received'] === 0 ? 'Die Auszahlung von '.$portal.' ist noch nicht eingegangen.' : null, + $payout['received'] > 0 && ($payout['outstanding'] ?? 0) > 0 ? 'Von der angekündigten Auszahlung fehlen noch '.Money::format((int) $payout['outstanding']).'.' : null, + $payout['difference'] > 0 ? 'Die Auszahlungsangaben weichen um '.Money::format($payout['difference']).' voneinander ab – ungeklärt.' : null, + ])); + } +} diff --git a/app/Process/CaseRecorder.php b/app/Process/CaseRecorder.php index 52adefb..5715cfd 100644 --- a/app/Process/CaseRecorder.php +++ b/app/Process/CaseRecorder.php @@ -5,6 +5,8 @@ use App\Enums\BookingStatus; use App\Models\Booking; use App\Models\Guest; +use App\Models\Tenant; +use App\Support\Settings; /** * Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake @@ -53,6 +55,10 @@ public static function updated(Booking $booking): void CaseLog::record($booking, 'guest', 'Gast zugeordnet: '.(Guest::query()->find($booking->guest_id)?->full_name ?? '–')); } + if (array_key_exists('information_version', $changes) && $booking->information_version > 0) { + CaseLog::record($booking, 'information', 'Unverbindliche Auskunft Version '.$booking->information_version.' gesendet'.($booking->information_valid_until ? ', Buchung anfragen bis '.$booking->information_valid_until->format('d.m.Y, H:i').' Uhr' : '').' – ohne Reservierung'); + } + if (array_key_exists('offer_version', $changes) && $booking->offer_version > 0) { CaseLog::record($booking, 'offer', 'Angebot Version '.$booking->offer_version.' gesendet'.($booking->hold_expires_at ? ', gültig bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : '')); } elseif (array_key_exists('hold_expires_at', $changes) && $booking->hold_expires_at !== null && in_array($booking->status, BookingStatus::holding(), true) && ! array_key_exists('status', $changes)) { @@ -78,9 +84,10 @@ public static function updated(Booking $booking): void 'arrival_info_sent_at' => 'Anreise-Informationen gesendet', 'review_requested_at' => 'Gast um eine Bewertung gebeten', ]; + $mailed = ['contact_requested_at', 'confirmation_sent_at', 'arrival_info_sent_at', 'review_requested_at']; foreach ($facts as $column => $summary) { if (array_key_exists($column, $changes) && $booking->{$column} !== null) { - CaseLog::record($booking, 'fact', $summary); + CaseLog::record($booking, 'fact', in_array($column, $mailed, true) ? self::mailFact($booking, $summary) : $summary); } } @@ -93,17 +100,29 @@ public static function updated(Booking $booking): void } } + /** + * A fact that says a mail went to the guest – in test operation it went to the test address only, and the history says so. + */ + private static function mailFact(Booking $booking, string $summary): string + { + $redirect = Settings::mailRedirectFor(Tenant::query()->find($booking->tenant_id)); + + return $redirect === null ? $summary : $summary.' – Testbetrieb: nur an die Testadresse, nicht an den Gast'; + } + private static function statusSummary(Booking $booking, mixed $from): string { $from = $from instanceof BookingStatus ? $from : BookingStatus::tryFrom((string) $from); return match ($booking->status) { - BookingStatus::Confirmed => $booking->wasChanged('accepted_at') && $booking->accepted_at !== null + BookingStatus::Confirmed => ($booking->acceptance['via'] ?? null) === 'booking_wish' && $booking->wasChanged('acceptance') + ? 'Buchungswunsch bestätigt – Buchung verbindlich' + : ($booking->wasChanged('accepted_at') && $booking->accepted_at !== null ? 'Angebot vom Gast angenommen – Buchung verbindlich' - : ($booking->caseType()->isExternallyBinding() ? 'Beim Portal verbindlich gebucht – übernommen' : 'Buchung verbindlich bestätigt'), + : ($booking->caseType()->isExternallyBinding() ? 'Beim Portal verbindlich gebucht – übernommen' : 'Buchung verbindlich bestätigt')), BookingStatus::DepositPaid => 'Anzahlung eingegangen', BookingStatus::Paid => 'Vollständig bezahlt', - BookingStatus::Completed => 'Aufenthalt abgeschlossen', + BookingStatus::Completed => 'Aufenthalt abgeschlossen'.($booking->settled_at === null ? ' – kaufmännische Punkte laufen weiter' : ''), BookingStatus::Declined => 'Ohne Buchung beendet (abgelehnt'.($booking->declined_by ? ' durch '.($booking->declined_by === 'guest' ? 'den Gast' : 'uns') : '').')', BookingStatus::Expired => 'Ohne Buchung beendet (Frist abgelaufen)', BookingStatus::Cancelled => 'Storniert', diff --git a/app/Process/WorkList.php b/app/Process/WorkList.php index 61e2f5a..143c5f4 100644 --- a/app/Process/WorkList.php +++ b/app/Process/WorkList.php @@ -31,8 +31,9 @@ public static function items(): array $cases = Booking::query() ->with(['guest', 'property', 'payments', 'importChannel', 'originChannel']) ->whereNull('archived_at') - ->whereNotIn('status', [BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed]) - ->where(fn ($query) => $query->whereNot('status', BookingStatus::Cancelled)->orWhereHas('tasks', fn ($tasks) => $tasks->where('status', 'open'))) + ->whereNotIn('status', [BookingStatus::Declined, BookingStatus::Expired]) + // Closed stays and cancellations only with open tasks: follow-ups (money, damage) stay visible (package 9). + ->where(fn ($query) => $query->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Completed])->orWhereHas('tasks', fn ($tasks) => $tasks->where('status', 'open'))) ->get(); foreach ($cases as $case) { $next = CaseActivities::next($case); diff --git a/database/migrations/2026_11_05_090000_create_information_wish_and_stay_closure.php b/database/migrations/2026_11_05_090000_create_information_wish_and_stay_closure.php new file mode 100644 index 0000000..0d3ebfa --- /dev/null +++ b/database/migrations/2026_11_05_090000_create_information_wish_and_stay_closure.php @@ -0,0 +1,68 @@ +unsignedSmallInteger('information_version')->default(0)->after('offer_version'); + $table->dateTime('information_sent_at')->nullable()->after('information_version'); + $table->dateTime('information_valid_until')->nullable()->after('information_sent_at'); + $table->json('information')->nullable()->after('information_valid_until'); + $table->dateTime('wish_at')->nullable()->after('information'); + $table->json('wish')->nullable()->after('wish_at'); + $table->string('arrival_time', 40)->nullable()->after('departure'); + $table->dateTime('completed_at')->nullable(); + $table->dateTime('settled_at')->nullable(); + $table->string('settled_note', 500)->nullable(); + $table->string('settled_by')->nullable(); + }); + + Schema::table('properties', function (Blueprint $table) { + $table->json('stay_tasks')->nullable(); + $table->boolean('asks_arrival_time')->default(false); + }); + + Schema::table('booking_tasks', function (Blueprint $table) { + $table->string('subject', 80)->default('')->after('kind'); + $table->string('title')->nullable()->after('subject'); + $table->string('responsible')->nullable()->after('title'); + }); + + // The new unique key is added before the old one is dropped: MariaDB needs an index on booking_id for its foreign key. + Schema::table('booking_tasks', function (Blueprint $table) { + $table->unique(['booking_id', 'kind', 'subject']); + }); + Schema::table('booking_tasks', function (Blueprint $table) { + $table->dropUnique(['booking_id', 'kind']); + }); + } + + public function down(): void + { + Schema::table('booking_tasks', function (Blueprint $table) { + $table->unique(['booking_id', 'kind']); + }); + Schema::table('booking_tasks', function (Blueprint $table) { + $table->dropUnique(['booking_id', 'kind', 'subject']); + $table->dropColumn(['subject', 'title', 'responsible']); + }); + + Schema::table('properties', function (Blueprint $table) { + $table->dropColumn(['stay_tasks', 'asks_arrival_time']); + }); + + Schema::table('bookings', function (Blueprint $table) { + $table->dropColumn(['information_version', 'information_sent_at', 'information_valid_until', 'information', 'wish_at', 'wish', 'arrival_time', 'completed_at', 'settled_at', 'settled_note', 'settled_by']); + }); + } +}; diff --git a/resources/views/information.blade.php b/resources/views/information.blade.php new file mode 100644 index 0000000..605bd4f --- /dev/null +++ b/resources/views/information.blade.php @@ -0,0 +1,84 @@ +@php($owner = \App\Documents\OfferTerms::owner($booking)) +@php($money = fn (int $cents): string => \App\Support\Money::format($cents)) +@extends('theme::layouts.app', ['title' => 'Unverbindliche Auskunft']) + +@push('head') + +@endpush + +@section('content') +
+

Unverbindliche Auskunft · Anfrage {{ $booking->reference }}

+

{{ $booking->property->name }}

+

für {{ $booking->guestName() }}

+ + @if (session('information.success')) +
{{ session('information.success') }}
+ @elseif (session('information.error') || $problem) + + @endif + +
+

Dies ist noch keine Buchung und keine Reservierung.

+

Preis und Verfügbarkeit gelten für den Stand vom {{ $booking->information_sent_at?->format('d.m.Y, H:i') }} Uhr. Der Zeitraum kann in der Zwischenzeit anderweitig vergeben werden. Wenn Sie die Buchung anfragen, prüfen wir beides erneut; verbindlich wird sie erst mit unserer Buchungsbestätigung.

+
+ +
+

Ihr Aufenthalt

+
+
Anreise
{{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif
+
Abreise
{{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif
+
Nächte
{{ $booking->nights() }}
+
Personen
{{ $booking->guests }}
+
Anfragen bis
{{ $booking->information_valid_until?->format('d.m.Y, H:i') }} Uhr
+
+ +

Preis (Stand der Auskunft)

+ + @foreach ($booking->quote['lines'] ?? [] as $line) + + @endforeach + +
{{ $line['label'] }}{{ $money($line['amount']) }}
Gesamtpreis{{ $money((int) $booking->total) }}
+

Anzahlung {{ $money((int) $booking->deposit) }} nach der Buchungsbestätigung, Restbetrag {{ $money((int) $booking->total - (int) $booking->deposit) }} bis {{ $booking->balance_due_on?->format('d.m.Y') }}. Die Kurtaxe ist nicht enthalten und wird vor Ort entrichtet.

+ + @if ($booking->offer_message) +

{{ $booking->offer_message }}

+ @endif + + @php($contractDocument = \App\Documents\OfferTerms::document($booking)) + @if ($contractDocument) +

Mietbedingungen

+
{!! $contractDocument['body'] !!}
+ @if ($contractDocument['annex']) +

{{ $contractDocument['annex_title'] ?: 'Anlage' }}

+
{!! $contractDocument['annex'] !!}
+ @endif + @else +

Bedingungen

+
{{ $booking->offerHtml('contract.terms') }}
+ @if ($booking->offerText('stay.cancellation')) +

Rücktritt / Stornierung

+
{{ $booking->offerHtml('stay.cancellation') }}
+ @endif + @endif +
+ + @if ($canAsk && ! session('information.success')) +
+
+ @csrf + + @error('terms')@enderror +

Mit „Buchung anfragen“ senden Sie uns Ihren Buchungswunsch. Wir prüfen Verfügbarkeit und Preis erneut. Der Vertrag kommt erst mit unserer Buchungsbestätigung zustande, die Sie per E-Mail erhalten.

+ +
+
+ @endif + +

Fragen? {{ $owner['name'] ?? '' }} · {{ $owner['phone'] ?? '' }} · {{ $owner['email'] ?? '' }}

+
+@endsection diff --git a/resources/views/livewire/booking-request.blade.php b/resources/views/livewire/booking-request.blade.php index 55a09a8..569c451 100644 --- a/resources/views/livewire/booking-request.blade.php +++ b/resources/views/livewire/booking-request.blade.php @@ -5,7 +5,7 @@

Ihre Anfrage {{ $booking->reference }} ist eingegangen. Wir haben den Zeitraum {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }} - @if ($booking->isHoldActive())bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr für Sie vorgemerkt.@elseif ($booking->status === \App\Enums\BookingStatus::OfferSent)bereits geprüft – unser Angebot ist unterwegs zu Ihnen.@else– eine Reservierung ist damit noch nicht verbunden.@endif + @if ($booking->isHoldActive())bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr für Sie vorgemerkt.@elseif ($booking->status === \App\Enums\BookingStatus::OfferSent)bereits geprüft – unser Angebot ist unterwegs zu Ihnen.@elseif ($booking->information_version > 0)geprüft – unsere unverbindliche Auskunft ist unterwegs zu Ihnen. Reserviert ist der Zeitraum damit noch nicht.@else– eine Reservierung ist damit noch nicht verbunden.@endif

Eine Bestätigung mit allen Details haben wir an {{ $booking->guest->email }} gesendet.

@@ -219,7 +219,11 @@ class="mt-5 w-full rounded-xl bg-accent px-4 py-3 font-semibold text-accent-ink Unverbindlich anfragen Wird gesendet … -

Kostenlos und unverbindlich. Wir halten den Termin für Sie frei und senden Ihnen ein Angebot per E-Mail – verbindlich wird die Buchung erst, wenn Sie es annehmen.

+ @if ($this->reservesDates) +

Kostenlos und unverbindlich. Wir halten den Termin für Sie frei und senden Ihnen ein Angebot per E-Mail – verbindlich wird die Buchung erst, wenn Sie es annehmen.

+ @else +

Kostenlos und unverbindlich. Sie erhalten eine Auskunft zu Preis und Verfügbarkeit per E-Mail und können daraus die Buchung anfragen – verbindlich wird sie erst mit unserer Bestätigung.

+ @endif diff --git a/resources/views/mail/booking-confirmed.blade.php b/resources/views/mail/booking-confirmed.blade.php index b9610d0..fec327f 100644 --- a/resources/views/mail/booking-confirmed.blade.php +++ b/resources/views/mail/booking-confirmed.blade.php @@ -3,7 +3,9 @@ Guten Tag {{ $booking->guest->full_name }}, -@if ($booking->accepted_at) +@if ($booking->accepted_at && ($booking->acceptance['via'] ?? null) === 'booking_wish') +vielen Dank für Ihren Buchungswunsch vom {{ $booking->accepted_at->format('d.m.Y') }}. Wir haben Verfügbarkeit und Preis erneut geprüft und bestätigen Ihre Buchung der **{{ $booking->property->name }}** hiermit verbindlich. +@elseif ($booking->accepted_at) vielen Dank – Sie haben unser Angebot am {{ $booking->accepted_at->format('d.m.Y') }} um {{ $booking->accepted_at->format('H:i') }} Uhr angenommen. Damit ist Ihre Buchung der **{{ $booking->property->name }}** verbindlich. @else wir freuen uns, Ihre Buchung der **{{ $booking->property->name }}** verbindlich zu bestätigen. diff --git a/resources/views/mail/booking-wish-answered.blade.php b/resources/views/mail/booking-wish-answered.blade.php new file mode 100644 index 0000000..ea14f88 --- /dev/null +++ b/resources/views/mail/booking-wish-answered.blade.php @@ -0,0 +1,32 @@ + +@if ($outcome === 'pending') +# Ihr Buchungswunsch ist eingegangen + +Guten Tag {{ $booking->guest->full_name }}, + +vielen Dank – Ihr Buchungswunsch für die **{{ $booking->property->name }}** vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} ist bei uns eingegangen. + +Wir prüfen ihn und melden uns in Kürze. **Die Buchung ist noch nicht verbindlich**; sie wird es erst mit unserer Buchungsbestätigung, die Sie mit dem Mietvertrag per E-Mail erhalten. +@else +# Ihr Buchungswunsch {{ $booking->reference }} + +Guten Tag {{ $booking->guest->full_name }}, + +vielen Dank für Ihren Buchungswunsch für die **{{ $booking->property->name }}**. +@if ($outcome === 'unavailable') +Leider ist der Zeitraum vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} inzwischen vergeben. +@else +Leider können wir Ihnen den Zeitraum vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} nicht bestätigen. +@endif +Es ist keine Buchung zustande gekommen, und es entstehen Ihnen keine Kosten. + +Vielleicht passt ein anderer Termin? Die freien Zeiträume finden Sie jederzeit in unserem Belegungskalender. + + +Freie Termine ansehen + +@endif + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/mail/booking-wish-notice.blade.php b/resources/views/mail/booking-wish-notice.blade.php new file mode 100644 index 0000000..efadd06 --- /dev/null +++ b/resources/views/mail/booking-wish-notice.blade.php @@ -0,0 +1,21 @@ + +# Buchungswunsch {{ $booking->reference }} + +{{ $booking->guestName() }} hat aus der Auskunft die Buchung angefragt: {{ $booking->property->name }}, {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}, {{ $booking->guests }} Personen. + +@if ($outcome === 'confirmed') +Alles war in Ordnung (Zeitraum frei, Kalender aktuell, Preis unverändert). Die Buchung ist **automatisch verbindlich bestätigt**; der Gast hat die Bestätigung mit dem Mietvertrag erhalten. +@elseif ($outcome === 'unavailable') +Der Zeitraum war inzwischen vergeben. **Es ist keine Buchung entstanden**; der Gast hat eine freundliche Absage erhalten. +@else +**Bitte bestätigen oder absagen.** Bis dahin ist nichts verbindlich und der Zeitraum nicht reserviert. + +@foreach ((array) ($booking->wish['findings'] ?? []) as $finding) +- {{ $finding }} +@endforeach +@endif + + +Vorgang öffnen + + diff --git a/resources/views/mail/information-sent.blade.php b/resources/views/mail/information-sent.blade.php new file mode 100644 index 0000000..2b38586 --- /dev/null +++ b/resources/views/mail/information-sent.blade.php @@ -0,0 +1,33 @@ + +# Unverbindliche Auskunft für die {{ $booking->property->name }} + +Guten Tag {{ $booking->guest->full_name }}, + +vielen Dank für Ihre Anfrage. Hier unsere **unverbindliche Auskunft** – noch **keine Buchung und keine Reservierung**: + +**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}
+**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}
+**Personen:** {{ $booking->guests }}
+**Anfragenummer:** {{ $booking->reference }} + +@include('mail.partials.quote') + +@if ($booking->offer_message) +{{ $booking->offer_message }} +@endif + +Preis und Verfügbarkeit gelten für den Stand vom **{{ $booking->information_sent_at?->format('d.m.Y, H:i') }} Uhr**. Der Zeitraum ist für Sie nicht reserviert und kann in der Zwischenzeit anderweitig vergeben werden. + +Möchten Sie buchen? Dann fragen Sie die Buchung bis **{{ $booking->information_valid_until?->format('d.m.Y, H:i') }} Uhr** an: + + +Auskunft ansehen und Buchung anfragen + + +Wir prüfen dann Verfügbarkeit und Preis erneut. **Verbindlich wird die Buchung erst mit unserer Buchungsbestätigung**; mit ihr erhalten Sie den Mietvertrag. + +Bei Fragen antworten Sie einfach auf diese E-Mail oder rufen Sie uns an: {{ config('fewo.owner.phone') }} + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/mail/reservation-expired.blade.php b/resources/views/mail/reservation-expired.blade.php index d034781..bd46a7e 100644 --- a/resources/views/mail/reservation-expired.blade.php +++ b/resources/views/mail/reservation-expired.blade.php @@ -1,9 +1,17 @@ +@if ($booking->information_version > 0 && $booking->offer_version === 0) +# Auskunft abgelaufen + +Zur unverbindlichen Auskunft **{{ $booking->reference }}** an {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) kam kein Buchungswunsch. Der Zeitraum war nicht reserviert; die Anfrage ist ohne Buchung beendet. + +Sie können weiterhin eine neue Auskunft senden. +@else # {{ $booking->offer_version > 0 ? 'Angebot abgelaufen' : 'Vormerkung abgelaufen' }} Die Anfrage **{{ $booking->reference }}** von {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) {{ $booking->offer_version > 0 ? 'wurde vom Gast nicht rechtzeitig angenommen' : 'wurde nicht rechtzeitig beantwortet' }}. Der Zeitraum ist im Kalender wieder frei. Sie können weiterhin ein (neues) Angebot senden, sofern der Zeitraum noch frei ist. +@endif Anfrage öffnen diff --git a/resources/views/mail/reservation-received.blade.php b/resources/views/mail/reservation-received.blade.php index 5d3f8e2..2b30e91 100644 --- a/resources/views/mail/reservation-received.blade.php +++ b/resources/views/mail/reservation-received.blade.php @@ -14,7 +14,11 @@ @include('mail.partials.quote') +@if ($booking->hold_expires_at === null && ! $booking->process()->preReservation()) +Wir prüfen Ihre Anfrage und senden Ihnen in Kürze eine **unverbindliche Auskunft** per E-Mail. Daraus können Sie die Buchung anfragen; verbindlich wird sie erst mit unserer Buchungsbestätigung. +@else Wir prüfen Ihre Anfrage und senden Ihnen in Kürze **unser Angebot** per E-Mail. Verbindlich wird die Buchung erst, wenn Sie dieses Angebot annehmen. +@endif @if ($booking->message) **Ihre Nachricht:**
diff --git a/routes/web.php b/routes/web.php index f633e4e..9b012cd 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,6 +2,7 @@ use App\Http\Controllers\ChangeController; use App\Http\Controllers\ChannelController; +use App\Http\Controllers\InformationController; use App\Http\Controllers\MarketingConsentController; use App\Http\Controllers\OfferController; use App\Http\Controllers\PageController; @@ -27,6 +28,9 @@ Route::get('/angebot/aenderung/{change}', [ChangeController::class, 'show'])->name('changes.show')->middleware('throttle:30,1'); Route::post('/angebot/aenderung/{change}/annehmen', [ChangeController::class, 'accept'])->name('changes.accept')->middleware('throttle:10,1'); Route::post('/angebot/aenderung/{change}/ablehnen', [ChangeController::class, 'decline'])->name('changes.decline')->middleware('throttle:10,1'); + // Information "unter Vorbehalt" of a request without a hold and the guest's booking wish (package 7). + Route::get('/angebot/auskunft/{booking}', [InformationController::class, 'show'])->name('information.show')->middleware('throttle:30,1'); + Route::post('/angebot/auskunft/{booking}/buchung-anfragen', [InformationController::class, 'wish'])->name('information.wish')->middleware('throttle:10,1'); }); Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); diff --git a/tests/Feature/AutoOfferTest.php b/tests/Feature/AutoOfferTest.php index 42e63b1..a055ede 100644 --- a/tests/Feature/AutoOfferTest.php +++ b/tests/Feature/AutoOfferTest.php @@ -97,14 +97,16 @@ public function test_without_pre_reservation_a_request_blocks_nothing(): void Mail::assertSent(ReservationReceived::class, fn (ReservationReceived $mail): bool => str_contains($mail->render(), 'nicht reserviert') && ! str_contains($mail->render(), 'vorgemerkt')); } - public function test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why(): void + public function test_automatic_mode_without_pre_reservation_waits_for_the_released_information_text_and_says_why(): void { Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]); $booking = $this->request(); + // Package 7: a request without a hold is answered with an information; its texts start as a working draft. $this->assertSame(BookingStatus::Reserved, $booking->status); - $this->assertStringContainsString('vorreservierung', mb_strtolower($booking->internal_notes)); + $this->assertSame(0, $booking->information_version); + $this->assertStringContainsString('auskunft unter vorbehalt', mb_strtolower($booking->internal_notes)); Mail::assertNotSent(OfferMade::class); Mail::assertSent(ReservationReceived::class, 1); Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->blockers !== []); diff --git a/tests/Feature/CaseIntakeTest.php b/tests/Feature/CaseIntakeTest.php index c7ffcc7..5ae37ee 100644 --- a/tests/Feature/CaseIntakeTest.php +++ b/tests/Feature/CaseIntakeTest.php @@ -107,7 +107,7 @@ public function test_a_booking_mail_becomes_a_case_and_the_later_calendar_entry_ // The portal collects the money: no payment tasks of our own; nothing went to the guest. $this->assertFalse($case->fresh()->wantsPaymentTasks()); - $this->assertSame('läuft über das Portal', collect(CaseActivities::for($case->fresh()))->firstWhere('key', 'payment')?->detail); + $this->assertSame('zieht das Portal ein', collect(CaseActivities::for($case->fresh()))->firstWhere('key', 'payment')?->detail); Mail::assertNotSent(BookingDocumentation::class); Mail::assertNotSent(BookingConfirmed::class); } diff --git a/tests/Feature/EndToEndStayAcceptanceTest.php b/tests/Feature/EndToEndStayAcceptanceTest.php new file mode 100644 index 0000000..0cf5cf9 --- /dev/null +++ b/tests/Feature/EndToEndStayAcceptanceTest.php @@ -0,0 +1,624 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + app(TenantContext::class)->set($this->property->tenant); + $this->manualPortal = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'booking_model' => 'inquiry', 'connector' => 'ical', 'import_enabled' => false, 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']); + Mail::fake(); + Storage::fake('local'); + Http::fake(fn () => Http::response('', 500)); + $this->withoutVite(); + $this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple])); + } + + /** T16 – hold 0: information "unter Vorbehalt", nothing reserved, the guest asks for the booking, the landlord confirms. */ + public function test_t16_information_without_hold_and_booking_wish(): void + { + Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]); + $booking = $this->request(); + + $this->assertNull($booking->hold_expires_at); + $this->assertSame(0, Booking::query()->occupying()->count(), 'the calendar stays free'); + $this->assertSame('Unverbindliche Auskunft prüfen und senden', WorkList::items()[0]['title']); + $this->assertSame(DocumentKind::Information, DocumentKind::forCase($booking)); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true]) + ->assertNotified('Auskunft gesendet'); + $booking->refresh(); + + $this->assertSame([BookingStatus::Reserved, 1, 0, null], [$booking->status, $booking->information_version, $booking->offer_version, $booking->hold_expires_at]); + $this->assertSame(0, Booking::query()->occupying()->count(), 'still nothing reserved'); + Mail::assertNotSent(OfferMade::class); + Mail::assertSent(InformationSent::class, fn (InformationSent $mail): bool => str_contains($mail->render(), 'keine Buchung und keine Reservierung') && ! str_contains($mail->render(), 'annehmen')); + + $show = URL::temporarySignedRoute('information.show', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]); + $this->get($show)->assertOk()->assertSee('Dies ist noch keine Buchung und keine Reservierung.')->assertSee('Buchung anfragen')->assertDontSee('Angebot annehmen'); + + $wish = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]); + $this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'noch nicht verbindlich')); + $this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'bereits vor')); + + $booking->refresh(); + $this->assertSame(BookingStatus::Reserved, $booking->status, 'a wish is no booking'); + $this->assertSame(0, Booking::query()->occupying()->count()); + $this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->count(), 'one task however often the guest clicks'); + Mail::assertSent(BookingWishAnswered::class, 1); + $this->assertSame('Buchungswunsch bestätigen?', WorkList::items()[0]['title']); + $this->assertSame('decideWish', CaseActivities::next($booking)?->action); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('decideWish', ['decision' => 'confirm']) + ->assertNotified('Buchung bestätigt'); + $booking->refresh(); + + $this->assertSame(BookingStatus::Confirmed, $booking->status); + $this->assertSame('booking_wish', $booking->acceptance['via']); + $this->assertSame('Ingrid', $booking->acceptance['confirmed_by']); + $this->assertNotNull($booking->contract_path); + Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => str_contains($mail->render(), 'Buchungswunsch')); + $this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->exists(), 'the manual portal is blocked now'); + $this->assertStringContainsString('Buchungswunsch', $booking->events()->where('type', 'wish')->reorder()->orderByDesc('id')->value('summary')); + } + + /** T16 (old link, expiry): a replaced information no longer works; an unanswered one ends without booking. */ + public function test_t16_old_links_and_unanswered_information(): void + { + Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]); + $booking = $this->request(); + $this->sendInformation($booking); + $this->sendInformation($booking->fresh()); + $booking->refresh(); + $this->assertSame(2, $booking->information_version); + + $old = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]); + $this->post($old, ['terms' => '1'])->assertSessionHas('information.error', fn (string $text): bool => str_contains($text, 'nicht mehr aktuell')); + $this->assertNull($booking->fresh()->wish_at); + + $this->travelTo($booking->information_valid_until->addMinute()); + app(ExpireReservations::class)->handle(); + $this->assertSame(BookingStatus::Expired, $booking->fresh()->status); + $this->flushSession(); + $current = URL::temporarySignedRoute('information.show', now()->addDay(), ['booking' => $booking, 'v' => 2]); + $this->get($current)->assertOk()->assertSee('abgeschlossen'); + } + + /** T17 – the dates were given away between information and wish: no booking, a friendly answer, a note for the landlord. */ + public function test_t17_booking_wish_after_the_dates_were_given_away(): void + { + Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]); + $first = $this->request(); + $this->sendInformation($first); + $second = $this->request('zweite@example.org'); + $this->sendInformation($second); + + // Meanwhile the first guest books and a portal reports an occupation that touches the second guest's stay. + $this->wish($first->fresh()); + Livewire::test(ViewBooking::class, ['record' => $first->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']); + $this->assertSame(BookingStatus::Confirmed, $first->fresh()->status); + + $this->post(URL::temporarySignedRoute('information.wish', $second->fresh()->information_valid_until, ['booking' => $second, 'v' => 1]), ['terms' => '1']) + ->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'inzwischen vergeben')); + + $second->refresh(); + $this->assertSame(BookingStatus::Declined, $second->status); + $this->assertSame(1, Booking::query()->occupying()->count(), 'no double booking'); + Mail::assertSent(BookingWishAnswered::class, fn (BookingWishAnswered $mail): bool => $mail->outcome === 'unavailable' && $mail->booking->is($second)); + Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'unavailable'); + $this->assertTrue(InboxMessage::query()->where('subject', 'like', '%Zeitraum inzwischen vergeben%')->exists()); + + // A portal occupation imported meanwhile has the same effect. + $third = $this->request('dritte@example.org', '2026-11-21', '2026-11-24'); + $this->sendInformation($third); + BlockedPeriod::factory()->for($this->property)->create(['source' => 'channel', 'channel_id' => $this->manualPortal->id, 'starts_on' => '2026-11-22', 'ends_on' => '2026-11-26']); + $this->wish($third->fresh()); + $this->assertSame(BookingStatus::Declined, $third->fresh()->status); + } + + /** T17 – price changed, calendar not current: even in automatic mode the wish waits for the landlord, with the reasons. */ + public function test_t17_changed_price_and_stale_calendar_need_the_landlord(): void + { + $this->automaticWithoutHold(); + $booking = $this->request(); + $this->assertSame(1, $booking->fresh()->information_version, 'sent automatically'); + + Season::query()->whereDate('starts_on', '<=', '2026-11-07')->whereDate('ends_on', '>', '2026-11-07')->update(['nightly_rate' => 9900]); + Channel::factory()->for($this->property)->create(['name' => 'Kalenderportal', 'connector' => 'ical', 'import_enabled' => true, 'status' => 'active', 'settings' => ['import_url' => 'https://portal.example/cal.ics'], 'last_success_at' => now()->subDays(2)]); + $this->wish($booking->fresh()); + + $booking->refresh(); + $this->assertSame(BookingStatus::Reserved, $booking->status); + $findings = implode(' ', $booking->wish['findings']); + $this->assertStringContainsString('Der Preis hat sich seit der Auskunft geändert', $findings); + $this->assertStringContainsString('Kalenderstand von Kalenderportal', $findings); + $task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->sole(); + $this->assertStringContainsString('Preis', (string) $task->note); + + // The landlord honours the price of the information (the guest was told it). + $told = $booking->total; + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']); + $this->assertSame([BookingStatus::Confirmed, $told], [$booking->fresh()->status, $booking->fresh()->total]); + } + + /** T18 – automatic and manual handling of a wish; two guests for the same dates never both get the booking. */ + public function test_t18_automatic_wish_is_confirmed_at_once_and_the_competitor_gets_a_refusal(): void + { + $this->automaticWithoutHold(); + $first = $this->request(); + $second = $this->request('zweite@example.org'); + Mail::assertSent(InformationSent::class, 2); + + $this->wish($first->fresh()); + $first->refresh(); + $this->assertSame(BookingStatus::Confirmed, $first->status, 'confirmed automatically after the new check'); + $this->assertSame('automatisch nach erneuter Prüfung', $first->acceptance['confirmed_by']); + Mail::assertSent(BookingConfirmed::class, 1); + Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'confirmed'); + + $this->wish($second->fresh()); + $this->assertSame(BookingStatus::Declined, $second->fresh()->status); + $this->assertSame(1, Booking::query()->occupying()->count()); + Mail::assertSent(BookingConfirmed::class, 1); + } + + /** T19 – A1 from the request to the closed stay: offer, payments, preparation, services, arrival, departure, closing. */ + public function test_t19_complete_a1_process_until_the_stay_is_closed(): void + { + $this->property->update(['asks_arrival_time' => true, 'stay_tasks' => [ + ['title' => 'Schlüsselübergabe', 'when' => 'on_arrival', 'responsible' => 'Nachbarin Frau Kruse', 'applies_to' => ['rental']], + ['title' => 'Endreinigung', 'when' => 'after_departure', 'responsible' => 'Reinigung Müller', 'applies_to' => ['rental', 'private']], + ]]); + $booking = $this->request(); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('sendOffer')->arguments([]), ['acknowledged' => true]); + $booking->refresh(); + $this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1']); + $booking->refresh(); + app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today()); + app(RecordPayment::class)->handle($booking->fresh(), (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today()); + $this->assertSame(BookingStatus::Paid, $booking->fresh()->status); + + // Five days before arrival: the arrival time is missing, the stay tasks are planned. + $this->travelTo(CarbonImmutable::parse('2026-11-02 08:00')); + app(SendBookingReminders::class)->handle(); + app(SendBookingReminders::class)->handle(); + $tasks = BookingTask::query()->where('booking_id', $booking->id)->get(); + $this->assertSame(1, $tasks->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'once, however often the run repeats'); + $this->assertSame(['Endreinigung', 'Schlüsselübergabe'], $tasks->where('kind', BookingTaskKind::Service)->pluck('title')->sort()->values()->all()); + $this->assertSame('Anreisedaten beim Gast erfragen', CaseActivities::next($booking->fresh())?->label); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('arrivalDetails', ['arrival_time' => 'gegen 16 Uhr', 'phone' => '0171 1234567', 'email' => 'gesa@example.org']); + $this->assertSame(BookingTaskStatus::Done, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->value('status')); + + $this->travelTo(CarbonImmutable::parse('2026-11-04 08:00')); + app(SendBookingReminders::class)->handle(); + Mail::assertSent(ArrivalInformation::class, 1); + + // Arrival: the key handover is done. + $this->travelTo(CarbonImmutable::parse('2026-11-07 15:00')); + $handover = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Schlüsselübergabe')->sole(); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $handover->id, 'outcome' => 'done', 'note' => 'Schlüssel übergeben']); + + // After the departure the cleaning is still open: the stay waits for it. + $this->travelTo(CarbonImmutable::parse('2026-11-11 08:00')); + app(SendBookingReminders::class)->handle(); + $this->assertSame(BookingStatus::Paid, $booking->fresh()->status); + $this->assertStringContainsString('Endreinigung', (string) collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'closure')?->detail); + + $cleaning = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Endreinigung')->sole(); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $cleaning->id, 'outcome' => 'handed_over', 'handed_to' => 'Reinigung Müller', 'note' => 'erledigt laut Rückmeldung']); + app(SendBookingReminders::class)->handle(); + + $booking->refresh(); + $this->assertSame(BookingStatus::Completed, $booking->status); + $this->assertNotNull($booking->settled_at, 'fully paid: nothing open commercially'); + $this->travelTo(CarbonImmutable::parse('2026-11-14 08:00')); + app(RequestReviews::class)->handle(); + $activities = collect(CaseActivities::for($booking)); + $this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'closure')->state); + $this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'settlement')->state); + $this->assertStringContainsString('Übergeben an Reinigung Müller', (string) $activities->firstWhere('label', 'Endreinigung')?->detail); + Mail::assertSent(ReviewRequest::class, 1); + $this->assertSame([], collect(WorkList::items())->where('url', 'like', '%bookings/'.$booking->id.'%')->all()); + } + + /** T20 – A4: portal payment, stay, later payout; "paid according to the portal" never reads as money received. */ + public function test_t20_complete_a4_process_with_portal_payment_and_later_payout(): void + { + $fewo = $this->fewo(['process_overrides' => ['booking' => ['payments' => 'portal', 'guest_messages' => 'portal']]]); + $this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-A4FLOW"); + $booking = Booking::query()->sole(); + $this->assertSame(CaseType::A4, $booking->case_type); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22', + 'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69']], + 'paid' => [['amount' => '979.51', 'paid_on' => '2026-10-21']]]); + $booking->refresh(); + + $this->assertSame(BookingStatus::Confirmed, $booking->status, 'paid to the portal is not "Anzahlung erhalten" / "Bezahlt"'); + $this->assertSame(0, CaseMoney::of($booking)->receivedOnAccount()); + $history = $booking->events()->pluck('summary')->implode(' | '); + $this->assertStringContainsString('Laut FeWo-direkt hat der Gast '.Money::format(97951).' an das Portal gezahlt – noch kein Geld bei uns', $history); + $this->assertStringNotContainsString('Anzahlung eingegangen', $history); + $activities = collect(CaseActivities::for($booking)); + $this->assertSame(ActivityState::External, $activities->firstWhere('key', 'arrival_info')->state); + $this->assertStringContainsString('(angekündigt)', $activities->firstWhere('key', 'arrival_info')->detail); + $this->assertSame(ActivityState::Waiting, $activities->firstWhere('key', 'payout')->state); + + $this->travelTo(CarbonImmutable::parse('2026-12-04 08:00')); + app(SendBookingReminders::class)->handle(); + Mail::assertNotSent(ArrivalInformation::class); + $this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])->count()); + + $this->travelTo(CarbonImmutable::parse('2026-12-15 08:00')); + app(SendBookingReminders::class)->handle(); + app(SendBookingReminders::class)->handle(); + $booking->refresh(); + $this->assertSame(BookingStatus::Completed, $booking->status, 'the outstanding payout does not hold the stay up'); + $this->assertNull($booking->settled_at); + $payout = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PayoutCheck)->sole(); + $this->assertSame('2026-12-28', $payout->due_on->toDateString()); + $this->assertSame(ActivityState::Waiting, collect(CaseActivities::for($booking))->firstWhere('key', 'task_payout_check')->state, 'not due yet'); + $this->assertContains('Die Auszahlung von FeWo-direkt ist noch nicht eingegangen.', CaseClosure::commercialPoints($booking)); + + $this->travelTo(CarbonImmutable::parse('2026-12-29 08:00')); + $this->assertSame('Auszahlung des Portals prüfen', collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id))['title'] ?? null); + app(RecordPayment::class)->handle($booking->fresh(), 89469, CarbonImmutable::today(), PaymentMethod::Transfer, kind: PaymentKind::PortalPayout, source: 'FeWo-direkt'); + + $booking->refresh(); + $this->assertSame(BookingTaskStatus::Done, $payout->fresh()->status); + $this->assertNotNull($booking->settled_at, 'commercially settled once the payout arrived'); + $this->assertSame(BookingStatus::Completed, $booking->status); + $this->assertSame($fewo->id, $booking->origin_channel_id); + } + + /** T21 – A6 family stay: services prepared, no guest mails, closing without reminders; the agreed money settles it. */ + public function test_t21_family_stay_with_preparation_and_closing(): void + { + $this->property->update(['tourist_tax_rate' => 250, 'stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental', 'private']]]]); + $linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 1800, 'pricing' => 'per_item', 'is_active' => true]); + Livewire::test(CreateBooking::class) + ->fillForm(['kind' => BookingForm::OWN_USE, 'internal_kind' => InternalKind::PrivateStay->value, 'occasion' => 'Besuch von Tochter Anna', 'property_id' => $this->property->id, 'guests' => 3, 'arrival' => '2026-11-14', 'departure' => '2026-11-19', + 'stay_first_name' => 'Anna', 'stay_last_name' => 'Stommer', 'stay_email' => 'anna@example.org', 'rent' => '0', 'tourist_tax_persons' => 2, + 'items' => [['extra_id' => $linen->id, 'quantity' => 3]]]) + ->call('create')->assertHasNoFormErrors(); + $visit = Booking::query()->sole(); + + $this->travelTo(CarbonImmutable::parse('2026-11-10 08:00')); + app(SendBookingReminders::class)->handle(); + $titles = BookingTask::query()->where('booking_id', $visit->id)->pluck('title')->sort()->values()->all(); + $this->assertSame(['Bereitstellen: 3 × Wäschepaket', 'Endreinigung'], $titles); + $this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'no arrival details for family'); + + $this->travelTo(CarbonImmutable::parse('2026-11-20 08:00')); + app(SendBookingReminders::class)->handle(); + $this->assertSame(BookingStatus::Confirmed, $visit->fresh()->status, 'the stay waits for its open tasks'); + foreach (BookingTask::query()->where('booking_id', $visit->id)->get() as $task) { + Livewire::test(ViewBooking::class, ['record' => $visit->getRouteKey()])->callAction('completeTask', ['task' => $task->id, 'outcome' => 'done']); + } + app(SendBookingReminders::class)->handle(); + app(RequestReviews::class)->handle(); + + $visit->refresh(); + $this->assertSame(BookingStatus::Completed, $visit->status); + $this->assertNull($visit->settled_at); + $this->assertSame(['Vereinbarte Zahlung noch offen: '.Money::format(7900).' (ohne Erinnerungen).'], CaseClosure::commercialPoints($visit)); + $this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('status', BookingTaskStatus::Open)->count(), 'no reminders of any kind'); + app(RecordPayment::class)->handle($visit, 7900, CarbonImmutable::today(), PaymentMethod::Cash); + $this->assertNotNull($visit->fresh()->settled_at); + Mail::assertNotSent(ArrivalInformation::class); + Mail::assertNotSent(ReviewRequest::class); + } + + /** T22 – the stay is closed while money is still open; the claim stays visible and the commercial closing waits. */ + public function test_t22_stay_closed_while_commercial_points_are_open(): void + { + $booking = $this->confirmedOwnBooking(); + app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today()); + + $this->travelTo(CarbonImmutable::parse('2026-11-12 08:00')); + app(SendBookingReminders::class)->handle(); + app(SendBookingReminders::class)->handle(); + $booking->refresh(); + + $this->assertSame(BookingStatus::Completed, $booking->status, 'open money does not hold the stay up'); + $this->assertNull($booking->settled_at); + $this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->whereIn('kind', [BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim])->count(), 'exactly one follow-up for the open amount'); + $this->assertNotNull(collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id)), 'the follow-up stays in the work list'); + $this->assertStringContainsString('Noch offen vom Gast', implode(' ', CaseClosure::commercialPoints($booking))); + $this->assertSame('Aufenthalt abgeschlossen, kaufmännisch noch offen', explode(' · ', CaseActivities::situation($booking))[1]); + + app(RecordPayment::class)->handle($booking, (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today()); + $booking->refresh(); + $this->assertNotNull($booking->settled_at); + $this->assertSame(BookingStatus::Completed, $booking->status, 'a late payment does not reopen the stay'); + + // A contradicting payout statement is settled by the landlord with a reason. + $this->fewo(); + $this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-DIFF01"); + $portal = Booking::query()->where('portal_reference', 'HA-DIFF01')->sole(); + Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22', + 'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69'], ['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Erwartet', 'amount' => '900.20']]]); + $this->travelTo(CarbonImmutable::parse('2026-12-15 08:00')); + app(SendBookingReminders::class)->handle(); + app(RecordPayment::class)->handle($portal->fresh(), 89469, CarbonImmutable::today(), kind: PaymentKind::PortalPayout, source: 'FeWo-direkt'); + $portal->refresh(); + $this->assertSame(BookingStatus::Completed, $portal->status); + $this->assertNull($portal->settled_at, 'the 5,51 € difference is not settled by the system'); + Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert']); + $portal->refresh(); + $this->assertSame(['Ingrid', 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'], [$portal->settled_by, $portal->settled_note]); + } + + /** T24 – landlord, property, portal and case settings decide the whole run. */ + public function test_t24_settings_of_every_level_are_effective_in_the_whole_run(): void + { + $this->releaseTexts(); + DocumentReleases::set(DocumentKind::Information, true, 'Test'); + // Landlord: automatic, requests reserve. Portal Ostseeklar (requests): no reservation, manual. Property: arrival information 5 days ahead. + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => true]]); + $this->manualPortal->update(['process_overrides' => ['inquiry' => ['pre_reservation' => false, 'processing' => 'manual']]]); + $this->property->update(['process_overrides' => ['arrival_info_days_before' => 5], 'asks_arrival_time' => true]); + + $direct = $this->request(); + $this->assertSame(BookingStatus::OfferSent, $direct->fresh()->status, 'landlord level: automatic offer with hold'); + $this->assertNotNull($direct->fresh()->hold_expires_at); + + $viaPortal = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-21'), CarbonImmutable::parse('2026-11-24'), 2), ['first_name' => 'Pia', 'last_name' => 'Portal', 'email' => 'pia@example.org'], originChannel: $this->manualPortal->fresh()); + $this->assertSame([0, 0, null], [$viaPortal->fresh()->information_version, $viaPortal->fresh()->offer_version, $viaPortal->fresh()->hold_expires_at], 'portal level: no hold, manual'); + $this->assertSame('sendInformation', CaseActivities::next($viaPortal->fresh())?->action); + + Livewire::test(ViewBooking::class, ['record' => $viaPortal->getRouteKey()])->callAction('automation', ['mode' => ProcessingMode::Automatic->value]); + $this->assertSame(1, $viaPortal->fresh()->information_version, 'case level: switched to automatic, the information goes out'); + $this->wish($viaPortal->fresh()); + $this->assertSame(BookingStatus::Confirmed, $viaPortal->fresh()->status, 'and the wish is confirmed automatically'); + + // Property level: arrival details are asked for 5 + 2 days ahead, the arrival information 5 days ahead. + $this->travelTo(CarbonImmutable::parse('2026-11-14 08:00')); + app(SendBookingReminders::class)->handle(); + $this->assertTrue(BookingTask::query()->where('booking_id', $viaPortal->id)->where('kind', BookingTaskKind::ArrivalDetails)->exists()); + Mail::assertNotSent(ArrivalInformation::class); + $this->travelTo(CarbonImmutable::parse('2026-11-16 08:00')); + app(SendBookingReminders::class)->handle(); + Mail::assertSent(ArrivalInformation::class, fn (ArrivalInformation $mail): bool => $mail->booking->is($viaPortal)); + + $this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert])); + Livewire::test(EffectiveSettings::class)->set('bookingId', $viaPortal->id)->assertSee('für diesen Vorgang umgestellt')->assertSee('Abweichung des Portals'); + } + + /** T25 – change of a binding portal booking: the portal's new price, the calendar and the portal tasks follow. */ + public function test_t25_change_of_a_binding_portal_booking(): void + { + $this->fewo(); + $this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-CHANGE"); + $booking = Booking::query()->sole(); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22']); + $this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-14')->exists()); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('change', ['arrival' => '2026-12-07', 'departure' => '2026-12-16', 'guests' => 2, 'portal_total' => '1199.00', 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Portal->value, 'reason' => 'Verlängerung über FeWo-direkt']) + ->assertNotified('Änderung gespeichert'); + + $booking->refresh(); + $this->assertSame(['2026-12-16', 119900, 'portal'], [$booking->departure->toDateString(), $booking->total, $booking->quote['source'] ?? null], 'the portal price counts, nothing is recalculated'); + $this->assertSame(CaseType::A4, $booking->case_type); + $this->assertSame(0, CaseMoney::of($booking)->openForUs(), 'the portal still collects'); + $this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-16')->exists(), 'portal task for the new dates'); + $this->assertSame(ChangeBasis::Portal, $booking->changes()->sole()->basis); + $this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::RefundCheck)->count()); + } + + /** Special cases: unknown guest contact of a portal booking, unknown portal price, a cancellation shortly before arrival. */ + public function test_special_cases_of_preparation_and_closing(): void + { + $this->property->update(['stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental']]]]); + $this->fewo(); + $this->portalMail("Anreise: 30.10.2026\nAbreise: 02.11.2026\nBuchungsnummer: HA-NOMAIL"); + $portal = Booking::query()->sole(); + + $this->travelTo(CarbonImmutable::parse('2026-10-26 08:00')); + app(SendBookingReminders::class)->handle(); + $details = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::ArrivalDetails)->sole(); + $this->assertStringContainsString('im Portal FeWo-direkt nachsehen', (string) $details->note, 'contact of a portal guest may have to come from the portal'); + + $this->travelTo(CarbonImmutable::parse('2026-11-03 08:00')); + $cleaning = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::Service)->sole(); + $cleaning->complete('Ingrid'); + app(SendBookingReminders::class)->handle(); + $portal->refresh(); + $this->assertSame(BookingStatus::Completed, $portal->status); + $this->assertSame(BookingTaskStatus::Dismissed, $details->fresh()->status, 'arrival details are moot after the departure'); + $this->assertContains('Der Gesamtpreis laut FeWo-direkt fehlt.', CaseClosure::commercialPoints($portal), 'an unknown portal price is no invented 0'); + + // Cancellation two days before arrival: preparation is dropped, costs keep the case open commercially. + $own = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-05'), CarbonImmutable::parse('2026-11-08'), 2), ['first_name' => 'Kurt', 'last_name' => 'Kurzfristig', 'email' => 'kurt@example.org'], sendMails: false); + Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('confirm', ['notify' => false]); + app(SendBookingReminders::class)->handle(); + $this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->exists()); + Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Krankheit', 'notify' => false, 'costs_task' => true]); + $own->refresh(); + $this->assertSame(BookingStatus::Cancelled, $own->status); + $this->assertSame(BookingTaskStatus::Dismissed, BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->value('status')); + $this->assertNull($own->settled_at, 'the cancellation fee is still to be settled'); + BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::CancellationFee)->sole()->complete('Ingrid', 'Keine Kosten berechnet (Kulanz).'); + $this->assertNotNull($own->fresh()->settled_at); + } + + /** Special case: an issue during the stay holds the closing up, a follow-up (damage) does not. */ + public function test_issues_hold_the_stay_up_and_follow_ups_do_not(): void + { + $booking = $this->confirmedOwnBooking(); + $this->travelTo(CarbonImmutable::parse('2026-11-08 10:00')); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::Issue->value, 'title' => 'Kaffeemaschine defekt', 'responsible' => 'Ingrid']); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::FollowUp->value, 'title' => 'Fleck im Teppich – Reinigung abrechnen']); + $this->assertSame(2, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::Issue, BookingTaskKind::FollowUp])->count()); + + $this->travelTo(CarbonImmutable::parse('2026-11-11 08:00')); + app(SendBookingReminders::class)->handle(); + $this->assertNotSame(BookingStatus::Completed, $booking->fresh()->status, 'the open issue holds the stay up'); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('closeStay', ['note' => 'Kaffeemaschine ersetzt']); + $booking->refresh(); + $this->assertSame(BookingStatus::Completed, $booking->status); + $this->assertSame(BookingTaskStatus::Open, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::FollowUp)->value('status'), 'the follow-up stays on the closed case'); + $this->assertSame('Kaffeemaschine ersetzt', BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::Issue)->value('note')); + } + + /** Section 5: stored statuses are not silently reinterpreted; the command shows and corrects them on request. */ + public function test_existing_payment_statuses_are_only_corrected_on_request(): void + { + $this->fewo(); + $this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-OLDPAY"); + $booking = Booking::query()->sole(); + $booking->update(['total' => 97951, 'deposit' => 30000]); + // As the old rule left it: "paid according to the portal" had moved the status. + $booking->payments()->create(['amount' => 39061, 'paid_on' => '2026-10-20', 'method' => PaymentMethod::Transfer, 'kind' => PaymentKind::GuestViaPortal]); + $booking->update(['status' => BookingStatus::DepositPaid]); + + $this->artisan('cases:recheck-payment-status')->expectsOutputToContain('Vorschau')->assertSuccessful(); + $this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status, 'nothing changed by the preview'); + $this->artisan('cases:recheck-payment-status', ['--apply' => true])->expectsOutputToContain('korrigiert')->assertSuccessful(); + $this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status); + $this->assertStringContainsString('laut Portal bezahlt', (string) $booking->events()->where('type', 'status')->reorder()->orderByDesc('id')->value('reason')); + } + + private function request(string $email = 'gesa@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking + { + return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email]); + } + + private function sendInformation(Booking $booking): void + { + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true]) + ->assertNotified('Auskunft gesendet'); + } + + private function wish(Booking $booking): void + { + $this->post(URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => $booking->information_version]), ['terms' => '1'])->assertRedirect(); + } + + private function automaticWithoutHold(): void + { + $this->releaseTexts(); + DocumentReleases::set(DocumentKind::Information, true, 'Test'); + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]); + } + + private function confirmedOwnBooking(): Booking + { + $booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'], sendMails: false); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('confirm', ['notify' => false]); + + return $booking->fresh(); + } + + /** + * @param array $attributes + */ + private function fewo(array $attributes = []): Channel + { + return Channel::query()->where('name', 'FeWo-direkt')->first() ?? Channel::factory()->for($this->property)->create([ + 'name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'case_intake' => CaseIntakeMode::Create, + 'settings' => ['email_senders' => 'fewo-direkt.de'], 'process_overrides' => ['booking' => ['payments' => 'portal']], ...$attributes, + ]); + } + + private function portalMail(string $text): void + { + app(ProcessPortalMail::class)->handle(new PortalMail(uniqid('msg-'), 'noreply@fewo-direkt.de', 'Neue Buchung', $text, CarbonImmutable::now())); + } + + private function releaseTexts(): void + { + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']); + DocumentReleases::set(DocumentKind::ExternalRecord, false, 'Test'); + } +} diff --git a/tests/Feature/TestOperationSmtpAcceptanceTest.php b/tests/Feature/TestOperationSmtpAcceptanceTest.php new file mode 100644 index 0000000..52dd70c --- /dev/null +++ b/tests/Feature/TestOperationSmtpAcceptanceTest.php @@ -0,0 +1,189 @@ +freePort(); + $this->capture = storage_path('framework/testing/smtp-sink-'.getmypid().'.jsonl'); + @mkdir(dirname($this->capture), 0777, true); + @unlink($this->capture); + @unlink($this->capture.'.stop'); + $this->sink = proc_open([PHP_BINARY, base_path('tests/Support/smtp-sink.php'), (string) $port, $this->capture, '120'], [], $pipes); + $this->waitFor(fn (): bool => file_exists($this->capture.'.ready')); + + config([ + 'mail.default' => 'smtp', + 'mail.mailers.smtp' => ['transport' => 'smtp', 'scheme' => 'smtp', 'host' => '127.0.0.1', 'port' => $port, 'username' => null, 'password' => null, 'timeout' => 5, 'local_domain' => 'localhost', 'auto_tls' => false], + 'fewo.mail_redirect_to' => null, + 'queue.default' => 'database', + ]); + // The real mail manager behind the test-operation gate, not the fake. + $manager = new MailManager(app()); + app()->instance('mail.manager', $manager); + Mail::swap($manager); + + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + app(TenantContext::class)->set(Property::sole()->tenant); + Storage::fake('local'); + Http::fake(fn () => Http::response('', 500)); + $this->withoutVite(); + $this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple])); + } + + protected function tearDown(): void + { + if ($this->sink !== null) { + touch($this->capture.'.stop'); + $this->waitFor(fn (): bool => ! file_exists($this->capture.'.ready')); + proc_close($this->sink); + } + @unlink($this->capture); + @unlink($this->capture.'.stop'); + + parent::tearDown(); + } + + public function test_t23_every_message_goes_only_to_the_test_address_over_real_smtp(): void + { + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + DocumentReleases::set(DocumentKind::Information, true, 'Test'); + Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => self::TEST_ADDRESS, 'notification_emails' => 'vermieterin@example.org', + 'bank_iban' => 'DE02120300000000202051', 'process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]); + app(TenantContext::class)->set(Settings::tenant()->fresh()); + $property = Property::sole(); + + // Automatic: request → information; guest: booking wish → confirmation; scheduled: arrival information. + $booking = app(CreateReservation::class)->handle($property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => self::GUEST]); + $booking->refresh(); + $this->post(URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => $booking->information_version]), ['terms' => '1'])->assertRedirect(); + $this->assertTrue($booking->fresh()->isBinding()); + $this->travelTo(CarbonImmutable::parse('2026-11-04 08:00')); + app(SendBookingReminders::class)->handle(); + + // Manual: the landlord resends the information of a second request; with Cc and Bcc to outside addresses. + $second = app(CreateReservation::class)->handle($property, new StayRequest(CarbonImmutable::parse('2026-11-21'), CarbonImmutable::parse('2026-11-24'), 2), ['first_name' => 'Ole', 'last_name' => 'Zweit', 'email' => 'ole@gast.example']); + Livewire::test(ViewBooking::class, ['record' => $second->getRouteKey()])->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])->assertNotified('Auskunft gesendet'); + Mail::to('ole@gast.example')->cc('cc@aussen.example')->bcc('bcc@aussen.example')->send(new BookingWishNotice($second->fresh(), 'pending')); + + // Queued while the landlord was live – sent after switching back to test operation: the gate decides at sending time. + Settings::tenant()->update(['operating_mode' => Settings::MODE_LIVE]); + Mail::to('ole@gast.example')->queue(new InformationSent($second->fresh(), 'https://example.test')); + $this->assertSame(1, DB::table('jobs')->count(), 'the message waits in the queue'); + Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST]); + $this->artisan('queue:work', ['--once' => true, '--stop-when-empty' => true]); + + $messages = $this->captured(); + $this->assertGreaterThanOrEqual(8, count($messages), 'information, notices, wish, confirmation, arrival information, manual and queued mails'); + foreach ($messages as $message) { + $this->assertSame([self::TEST_ADDRESS], $message['to'], 'SMTP envelope of: '.$message['subject']); + $this->assertStringNotContainsString('gast.example>', $message['headers_to']); + } + $all = implode("\n", array_column($messages, 'envelope')); + foreach ([self::GUEST, 'ole@gast.example', 'cc@aussen.example', 'bcc@aussen.example', 'vermieterin@example.org'] as $original) { + $this->assertStringNotContainsString($original, $all, $original.' never in an SMTP envelope'); + } + $this->assertTrue(collect($messages)->contains(fn (array $message): bool => str_contains($message['data'], EnforceMailTestMode::ORIGINAL_RECIPIENTS_HEADER.': '.self::GUEST)), 'the original recipient is documented in a header'); + $this->assertTrue(collect($messages)->contains(fn (array $message): bool => str_contains($message['subject'], 'Unverbindliche Auskunft'))); + + // The history says where the mails really went. + $history = Booking::query()->find($booking->id)->events()->pluck('summary')->implode(' | '); + $this->assertStringContainsString('im Testbetrieb an die Testadresse (nicht an den Gast)', $history); + $this->assertStringContainsString('Testbetrieb: nur an die Testadresse, nicht an den Gast', $history); + $this->assertStringNotContainsString('E-Mail an den Gast:', $history); + } + + /** + * @return list, subject: string, headers_to: string, envelope: string, data: string}> + */ + private function captured(): array + { + $this->waitFor(fn (): bool => file_exists($this->capture)); + $messages = []; + foreach (file($this->capture, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) { + $entry = json_decode($line, true); + $data = (string) $entry['data']; + $headers = substr($data, 0, (int) strpos($data, "\r\n\r\n")); + preg_match('/^Subject: (.*)$/mi', $headers, $subject); + preg_match('/^To: (.*)$/mi', $headers, $to); + $messages[] = [ + 'to' => $entry['to'], + 'subject' => mb_decode_mimeheader(trim($subject[1] ?? '')), + 'headers_to' => $to[1] ?? '', + 'envelope' => $entry['from'].' -> '.implode(',', $entry['to']), + 'data' => $data, + ]; + } + + return $messages; + } + + private function freePort(): int + { + $socket = stream_socket_server('tcp://127.0.0.1:0'); + $name = stream_socket_get_name($socket, false); + fclose($socket); + + return (int) substr((string) $name, strrpos((string) $name, ':') + 1); + } + + private function waitFor(callable $condition): void + { + $until = microtime(true) + 10; + while (! $condition() && microtime(true) < $until) { + usleep(50000); + } + } +} diff --git a/tests/Support/smtp-sink.php b/tests/Support/smtp-sink.php new file mode 100644 index 0000000..6185684 --- /dev/null +++ b/tests/Support/smtp-sink.php @@ -0,0 +1,115 @@ +, delivers nothing anywhere and writes one JSON line per message (envelope sender, envelope + * recipients, raw data) to . It stops when .stop exists or after (default 120). + * + * Usage: php tests/Support/smtp-sink.php [seconds] + */ +$port = (int) ($argv[1] ?? 2525); +$file = (string) ($argv[2] ?? sys_get_temp_dir().'/smtp-sink.jsonl'); +$until = time() + (int) ($argv[3] ?? 120); + +$server = stream_socket_server('tcp://127.0.0.1:'.$port, $errorCode, $errorMessage); +if ($server === false) { + fwrite(STDERR, "SMTP sink: {$errorMessage}\n"); + exit(1); +} +stream_set_blocking($server, false); +file_put_contents($file.'.ready', (string) getmypid()); + +/** @var array, data: ?string}> $clients */ +$clients = []; + +$send = function ($socket, string $line): void { + @fwrite($socket, $line."\r\n"); +}; + +while (time() < $until && ! file_exists($file.'.stop')) { + $read = [$server]; + foreach ($clients as $entry) { + $read[] = $entry['socket']; + } + $write = $except = null; + if (@stream_select($read, $write, $except, 0, 200000) === false) { + break; + } + + foreach ($read as $socket) { + if ($socket === $server) { + $connection = @stream_socket_accept($server, 0); + if ($connection !== false) { + stream_set_blocking($connection, false); + $clients[(int) $connection] = ['socket' => $connection, 'buffer' => '', 'from' => null, 'to' => [], 'data' => null]; + $send($connection, '220 fewo-smtp-sink ESMTP'); + } + + continue; + } + + $id = (int) $socket; + $chunk = @fread($socket, 65536); + if ($chunk === '' || $chunk === false) { + if (feof($socket)) { + fclose($socket); + unset($clients[$id]); + } + + continue; + } + $clients[$id]['buffer'] .= $chunk; + + while (true) { + $client = &$clients[$id]; + if ($client['data'] !== null) { + $end = strpos($client['buffer'], "\r\n.\r\n"); + if ($end === false) { + break; + } + $client['data'] .= substr($client['buffer'], 0, $end); + $client['buffer'] = substr($client['buffer'], $end + 5); + file_put_contents($file, json_encode(['from' => $client['from'], 'to' => $client['to'], 'data' => $client['data']])."\n", FILE_APPEND | LOCK_EX); + $client['from'] = null; + $client['to'] = []; + $client['data'] = null; + $send($socket, '250 OK: queued in the sink'); + + continue; + } + + $position = strpos($client['buffer'], "\r\n"); + if ($position === false) { + break; + } + $line = substr($client['buffer'], 0, $position); + $client['buffer'] = substr($client['buffer'], $position + 2); + $command = strtoupper(substr($line, 0, 4)); + + match (true) { + $command === 'EHLO' => $send($socket, "250-fewo-smtp-sink\r\n250 8BITMIME"), + $command === 'HELO' => $send($socket, '250 fewo-smtp-sink'), + $command === 'MAIL' => [$client['from'] = trim(substr($line, 10), ' <>'), $send($socket, '250 OK')], + $command === 'RCPT' => [$client['to'][] = trim(substr($line, 8), ' <>'), $send($socket, '250 OK')], + $command === 'DATA' => [$client['data'] = '', $send($socket, '354 End data with .')], + $command === 'RSET' => [$client['from'] = null, $client['to'] = [], $send($socket, '250 OK')], + $command === 'NOOP' => $send($socket, '250 OK'), + $command === 'QUIT' => [$send($socket, '221 Bye'), fclose($socket), $clients[$id] = null], + default => $send($socket, '502 Command not implemented'), + }; + unset($client); + if ($clients[$id] === null) { + unset($clients[$id]); + + break; + } + } + unset($client); + } +} + +foreach ($clients as $entry) { + @fclose($entry['socket']); +} +fclose($server); +@unlink($file.'.ready');