, portal_total?: ?int, agreed_total?: ?int, agreed_total_label?: ?string, rent?: ?int, tourist_tax_persons?: ?int} $changes * @return array{errors: list, before: array, after: array, summary: list, calendar: list, portals: list, price: array{before: ?int, after: ?int, difference: ?int, source: string}, payment: list, refund: int, confirmation: bool} */ public function preview(Booking $booking, array $changes): array { $booking->loadMissing(['property', 'payments', 'guest']); $errors = []; $before = self::snapshot($booking); $arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival); $departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure); $guests = array_key_exists('guests', $changes) && filled($changes['guests']) ? (int) $changes['guests'] : $booking->guests; $extras = array_key_exists('extras', $changes) && is_array($changes['extras']) ? array_filter(array_map('intval', $changes['extras'])) : (array) ($booking->extras ?? []); if ($departure->lessThanOrEqualTo($arrival)) { $errors[] = 'Die Abreise muss nach der Anreise liegen.'; } elseif (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) { $errors[] = 'Der neue Zeitraum ist nicht frei.'; } if ($guests !== null && $guests > $booking->property->max_guests) { $errors[] = 'Höchstens '.$booking->property->max_guests.' Personen.'; } [$quote, $source, $priceError] = $departure->greaterThan($arrival) ? $this->price($booking, $changes, $arrival, $departure, $guests, $extras) : [null, '–', null]; if ($priceError !== null) { $errors[] = $priceError; } $paid = $booking->paidAmount(); $total = $quote !== null ? $quote['total'] : $booking->total; $depositPaid = $booking->deposit !== null && $paid >= $booking->deposit && $paid > 0; $deposit = $quote === null ? $booking->deposit : ($depositPaid ? $booking->deposit : ($quote['deposit'] ?? $booking->deposit)); $after = [ 'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString(), 'guests' => $guests, 'extras' => $extras, 'quote' => $quote['quote'] ?? $booking->quote, 'total' => $total, 'deposit' => $deposit, 'balance_due_on' => $quote['balance_due_on'] ?? $booking->balance_due_on?->toDateString(), 'rent' => $changes['rent'] ?? null, 'tourist_tax_persons' => array_key_exists('tourist_tax_persons', $changes) ? $changes['tourist_tax_persons'] : $booking->tourist_tax_persons, ]; [$calendar, $portals] = $this->calendarConsequences($booking, $arrival, $departure); $difference = $total !== null && $booking->total !== null ? $total - $booking->total : null; $refund = $total !== null ? max(0, $paid - $total) : 0; $payment = array_values(array_filter([ $booking->wantsPaymentTasks() || ($total !== null && $total > 0 && $booking->process()->payments()->value === 'landlord' && ! $booking->isInternal()) ? 'Bezahlt bisher: '.Money::format($paid).' · danach offen: '.Money::format(max(0, (int) $total - $paid)) : null, $refund > 0 ? 'Der Gast hat mehr bezahlt als der neue Preis: '.Money::format($refund).' zu erstatten (Aufgabe wird angelegt).' : null, $depositPaid ? 'Die Anzahlung ist bezahlt und bleibt unverändert.' : null, $after['balance_due_on'] !== ($booking->balance_due_on?->toDateString()) && $after['balance_due_on'] !== null && ! $booking->isInternal() ? 'Restzahlung neu fällig am '.CarbonImmutable::parse($after['balance_due_on'])->format('d.m.Y').'.' : null, $booking->process()->payments()->value === 'portal' ? 'Die Zahlung läuft weiter über das Portal.' : null, ])); return [ 'errors' => $errors, 'before' => $before, 'after' => $after, 'summary' => self::summary($before, $after), 'calendar' => $calendar, 'portals' => $portals, 'price' => ['before' => $booking->total, 'after' => $total, 'difference' => $difference, 'source' => $source], 'payment' => $payment, 'refund' => $refund, 'confirmation' => ! $booking->isInternal() && filled($booking->guest?->email), ]; } /** * An agreed change (or a change of an internal case): takes effect at once. * * @param array $changes * @param array{requested_by: string, reason: string, basis: ChangeBasis, agreed_at?: ?string, effective_on?: ?string, send_confirmation?: bool} $meta * * @throws ReservationException */ public function apply(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange { $this->guard($booking); if ($meta['basis'] === ChangeBasis::GuestLink) { throw new ReservationException('Eine Zustimmung über den Link entsteht nur, wenn der Gast selbst annimmt.'); } $change = DB::transaction(function () use ($booking, $changes, $meta, $by): BookingChange { $booking->lockForTransition(); $preview = $this->preview($booking, $changes); if ($preview['errors'] !== []) { throw new ReservationException(implode(' ', $preview['errors'])); } $change = $booking->changes()->create([ 'status' => ChangeStatus::Applied, 'requested_by' => $meta['requested_by'], 'basis' => $meta['basis'], 'reason' => trim((string) $meta['reason']), 'effective_on' => $meta['effective_on'] ?? today()->toDateString(), 'agreed_at' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($meta['agreed_at'] ?? now()), 'agreed_by' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($booking->guest?->full_name ?? 'Gast'), 'before' => $preview['before'], 'after' => $preview['after'], 'consequences' => self::consequences($preview), 'applied_at' => now(), 'recorded_by' => $by, ]); $change->tenant_id = $booking->tenant_id; $change->save(); $this->write($booking, $preview, $meta['reason'], $by, $change); return $change; }); if ($meta['send_confirmation'] ?? false) { $this->confirm($booking->fresh(), $change); } return $change->fresh(); } /** * A change the guest still has to agree to: nothing changes; the guest gets a link to accept or decline. * * @param array $changes * @param array{requested_by: string, reason: string, effective_on?: ?string, valid_days?: int} $meta * * @throws ReservationException */ public function propose(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange { $this->guard($booking); if ($booking->isInternal() || $booking->caseType()->isExternallyBinding()) { throw new ReservationException('Ein Vorschlag mit Zustimmungslink ist nur für eigene Buchungen möglich – Portalbuchungen werden im Portal geändert.'); } if (blank($booking->guest?->email)) { throw new ReservationException('Für einen Vorschlag wird die E-Mail-Adresse des Gastes benötigt.'); } if ($booking->changes()->where('status', ChangeStatus::Proposed)->exists()) { throw new ReservationException('Es liegt schon ein Änderungsvorschlag beim Gast. Bitte zuerst zurückziehen.'); } $preview = $this->preview($booking, $changes); if ($preview['errors'] !== []) { throw new ReservationException(implode(' ', $preview['errors'])); } $change = $booking->changes()->create([ 'status' => ChangeStatus::Proposed, 'requested_by' => $meta['requested_by'], 'reason' => trim((string) $meta['reason']), 'effective_on' => $meta['effective_on'] ?? null, 'before' => $preview['before'], 'after' => $preview['after'], 'consequences' => self::consequences($preview), 'expires_at' => now()->addDays((int) ($meta['valid_days'] ?? 7)), 'recorded_by' => $by, ]); $change->tenant_id = $booking->tenant_id; $change->save(); CaseLog::record($booking, 'change', 'Änderung dem Gast vorgeschlagen: '.implode(' · ', $preview['summary']), $meta['reason'], data: ['booking_change_id' => $change->id]); try { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ChangeProposed($booking, $change, $this->link($change))); } catch (Throwable $exception) { Log::warning('Änderungsvorschlag nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); throw new ReservationException('Der Vorschlag ist gespeichert, aber die E-Mail konnte nicht versendet werden.'); } return $change; } /** * The guest accepts a proposed change through the signed link: the dates are checked again, then it takes effect. * * @throws ReservationException */ public function accept(BookingChange $change, ?string $ip = null): BookingChange { return DB::transaction(function () use ($change, $ip): BookingChange { $booking = $change->booking; $booking->lockForTransition(); $change = BookingChange::query()->whereKey($change->id)->lockForUpdate()->firstOrFail(); if ($change->status !== ChangeStatus::Proposed) { throw new ReservationException('Dieser Vorschlag ist nicht mehr offen.'); } if ($change->expires_at !== null && $change->expires_at->isPast()) { $change->update(['status' => ChangeStatus::Expired]); throw new ReservationException('Dieser Vorschlag ist abgelaufen. Bitte melden Sie sich bei uns.'); } $after = (array) $change->after; $preview = $this->preview($booking, [...$after, 'agreed_total' => $after['total'] ?? null, 'portal_total' => null]); if ($preview['errors'] !== []) { throw new ReservationException('Die Änderung ist leider nicht mehr möglich: '.implode(' ', $preview['errors'])); } $change->update(['status' => ChangeStatus::Applied, 'basis' => ChangeBasis::GuestLink, 'agreed_at' => now(), 'agreed_by' => $booking->guest?->full_name, 'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null, 'applied_at' => now()]); CaseLog::context(fn () => $this->write($booking, $preview, (string) $change->reason, CaseLog::GUEST, $change), actor: CaseLog::GUEST); return $change->fresh(); }); } public function decline(BookingChange $change, ?string $ip = null): void { if ($change->status !== ChangeStatus::Proposed) { return; } $change->update(['status' => ChangeStatus::Declined, 'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null]); CaseLog::record($change->booking, 'change', 'Änderungsvorschlag vom Gast abgelehnt', actor: CaseLog::GUEST, data: ['booking_change_id' => $change->id]); } public function withdraw(BookingChange $change, ?string $by = null): void { if ($change->status === ChangeStatus::Proposed) { $change->update(['status' => ChangeStatus::Withdrawn, 'decided_at' => now()]); CaseLog::record($change->booking, 'change', 'Änderungsvorschlag zurückgezogen', actor: $by); } } /** * The guest's signed link to a proposed change (valid while the proposal is). */ public function link(BookingChange $change): string { $until = $change->expires_at ?? now()->addDays(7); return $change->booking->website()?->temporarySignedRoute('changes.show', $until, ['change' => $change]) ?? URL::temporarySignedRoute('changes.show', $until, ['change' => $change]); } /** * Sends the updated confirmation of an agreed change (information, not consent). */ public function confirm(Booking $booking, BookingChange $change): bool { if ($booking->isInternal() || blank($booking->guest?->email)) { return false; } try { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingChanged($booking, $change)); $change->update(['confirmation_sent_at' => now()]); return true; } catch (Throwable $exception) { Log::warning('Änderungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); return false; } } /** * @throws ReservationException */ private function guard(Booking $booking): void { if (! in_array($booking->status, BookingStatus::occupying(), true)) { throw new ReservationException('Ändern lässt sich nur eine bestehende Buchung oder Belegung. Ein Angebot wird über „Angebot ändern & neu senden“ geändert.'); } } /** * Writes the new state on the case (inside the transaction of the caller). * * @param array $preview */ private function write(Booking $booking, array $preview, string $reason, ?string $by, BookingChange $change): void { $after = $preview['after']; $booking->update([ 'arrival' => $after['arrival'], 'departure' => $after['departure'], 'guests' => $after['guests'], 'extras' => $after['extras'], 'quote' => $after['quote'], 'total' => $after['total'], 'deposit' => $after['deposit'], 'balance_due_on' => $after['balance_due_on'], 'tourist_tax_persons' => $after['tourist_tax_persons'], ]); CaseLog::record($booking, 'change', 'Geändert: '.implode(' · ', $preview['summary']), $reason, data: ['booking_change_id' => $change->id], actor: $by); $this->payments->updateStatus($booking->fresh()); if ($preview['refund'] > 0) { BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [ 'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'note' => 'Nach der Änderung zu viel bezahlt: '.Money::format($preview['refund']).' an den Gast erstatten (als „Erstattung“ erfassen).', 'completed_by' => null, 'completed_at' => null, ]); } } /** * The new price and where it comes from. * * @param array $changes * @param array $extras * @return array{0: ?array{quote: array, total: int, deposit: ?int, balance_due_on: ?string}, 1: string, 2: ?string} */ private function price(Booking $booking, array $changes, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras): array { if ($booking->isInternal()) { try { $rent = array_key_exists('rent', $changes) && $changes['rent'] !== null ? (int) $changes['rent'] : PrivateStayPrice::rentOf($booking->quote); $taxPersons = array_key_exists('tourist_tax_persons', $changes) ? ($changes['tourist_tax_persons'] === null ? null : (int) $changes['tourist_tax_persons']) : $booking->tourist_tax_persons; $quote = $this->privateStay->quote($booking->property, $arrival, $departure, $guests, $extras, $rent, $taxPersons); return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => null, 'balance_due_on' => null], 'vereinbart (Miete, Leistungen, Kurabgabe)', null]; } catch (QuoteException $exception) { return [null, '–', $exception->getMessage()]; } } if ($booking->caseType()->isExternallyBinding() || ($booking->quote['source'] ?? null) === 'portal') { $total = filled($changes['portal_total'] ?? null) ? (int) $changes['portal_total'] : $booking->total; if ($total === null) { return [null, 'laut Portal – noch nicht bekannt', null]; } $columns = $this->portalPrice->columns($booking->property, $arrival, $departure, $guests, $total, $booking->processChannel()?->name); return [['quote' => $columns['quote'], 'total' => (int) $columns['total'], 'deposit' => $columns['deposit'], 'balance_due_on' => $columns['balance_due_on']], filled($changes['portal_total'] ?? null) ? 'neuer Gesamtpreis laut Portal' : 'Gesamtpreis laut Portal unverändert – bitte neuen Betrag eintragen, falls das Portal ihn geändert hat', null]; } $agreed = filled($changes['agreed_total'] ?? null) ? (int) $changes['agreed_total'] : null; try { $quote = $this->calculator->calculate($booking->property, new StayRequest($arrival, $departure, max(1, (int) $guests), $extras, $booking->promo_code)); foreach ((array) ($booking->quote['lines'] ?? []) as $line) { if (($line['type'] ?? null) === QuoteLineType::Adjustment->value) { $quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, (string) $line['label'], 1, (int) $line['amount'], (int) $line['amount'])); } } $source = 'aus Ihren Preisen neu berechnet'; } catch (QuoteException $exception) { if ($agreed === null) { return [null, '–', 'Preis: '.$exception->getMessage().' Bitte einen vereinbarten Preis eintragen.']; } $quote = new PriceQuote($arrival, $departure, (int) $guests, [new QuoteLine(QuoteLineType::Accommodation, 'Vereinbarter Preis', 1, $agreed, $agreed)], $booking->property->deposit_percent, $arrival->subDays($booking->property->balance_due_days_before_arrival)); $source = 'vereinbarter Preis'; } if ($agreed !== null && $agreed !== $quote->total()) { $label = trim((string) ($changes['agreed_total_label'] ?? '')) ?: 'Vereinbarte Preisanpassung'; $quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $agreed - $quote->total(), $agreed - $quote->total())); $source = 'vereinbarter Preis'; } return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()], $source, null]; } /** * What happens in the calendar and on the portals that are blocked by hand. * * @return array{0: list, 1: list} */ private function calendarConsequences(Booking $booking, CarbonImmutable $arrival, CarbonImmutable $departure): array { $oldStart = $booking->arrival; $oldEnd = $booking->departure; if ($arrival->equalTo($oldStart) && $departure->equalTo($oldEnd)) { return [['Kalender unverändert.'], []]; } $added = array_values(array_filter([ $arrival->lessThan($oldStart) ? [$arrival, $oldStart->min($departure)] : null, $departure->greaterThan($oldEnd) ? [$oldEnd->max($arrival), $departure] : null, ])); $freed = array_values(array_filter([ $oldStart->lessThan($arrival) ? [$oldStart, $arrival->min($oldEnd)] : null, $oldEnd->greaterThan($departure) ? [$departure->max($oldStart), $oldEnd] : null, ])); $range = fn (array $pair): string => $pair[0]->format('d.m.').'–'.$pair[1]->format('d.m.Y'); $calendar = [ ...array_map(fn (array $pair): string => 'Neu belegt: '.$range($pair), $added), ...array_map(fn (array $pair): string => 'Wieder frei: '.$range($pair), $freed), 'Die Kalender für die Portale zeigen den neuen Zeitraum beim nächsten Abruf.', ]; $origin = $booking->origin_channel_id ?? $booking->import_channel_id; $portals = $booking->property->channels()->active()->where('requires_manual_blocking', true)->get() ->filter(fn (Channel $channel): bool => $channel->exportsOccupations() && $channel->id !== $origin) ->map(fn (Channel $channel): string => 'Aufgabe für '.$channel->name.': '.implode(', ', [...array_map(fn (array $pair): string => 'sperren '.$range($pair), $added), ...array_map(fn (array $pair): string => 'freigeben '.$range($pair), $freed)])) ->values()->all(); if ($booking->caseType()->isExternallyBinding()) { $portals[] = 'Die Änderung selbst muss im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ vorliegen – hier wird sie nur nachgetragen.'; } return [$calendar, $portals]; } /** * @return array */ private static function snapshot(Booking $booking): array { return [ 'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(), 'guests' => $booking->guests, 'extras' => (array) ($booking->extras ?? []), 'quote' => $booking->quote, 'total' => $booking->total, 'deposit' => $booking->deposit, 'balance_due_on' => $booking->balance_due_on?->toDateString(), 'tourist_tax_persons' => $booking->tourist_tax_persons, ]; } /** * @param array $before * @param array $after * @return list */ private static function summary(array $before, array $after): array { $date = fn (?string $value): string => $value ? CarbonImmutable::parse($value)->format('d.m.Y') : '–'; $lines = []; if ($before['arrival'] !== $after['arrival'] || $before['departure'] !== $after['departure']) { $lines[] = 'Zeitraum '.$date($before['arrival']).'–'.$date($before['departure']).' → '.$date($after['arrival']).'–'.$date($after['departure']); } if ($before['guests'] !== $after['guests']) { $lines[] = 'Personen '.($before['guests'] ?? '?').' → '.($after['guests'] ?? '?'); } if ((array) $before['extras'] != (array) $after['extras']) { $lines[] = 'Zusatzleistungen geändert'; } if ($before['total'] !== $after['total']) { $lines[] = 'Preis '.($before['total'] === null ? '–' : Money::format($before['total'])).' → '.($after['total'] === null ? '–' : Money::format($after['total'])); } return $lines === [] ? ['keine inhaltliche Änderung'] : $lines; } /** * @param array $preview * @return array */ private static function consequences(array $preview): array { return ['summary' => $preview['summary'], 'calendar' => $preview['calendar'], 'portals' => $preview['portals'], 'price' => $preview['price'], 'payment' => $preview['payment'], 'refund' => $preview['refund']]; } }