diff --git a/app/Actions/AutoOffer.php b/app/Actions/AutoOffer.php index 17bdf5e..5449a5f 100644 --- a/app/Actions/AutoOffer.php +++ b/app/Actions/AutoOffer.php @@ -4,7 +4,10 @@ use App\Availability\AvailabilityChecker; use App\Availability\CalendarClearance; +use App\Documents\DocumentComposer; +use App\Documents\DocumentFinding; use App\Enums\BookingStatus; +use App\Enums\DocumentKind; use App\Enums\ProcessingMode; use App\Exceptions\ReservationException; use App\Models\Booking; @@ -18,7 +21,8 @@ * * 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), - * and the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed). + * the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an + * offer composition without anything to confirm ({@see DocumentComposer}: template released, contract data complete). */ class AutoOffer { @@ -57,6 +61,9 @@ 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])]; + return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)]; } @@ -79,7 +86,7 @@ public function handle(Booking $booking): array } try { - $this->sendOffer->handle($booking->fresh()); + $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/ConfirmBooking.php b/app/Actions/ConfirmBooking.php index 05b5d1a..02fe4e8 100644 --- a/app/Actions/ConfirmBooking.php +++ b/app/Actions/ConfirmBooking.php @@ -6,11 +6,14 @@ use App\Documents\OfferTerms; use App\Documents\RentalContract; use App\Enums\BookingStatus; +use App\Enums\DocumentKind; use App\Enums\InboxMessageKind; use App\Exceptions\ReservationException; use App\Filament\Resources\Bookings\BookingResource; use App\Mail\BookingConfirmed; +use App\Mail\BookingDocumentation; use App\Models\Booking; +use App\Process\CaseLog; use App\Support\Inbox; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; @@ -84,18 +87,28 @@ public function bind(Booking $booking): void * * @return bool whether the guest has the confirmation (true when no mail was requested) */ - public function deliver(Booking $booking, bool $notifyGuest = true): bool + public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKind $kind = null): bool { $booking->loadMissing(['guest', 'property']); + $kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Confirmation; try { - $this->contract->generate($booking); + $created = $booking->contract_path === null; + $this->contract->generate($booking, kind: $kind); + if ($created) { + CaseLog::record($booking, 'document', $kind->getLabel().' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: [ + 'kind' => $kind->value, + 'template' => $booking->offer_terms['template'] ?? null, + 'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])), + 'pdf_sha256' => $booking->contract_pdf_sha256, + ]); + } if (! $notifyGuest) { return true; } - Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking)); + Mail::to($booking->guest->email, $booking->guest->full_name)->send($kind === DocumentKind::ExternalRecord ? new BookingDocumentation($booking) : new BookingConfirmed($booking)); $booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save(); return true; diff --git a/app/Actions/ProvideGuestContact.php b/app/Actions/ProvideGuestContact.php index 096ff01..61bcedf 100644 --- a/app/Actions/ProvideGuestContact.php +++ b/app/Actions/ProvideGuestContact.php @@ -8,8 +8,8 @@ use App\Exceptions\ReservationException; use App\Models\Booking; use App\Models\Guest; -use App\Process\CaseAutomation; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\DB; /** * The guest's contact data arrived (portal message, e-mail, phone) and is entered on the booking. The landlord chooses @@ -22,7 +22,7 @@ class ProvideGuestContact public const MANUAL = 'manual'; - public function __construct(private ConfirmBooking $confirm, private SendOffer $offer) {} + public function __construct(private ConfirmBooking $confirm, private AutoOffer $autoOffer, private SendBookingDocuments $documents) {} /** * @param array $contact first_name, last_name, email, phone, street, postal_code, city, country @@ -62,22 +62,28 @@ public function handle(Booking $booking, array $contact, string $process = self: $booking->update(['processing_mode' => ProcessingMode::Automatic]); if (in_array($booking->status, BookingStatus::occupying(), true)) { - $missing = app(CaseAutomation::class)->documentBlockers($booking); - if ($missing !== []) { - throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen können noch nicht automatisch versendet werden: '.implode(' ', $missing)); + $reasons = $this->documents->automatically($booking); + if ($reasons !== []) { + throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons)); } - $this->confirm->deliver($booking); - return 'Kontaktdaten gespeichert, Vertrag gesendet'; + return 'Kontaktdaten gespeichert, Unterlagen gesendet'; } if ($booking->intake === IntakeKind::Booking) { - $this->confirm->handle($booking); + DB::transaction(fn () => $this->confirm->bind($booking)); + $reasons = $this->documents->automatically($booking->fresh()); + if ($reasons !== []) { + throw new ReservationException('Kontaktdaten gespeichert und Buchung bestätigt. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons)); + } - return 'Kontaktdaten gespeichert, Buchung bestätigt und Vertrag gesendet'; + return 'Kontaktdaten gespeichert, Buchung bestätigt und Unterlagen gesendet'; } - $this->offer->handle($booking); + $reasons = $this->autoOffer->handle($booking); + if ($reasons !== []) { + throw new ReservationException('Kontaktdaten gespeichert. Das Angebot wird noch nicht automatisch gesendet: '.implode(' ', $reasons)); + } return 'Kontaktdaten gespeichert, Angebot gesendet'; } diff --git a/app/Actions/SendBookingDocuments.php b/app/Actions/SendBookingDocuments.php new file mode 100644 index 0000000..a9f5bbd --- /dev/null +++ b/app/Actions/SendBookingDocuments.php @@ -0,0 +1,113 @@ + $changes + */ + public function compose(Booking $booking, array $changes = []): DocumentComposition + { + return $this->composer->compose($booking, self::kindFor($booking), $changes); + } + + /** + * The automatic run: sends when the composition allows it. + * + * @return list why nothing was sent (empty: sent or nothing to send) + */ + public function automatically(Booking $booking): array + { + if ($booking->confirmation_sent_at !== null) { + return []; + } + + $composition = $this->compose($booking); + if (! $composition->canSendAutomatically()) { + return [...$composition->blockers(), ...array_map(fn (string $point): string => 'Bitte prüfen: '.$point, $composition->toConfirm())]; + } + + return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).']; + } + + /** + * Sending by hand after the landlord saw the composition. + * + * @param array $changes contract_template_id, annex_ids + * @return bool whether the guest has the documents + * + * @throws ReservationException + */ + public function handle(Booking $booking, array $changes = [], bool $acknowledged = false): bool + { + if (! $booking->isBinding()) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'mit Unterlagen bestätigt'); + } + + $composition = $this->compose($booking, $changes); + if ($composition->blockers() !== []) { + throw new ReservationException(implode(' ', $composition->blockers())); + } + if (! $composition->canSendByHand($acknowledged)) { + throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $composition->toConfirm())); + } + + return $this->send($booking, $composition, $acknowledged, automatic: false); + } + + /** + * The document kind of a binding case (a case whose documents the portal sends has none from us). + */ + public static function kindFor(Booking $booking): DocumentKind + { + $kind = DocumentKind::forCase($booking); + + return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord], true) ? $kind : DocumentKind::Confirmation; + } + + private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool + { + $lock = Cache::lock('booking-documents-'.$booking->id, 120); + if (! $lock->get()) { + throw new ReservationException('Die Unterlagen werden gerade versendet. Bitte kurz warten und die Seite neu laden.'); + } + + try { + $booking->refresh(); + if ($booking->confirmation_sent_at !== null) { + return true; + } + + if (! $composition->termsFrozen && $booking->contract_path === null && $composition->terms !== null) { + $booking->update(['offer_terms' => $composition->terms]); + } + + if ($acknowledged && $composition->toConfirm() !== []) { + CaseLog::record($booking, 'document', 'Hinweise vor dem Versand bestätigt', data: ['confirmed' => $composition->toConfirm()]); + } + + return CaseLog::context(fn (): bool => $this->confirm->deliver($booking, kind: $composition->kind), actor: $automatic ? CaseLog::SYSTEM.' (automatisch)' : null); + } finally { + $lock->release(); + } + } +} diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index 7602113..3a18140 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -3,9 +3,11 @@ namespace App\Actions; use App\Availability\AvailabilityChecker; +use App\Documents\DocumentComposer; use App\Documents\OfferTerms; use App\Documents\RentalContract; use App\Enums\BookingStatus; +use App\Enums\DocumentKind; use App\Enums\InboxMessageKind; use App\Enums\QuoteLineType; use App\Exceptions\ReservationException; @@ -17,6 +19,7 @@ use App\Pricing\QuoteException; use App\Pricing\QuoteLine; use App\Pricing\StayRequest; +use App\Process\CaseLog; use App\Support\Inbox; use Carbon\CarbonImmutable; use Illuminate\Support\Arr; @@ -42,7 +45,12 @@ public function __construct( ) {} /** - * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list, guest?: array} $changes + * The offer is checked through its composition ({@see DocumentComposer}) like every other document: points the + * landlord has to confirm (e.g. an unreleased template, missing contract data, a request that by the settings + * reserves nothing) stop it unless `acknowledged` is set. `expected_version` makes a repeated call harmless: when + * another offer was sent in the meantime, nothing is sent again. + * + * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list, guest?: array, acknowledged?: bool, expected_version?: ?int} $changes * * @throws QuoteException * @throws ReservationException @@ -57,6 +65,11 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet'); } + $toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer, $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(); @@ -64,6 +77,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet'); } + if (isset($changes['expected_version']) && $booking->offer_version !== (int) $changes['expected_version']) { + throw new ReservationException('Inzwischen wurde schon ein Angebot gesendet (Version '.$booking->offer_version.'). Es wurde nichts erneut gesendet.'); + } + $arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival); $departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure); @@ -75,7 +92,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t $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->quoteWithAdjustment($booking, $stay, $adjustment, $adjustmentLabel); + $quote = $this->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'])); @@ -105,6 +122,14 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t $booking->refresh(); $this->contract->generate($booking, draft: true); + CaseLog::record($booking, 'document', 'Angebot Version '.$booking->offer_version.' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: array_filter([ + 'kind' => DocumentKind::Offer->value, + 'template' => $booking->offer_terms['template'] ?? null, + 'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])), + 'pdf_sha256' => $booking->offer_pdf_sha256, + 'offer_hash' => $booking->offer_hash, + 'confirmed' => $toConfirm, + ])); if ($sendMail) { $this->deliver($booking); @@ -155,7 +180,7 @@ public function offerUrl(Booking $booking): string * * @throws QuoteException */ - private function quoteWithAdjustment(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote + public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote { $quote = $this->calculator->calculate($booking->property, $stay); if ($adjustment === 0) { diff --git a/app/Documents/ContractPlaceholders.php b/app/Documents/ContractPlaceholders.php index 905bdc9..3dc2789 100644 --- a/app/Documents/ContractPlaceholders.php +++ b/app/Documents/ContractPlaceholders.php @@ -106,10 +106,10 @@ private static function values(Booking $booking, array $propertyData): array 'anreise_datum' => $booking->arrival->format('d.m.Y'), 'abreise_datum' => $booking->departure->format('d.m.Y'), 'naechte' => (string) $booking->nights(), - 'personen' => (string) $booking->guests, - 'gesamtpreis' => Money::format($booking->total), - 'anzahlung' => Money::format($booking->deposit), - 'restzahlung' => Money::format($booking->total - $booking->deposit), + 'personen' => $booking->guests !== null ? (string) $booking->guests : null, + 'gesamtpreis' => $booking->total !== null ? Money::format($booking->total) : null, + 'anzahlung' => $booking->deposit !== null ? Money::format($booking->deposit) : null, + 'restzahlung' => $booking->total !== null && $booking->deposit !== null ? Money::format($booking->total - $booking->deposit) : null, 'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'), 'buchungsnummer' => $booking->reference, 'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'), diff --git a/app/Documents/DocumentComposer.php b/app/Documents/DocumentComposer.php new file mode 100644 index 0000000..b653495 --- /dev/null +++ b/app/Documents/DocumentComposer.php @@ -0,0 +1,404 @@ + $changes adjustments of the landlord (offer: dates, guests, promo code, price adjustment + * in cents, validity, message, guest data; all kinds: contract_template_id, annex_ids) + */ + public function compose(Booking $booking, ?DocumentKind $kind = null, array $changes = []): DocumentComposition + { + $booking->loadMissing(['guest', 'property', 'originChannel', 'importChannel']); + $kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Internal; + $findings = []; + + $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)]; + } + + $frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms))); + $explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null); + $template = match (true) { + $frozen => isset($booking->offer_terms['template']['id']) ? ContractTemplate::query()->find($booking->offer_terms['template']['id']) : null, + default => OfferTerms::templateFor($booking, $explicitTemplate ? $changes['contract_template_id'] : null), + }; + $terms = match (true) { + ! $kind->isForGuests() => null, + $frozen => $booking->offer_terms, + default => OfferTerms::capture($template, $draft, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null), + }; + $draft->offer_terms = $terms; + + $findings = [...$findings, ...$this->commonFindings($booking, $draft, $kind, $template, $frozen)]; + if ($kind === DocumentKind::ExternalRecord) { + $findings = [...$findings, ...$this->externalFindings($booking, $template, $terms, $frozen)]; + } + if ($kind === DocumentKind::Confirmation) { + $findings = [...$findings, ...$this->confirmationFindings($booking)]; + } + + return new DocumentComposition( + kind: $kind, + draft: $draft, + intakeLabel: explode(' · ', CaseActivities::situation($booking))[0], + priceLines: array_values(array_map(fn (array $line): array => ['label' => (string) $line['label'], 'amount' => (int) $line['amount']], (array) ($draft->quote['lines'] ?? []))), + priceSource: $this->priceSource($booking, $draft, $kind), + services: $this->services($draft), + cancellation: $this->cancellation($terms, $kind), + template: $template, + templateSource: $this->templateSource($booking, $frozen, $explicitTemplate), + annexes: array_values(array_map(fn (array $annex): array => ['id' => (int) $annex['id'], 'label' => $annex['name'].' (Version '.$annex['version'].')'], (array) ($terms['annexes'] ?? []))), + terms: $terms, + termsFrozen: $frozen, + findings: $findings, + ); + } + + /** + * Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will. + * + * @param array $changes + * @return list + */ + private function prepareOffer(Booking $booking, Booking $draft, array $changes): array + { + $findings = []; + + 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().').'); + } + + try { + $arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival); + $departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure); + $guests = (int) ($changes['guests'] ?? $booking->guests); + $promo = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code; + $adjustment = (int) ($changes['price_adjustment'] ?? 0); + $label = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag'); + $quote = $this->offer->quoteFor($booking, new StayRequest($arrival, $departure, max(1, $guests), $booking->extras ?? [], $promo), $adjustment, $label); + + $draft->forceFill([ + 'arrival' => $arrival->toDateString(), + 'departure' => $departure->toDateString(), + 'guests' => $quote->guests, + 'promo_code' => $quote->promoCodeApplied ? $promo : null, + 'quote' => $quote->toArray(), + 'total' => $quote->total(), + 'deposit' => $quote->deposit(), + 'balance_due_on' => $quote->balanceDueOn->toDateString(), + ]); + + if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) { + $findings[] = DocumentFinding::blocker('Der Zeitraum ist nicht mehr frei.'); + } + } catch (QuoteException $exception) { + $findings[] = DocumentFinding::blocker('Preis: '.$exception->getMessage()); + } catch (Throwable) { + $findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.'); + } + + $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, + 'offer_sent_at' => now(), + 'offer_message' => $changes['offer_message'] ?? $booking->offer_message, + ]); + + 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); + } + if ($booking->offer_version > 0) { + $findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.'); + } + + return $findings; + } + + /** + * @return list + */ + private function commonFindings(Booking $booking, Booking $draft, DocumentKind $kind, ?ContractTemplate $template, bool $frozen): array + { + if (! $kind->isForGuests()) { + return [DocumentFinding::info('Für diesen Vorgang geht kein Dokument an Gäste.')]; + } + + $findings = []; + if (! $kind->isAvailable()) { + $findings[] = DocumentFinding::blocker('„'.$kind->getLabel().'“ kann erst mit einem späteren Ausbauschritt versendet werden; die Arbeitsfassung ist vorbereitet.'); + } + if ($draft->guest === null) { + $findings[] = DocumentFinding::blocker('Name und Kontaktdaten des Gastes fehlen.'); + } elseif (blank($draft->guest->email)) { + $findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.'); + } + if ($kind !== DocumentKind::Offer && $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) { + $findings[] = DocumentFinding::info('Bereits gesendet am '.$booking->confirmation_sent_at->format('d.m.Y, H:i').' Uhr. Erneutes Senden schickt dieselben Unterlagen.'); + } + + if ($frozen) { + return $findings; + } + + if ($kind->isAvailable() && ! DocumentReleases::isReleased($kind)) { + $findings[] = DocumentFinding::confirm('Die Texte für „'.$kind->getLabel().'“ sind eine Arbeitsfassung und noch nicht freigegeben (So arbeite ich › Dokumente).'); + } + if ($template !== null && ! $template->isReleased()) { + $findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist noch nicht für Gäste freigegeben (Vorlagen › Freigabe).'); + } + $missing = $this->missingPlaceholders($draft); + if ($missing !== []) { + $findings[] = DocumentFinding::confirm('Im Vertragstext fehlen Angaben, sie erscheinen als [name?]: '.implode(', ', $missing).'.'); + } + + return $findings; + } + + /** + * Bookings already binding on a portal: no acceptance link, the portal price counts, and the template must not add + * obligations the guest did not accept there (E-004). + * + * @param array|null $terms + * @return list + */ + private function externalFindings(Booking $booking, ?ContractTemplate $template, ?array $terms, bool $frozen): array + { + $channel = $booking->processChannel()?->name ?? 'dem Portal'; + $findings = [DocumentFinding::info('Kein Annahmelink: Die Buchung ist bei '.$channel.' bereits verbindlich zustande gekommen.')]; + + if ($frozen) { + return $findings; + } + + if ($template === null) { + $findings[] = DocumentFinding::confirm('Für Buchungen über '.$channel.' ist keine eigene Vorlage hinterlegt. Die Unterlagen enthielten Ihre Mietbedingungen der Webseite – ihnen hat der Gast bei '.$channel.' nicht zugestimmt.'); + } elseif (! $template->confirmsPortalTerms()) { + $findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist nicht als Wiedergabe der Bedingungen von '.$channel.' bestätigt. Zusätzliche Pflichten gelten nur, wenn der Gast ihnen dort zugestimmt hat.'); + $fees = $this->fees($terms); + if ($fees !== []) { + $findings[] = DocumentFinding::confirm('Gebühren in der Vorlage, die bei '.$channel.' nicht nachweislich vereinbart sind: '.implode('; ', $fees).'.'); + } + } + + if ($booking->process()->payments() === Responsibility::Portal && $this->mentionsPaymentsToUs($terms)) { + $findings[] = DocumentFinding::confirm('Die Vorlage nennt Zahlungen an Sie (Anzahlung/Restzahlung), laut Einstellung zahlt der Gast über '.$channel.'.'); + } + + return $findings; + } + + /** + * @return list + */ + private function confirmationFindings(Booking $booking): array + { + return $booking->accepted_at !== null + ? [DocumentFinding::info('Bedingungen wie im angenommenen Angebot vom '.$booking->accepted_at->format('d.m.Y').' (unverändert).')] + : []; + } + + private function priceSource(Booking $booking, Booking $draft, DocumentKind $kind): string + { + 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', + $booking->accepted_at !== null => 'wie im angenommenen Angebot', + default => 'aus Ihren Preisen berechnet', + }; + } + + private function templateSource(Booking $booking, bool $frozen, bool $explicit): string + { + if ($frozen) { + return $booking->offer_version > 0 ? 'im angenommenen Angebot festgehalten' : 'mit den Unterlagen festgehalten'; + } + if ($explicit) { + return 'für diesen Vorgang gewählt'; + } + + $source = $this->settings->forBooking($booking)->source(ProcessSetting::ContractTemplate); + + return match ($source) { + ProcessProfile::CHANNEL => 'eingestellt für '.$booking->processChannel()?->name.' ('.($booking->intake?->getLabel() ?? '').')', + ProcessProfile::PROPERTY => 'eingestellt für die Wohnung '.$booking->property->name, + ProcessProfile::TENANT => 'Ihre Standardeinstellung', + default => 'keine Vorlage eingestellt', + }; + } + + /** + * @return list + */ + private function services(Booking $draft): array + { + $extras = array_filter((array) ($draft->extras ?? []), fn ($quantity): bool => (int) $quantity > 0); + if ($extras === []) { + return []; + } + + return Extra::query()->whereIn('id', array_keys($extras))->orderBy('name')->get() + ->map(fn (Extra $extra): string => $extra->name.((int) $extras[$extra->id] > 1 ? ' × '.$extras[$extra->id] : '')) + ->values()->all(); + } + + /** + * @param array|null $terms + * @return list + */ + private function cancellation(?array $terms, DocumentKind $kind): array + { + $lines = []; + if ($kind === DocumentKind::ExternalRecord) { + $lines[] = 'Maßgeblich ist die bei der Buchung über das Portal vereinbarte Regel.'; + } + + $policy = $terms['cancellation_policy'] ?? null; + if (is_array($policy) && ! empty($policy['tiers'])) { + return [...$lines, ...CancellationPolicy::describe($policy)]; + } + if (filled($terms['texts']['stay.cancellation'] ?? null)) { + return [...$lines, 'Laut Text „Rücktritt / Stornierung“ der Vorlage bzw. Webseite (keine Staffel hinterlegt).']; + } + + return $terms === null ? $lines : [...$lines, 'Keine Stornoregel hinterlegt.']; + } + + /** + * Placeholders of the contract text that have no value for this case. + * + * @return list + */ + private function missingPlaceholders(Booking $draft): array + { + $terms = (array) ($draft->offer_terms ?? []); + $data = (array) ($terms['property_data'] ?? []); + $texts = array_filter([ + $terms['document']['body'] ?? null, + $terms['document']['annex_body'] ?? null, + ...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])), + ]); + + return array_values(array_unique(array_merge(...array_map(fn (string $html): array => ContractPlaceholders::missing($html, $draft, $data), $texts ?: [''])))); + } + + /** + * Fees a template states: the replacement fee of its cancellation rule and amounts written in its texts. + * + * @param array|null $terms + * @return list + */ + private function fees(?array $terms): array + { + $fees = []; + $policy = $terms['cancellation_policy'] ?? null; + if (is_array($policy) && ($policy['replacement_fee'] ?? null) !== null) { + $fees[] = 'Ersatzmieter-Gebühr '.Money::format((int) $policy['replacement_fee']); + } + if (is_array($policy) && ! empty($policy['tiers'])) { + $fees[] = 'Stornokosten nach Staffel ('.$policy['name'].')'; + } + + $text = strip_tags(implode(' ', $this->templateTexts($terms))); + preg_match_all('/\d{1,3}(?:\.\d{3})*(?:,\d{1,2})?\s?(?:€|EUR\b|Euro\b)/u', html_entity_decode($text), $amounts); + foreach (array_unique($amounts[0]) as $amount) { + $fees[] = trim($amount).' (im Text)'; + } + + return $fees; + } + + /** + * @param array|null $terms + */ + private function mentionsPaymentsToUs(?array $terms): bool + { + $text = implode(' ', $this->templateTexts($terms)); + foreach (self::PAYMENT_PLACEHOLDERS as $placeholder) { + if (preg_match('/\{\{\s*'.$placeholder.'\s*\}\}/i', $text) === 1) { + return true; + } + } + + return false; + } + + /** + * The texts a template contributes (not the website texts it falls back to). + * + * @param array|null $terms + * @return list + */ + private function templateTexts(?array $terms): array + { + if ($terms === null || ! isset($terms['template'])) { + return []; + } + + $template = ContractTemplate::query()->find($terms['template']['id']); + + return array_values(array_filter([ + $terms['document']['body'] ?? null, + $terms['document']['annex_body'] ?? null, + ...array_values($template?->overrides() ?? []), + ...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])), + ])); + } + + /** + * @param array $changes + * @return array + */ + private static function guestChanges(array $changes): array + { + $guest = (array) ($changes['guest'] ?? []); + + return array_map(fn ($value): ?string => filled($value) ? trim((string) $value) : null, array_filter(Arr::only($guest, ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']), 'filled')); + } +} diff --git a/app/Documents/DocumentComposition.php b/app/Documents/DocumentComposition.php new file mode 100644 index 0000000..15e2a26 --- /dev/null +++ b/app/Documents/DocumentComposition.php @@ -0,0 +1,129 @@ + $priceLines + * @param list $services + * @param list $cancellation + * @param list $annexes + * @param array|null $terms the terms the document freezes (null: the website texts apply live) + * @param list $findings + */ + public function __construct( + public readonly DocumentKind $kind, + public readonly Booking $draft, + public readonly string $intakeLabel, + public readonly array $priceLines, + public readonly string $priceSource, + public readonly array $services, + public readonly array $cancellation, + public readonly ?ContractTemplate $template, + public readonly string $templateSource, + public readonly array $annexes, + public readonly ?array $terms, + public readonly bool $termsFrozen, + public readonly array $findings, + ) {} + + public function recipientName(): ?string + { + return $this->draft->guest?->full_name; + } + + public function recipientEmail(): ?string + { + return filled($this->draft->guest?->email) ? $this->draft->guest->email : null; + } + + /** + * @return list + */ + public function blockers(): array + { + return $this->messages(DocumentFinding::BLOCKER); + } + + /** + * @param list $except codes of findings left out + * @return list + */ + public function toConfirm(array $except = []): array + { + return $this->messages(DocumentFinding::CONFIRM, $except); + } + + /** + * @return list + */ + public function information(): array + { + return $this->messages(DocumentFinding::INFO); + } + + /** + * The automatic run sends only a document without blockers and without anything the landlord has to confirm. + */ + public function canSendAutomatically(): bool + { + return $this->blockers() === [] && $this->toConfirm() === []; + } + + /** + * By hand: no blockers, and every point to confirm was confirmed. + */ + public function canSendByHand(bool $acknowledged): bool + { + return $this->blockers() === [] && ($this->toConfirm() === [] || $acknowledged); + } + + /** + * The template as the landlord reads it. + */ + public function templateLabel(): string + { + if ($this->terms !== null && isset($this->terms['template']['name'])) { + return $this->terms['template']['name'].' (Version '.$this->terms['template']['version'].')'; + } + + return $this->template?->label() ?? 'Texte der Webseite'; + } + + /** + * What is stored about the document in the case history. + * + * @return array + */ + public function record(): array + { + return [ + 'kind' => $this->kind->value, + 'template' => $this->terms['template'] ?? null, + 'annexes' => array_map(fn (array $annex): string => $annex['label'], $this->annexes), + 'recipient' => $this->recipientEmail(), + 'total' => $this->draft->total, + 'price_source' => $this->priceSource, + ]; + } + + /** + * @param list $except + * @return list + */ + private function messages(string $severity, array $except = []): array + { + return array_values(array_map(fn (DocumentFinding $finding): string => $finding->message, array_filter($this->findings, fn (DocumentFinding $finding): bool => $finding->severity === $severity && ! in_array($finding->code, $except, true)))); + } +} diff --git a/app/Documents/DocumentFinding.php b/app/Documents/DocumentFinding.php new file mode 100644 index 0000000..0fcdaf1 --- /dev/null +++ b/app/Documents/DocumentFinding.php @@ -0,0 +1,41 @@ +value] ?? null; + + return is_array($entry) ? (bool) ($entry['released'] ?? false) : $kind->releasedByDefault(); + } + + /** + * @return array{released: bool, by: ?string, at: ?string}|null the landlord's decision, null when none was made + */ + public static function decision(DocumentKind $kind, ?Tenant $tenant = null): ?array + { + $entry = self::entries($tenant)[$kind->value] ?? null; + + return is_array($entry) ? ['released' => (bool) ($entry['released'] ?? false), 'by' => $entry['by'] ?? null, 'at' => $entry['at'] ?? null] : null; + } + + /** + * Stores the decision for one kind; an unchanged decision keeps its date and author. + */ + public static function set(DocumentKind $kind, bool $released, string $actor, ?Tenant $tenant = null): void + { + $tenant ??= Settings::tenant(); + if ($tenant === null || self::isReleased($kind, $tenant) === $released && self::decision($kind, $tenant) !== null) { + return; + } + + $entries = self::entries($tenant); + $entries[$kind->value] = ['released' => $released, 'by' => $actor, 'at' => now()->toIso8601String()]; + $tenant->update(['document_releases' => $entries]); + } + + /** + * @return array + */ + private static function entries(?Tenant $tenant): array + { + return (array) (($tenant ?? Settings::tenant())?->document_releases ?? []); + } +} diff --git a/app/Documents/RentalContract.php b/app/Documents/RentalContract.php index 2c36fdb..51ed7d1 100644 --- a/app/Documents/RentalContract.php +++ b/app/Documents/RentalContract.php @@ -2,50 +2,73 @@ namespace App\Documents; +use App\Enums\DocumentKind; use App\Models\Booking; use App\Models\Site; use Barryvdh\DomPDF\Facade\Pdf; use Illuminate\Support\Facades\Storage; /** - * The rental contract as PDF. As a draft it is part of the offer (offer_path, one file per offer version); - * the final contract is generated at confirmation (contract_path). Both are stored, so later changes of - * texts or prices do not alter a document the guest already received. + * The PDF of a case's document. As a draft it is part of the offer (offer_path, one file per offer version); the + * document of record – rental contract, booking documentation of a portal booking or stay confirmation, depending on + * the case – is generated once when it is sent (contract_path). Both are stored, so later changes of texts or prices do + * not alter a document the guest already received. */ class RentalContract { private const DISK = 'local'; - public function generate(Booking $booking, bool $draft = false): string + public function generate(Booking $booking, bool $draft = false, ?DocumentKind $kind = null): string { $booking->loadMissing(['guest', 'property']); + $kind = $draft ? DocumentKind::Offer : ($kind ?? DocumentKind::forCase($booking) ?? DocumentKind::Confirmation); $filename = $draft - ? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf" - : "contracts/Mietvertrag-{$booking->reference}.pdf"; - $path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename); + ? "Angebot-{$booking->reference}-v{$booking->offer_version}.pdf" + : "{$kind->fileName()}-{$booking->reference}.pdf"; + $path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/{$filename}"; - // The logo is embedded as a file: the PDF is rendered on the server and must not depend on - // fetching anything over the network. Each website has its own (A14). - $logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO); - - // The final contract is a document of record: once stored it is never rewritten (confirmation resends reuse it). + // The document of record is never rewritten once stored (confirmation resends reuse it). if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) { return $booking->contract_path; } - $document = OfferTerms::document($booking); - $pdf = Pdf::loadView($document !== null ? 'pdf.contract-document' : 'pdf.contract', [ - 'booking' => $booking, - 'draft' => $draft, - 'logo' => $logo, - 'document' => $document, - ])->setPaper('a4')->output(); + $pdf = $this->render($booking, $kind, $draft); Storage::disk(self::DISK)->put($path, $pdf); $booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]); return $path; } + /** + * The PDF bytes of a document, without storing anything (also used for previews of a composition). + */ + public function render(Booking $booking, DocumentKind $kind, bool $draft = false): string + { + [$view, $data] = $this->view($booking, $kind, $draft); + + return Pdf::loadView($view, $data)->setPaper('a4')->output(); + } + + /** + * The view and its data that make up the document. + * + * @return array{0: string, 1: array} + */ + public function view(Booking $booking, DocumentKind $kind, bool $draft = false): array + { + // The logo is embedded as a file: the PDF is rendered on the server and must not depend on + // fetching anything over the network. Each website has its own (A14). + $logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO); + $document = $kind === DocumentKind::StayConfirmation ? null : OfferTerms::document($booking); + $view = match (true) { + $kind === DocumentKind::StayConfirmation => 'pdf.stay-confirmation', + $document !== null => 'pdf.contract-document', + default => 'pdf.contract', + }; + + return [$view, ['booking' => $booking, 'draft' => $draft, 'logo' => $logo, 'document' => $document, 'kind' => $kind]]; + } + public function absolutePath(Booking $booking, bool $draft = false): ?string { $path = $draft ? $booking->offer_path : $booking->contract_path; diff --git a/app/Enums/DocumentKind.php b/app/Enums/DocumentKind.php new file mode 100644 index 0000000..65ac3c9 --- /dev/null +++ b/app/Enums/DocumentKind.php @@ -0,0 +1,121 @@ + 'Angebot mit Annahmelink', + self::Information => 'Auskunft unter Vorbehalt', + self::Confirmation => 'Buchungsbestätigung mit Mietvertrag', + self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)', + self::StayConfirmation => 'Aufenthaltsbestätigung (privat)', + self::Internal => 'Nur intern, kein Dokument an Gäste', + }; + } + + /** + * What the landlord reads about this kind on the settings page. + */ + 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::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. Folgt mit Paket 6.', + self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.', + }; + } + + /** + * The document a case needs at its current stage, or null when nobody needs one from us (e.g. the portal sends it). + */ + public static function forCase(Booking $booking): ?self + { + $profile = $booking->process(); + + return match (true) { + $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, + default => self::Offer, + }; + } + + /** + * Whether the guest makes the contract by accepting this document (only the offer carries an acceptance link). + */ + public function hasAcceptanceLink(): bool + { + return $this === self::Offer; + } + + /** + * Whether a rental contract is part of this document. + */ + public function containsContract(): bool + { + return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true); + } + + /** + * Whether this kind can be sent with the current packages (the others exist as working drafts only). + */ + public function isAvailable(): bool + { + return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true); + } + + /** + * Whether the texts of this kind count as released while the landlord has not decided otherwise: the offer and the + * confirmation are the documents in use since the start; every new kind starts as a working draft. + */ + public function releasedByDefault(): bool + { + return in_array($this, [self::Offer, self::Confirmation], true); + } + + /** + * Whether this kind goes to guests at all. + */ + public function isForGuests(): bool + { + return $this !== self::Internal; + } + + /** + * File name prefix of the stored PDF. + */ + public function fileName(): string + { + return match ($this) { + self::Offer => 'Angebot', + self::Information => 'Auskunft', + self::Confirmation => 'Mietvertrag', + self::ExternalRecord => 'Buchungsunterlagen', + self::StayConfirmation => 'Aufenthaltsbestaetigung', + self::Internal => 'Intern', + }; + } +} diff --git a/app/Filament/Forms/DocumentCompositionFields.php b/app/Filament/Forms/DocumentCompositionFields.php new file mode 100644 index 0000000..63b24e4 --- /dev/null +++ b/app/Filament/Forms/DocumentCompositionFields.php @@ -0,0 +1,110 @@ + */ + private static array $compositions = []; + + /** + * @param Closure(Get): array $changes the adjustments currently in the form + * @return list + */ + public static function make(Booking $booking, DocumentKind $kind, Closure $changes, ?Closure $visible = null): array + { + $compose = fn (Get $get): DocumentComposition => self::compose($booking, $kind, $changes($get)); + + return [ + View::make('filament.document-composition') + ->viewData(fn (Get $get): array => self::viewData($compose($get), $changes($get))), + Checkbox::make('acknowledged') + ->label('Ich habe die Hinweise geprüft und möchte das Dokument so senden.') + ->visible(fn (Get $get): bool => ($visible === null || $visible($get)) && $compose($get)->toConfirm() !== []) + ->accepted(), + ]; + } + + /** + * One composition per form state and request (the view and the confirmation box both need it). + * + * @param array $changes + */ + public static function compose(Booking $booking, DocumentKind $kind, array $changes): DocumentComposition + { + $key = $booking->id.':'.$kind->value.':'.md5(serialize($changes)).':'.$booking->updated_at?->getTimestamp(); + + return self::$compositions[$key] ??= app(DocumentComposer::class)->compose($booking, $kind, $changes); + } + + /** + * @param array $changes + * @return array + */ + private static function viewData(DocumentComposition $composition, array $changes): array + { + $user = auth()->user(); + + return [ + 'composition' => $composition, + 'expert' => $user instanceof User && $user->adminMode() === AdminMode::Expert, + 'mailPreview' => self::mailPreview($composition), + 'documentPreview' => self::documentPreview($composition), + 'pdfUrl' => route('filament.admin.document-preview', ['booking' => $composition->draft->getRouteKey(), 'kind' => $composition->kind->value, 'changes' => base64_encode(json_encode($changes) ?: '[]')]), + ]; + } + + private static function mailPreview(DocumentComposition $composition): string + { + $draft = $composition->draft; + if ($draft->guest === null) { + return '

Keine Vorschau: Der Gast ist noch nicht bekannt.

'; + } + + try { + return match ($composition->kind) { + DocumentKind::Offer => (new OfferMade($draft, '#'))->render(), + DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(), + default => (new BookingConfirmed($draft))->render(), + }; + } catch (Throwable $exception) { + report($exception); + + return '

Die Vorschau der E-Mail ist gerade nicht möglich.

'; + } + } + + private static function documentPreview(DocumentComposition $composition): string + { + try { + [$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer); + + return view($view, $data)->render(); + } catch (Throwable $exception) { + report($exception); + + return '

Die Vorschau des Dokuments ist gerade nicht möglich.

'; + } + } +} diff --git a/app/Filament/Pages/HandlingSettings.php b/app/Filament/Pages/HandlingSettings.php index 63356c8..da65d90 100644 --- a/app/Filament/Pages/HandlingSettings.php +++ b/app/Filament/Pages/HandlingSettings.php @@ -2,6 +2,8 @@ namespace App\Filament\Pages; +use App\Documents\DocumentReleases; +use App\Enums\DocumentKind; use App\Enums\IntakeKind; use App\Enums\ProcessSetting; use App\Enums\UserRole; @@ -12,7 +14,9 @@ use App\Models\Tenant; use App\Support\Settings; use BackedEnum; +use Carbon\CarbonImmutable; use Filament\Actions\Action; +use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Pages\Page; use Filament\Schemas\Components\Actions; @@ -63,7 +67,10 @@ public static function settings(): array public function mount(): void { - $this->form->fill(ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? []))); + $this->form->fill([ + ...ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? [])), + 'document_releases' => collect(self::releasableKinds())->mapWithKeys(fn (DocumentKind $kind): array => [$kind->value => DocumentReleases::isReleased($kind, $this->tenant())])->all(), + ]); } public function form(Schema $schema): Schema @@ -75,6 +82,17 @@ public function form(Schema $schema): Schema ->description('Gilt für alle Wohnungen und Portale, solange dort nichts anderes eingestellt ist. Neue Einstellungen gelten für neue Vorgänge; laufende Vorgänge behalten ihre Regeln.') ->columns(2) ->schema(ProcessSettingFields::make('', self::settings(), fn (ProcessSetting $setting): string => 'Grundeinstellung ('.$setting->describe($setting->default()).')')), + Section::make('Dokumente') + ->description('Welche Dokumente an Gäste gehen dürfen. Eine Arbeitsfassung wird nie automatisch versendet, von Hand nur nach ausdrücklicher Bestätigung im Vorgang. Vorlagen selbst geben Sie unter Vorlagen frei.') + ->schema([ + ...array_map(fn (DocumentKind $kind): Toggle => Toggle::make('document_releases.'.$kind->value) + ->label($kind->getLabel().' – freigegeben') + ->helperText(fn (): string => $kind->description().self::decisionNote($kind)), self::releasableKinds()), + Text::make(fn (): HtmlString => new HtmlString('
    '.collect(DocumentKind::cases()) + ->reject(fn (DocumentKind $kind): bool => in_array($kind, self::releasableKinds(), true) || ! $kind->isForGuests()) + ->map(fn (DocumentKind $kind): string => '
  • '.e($kind->getLabel()).': '.e($kind->description()).' '.e($kind->isAvailable() ? '(in Verwendung; Texte unter Webseite › Texte bzw. Vorlagen)' : '(Arbeitsfassung vorbereitet, noch nicht nutzbar)').'
  • ') + ->implode('').'
')), + ]), Section::make('Abweichungen') ->description('Wo Portale oder Wohnungen anders arbeiten. Ändern unter Portale bzw. Wohnungen (Expertenansicht).') ->collapsed() @@ -94,11 +112,33 @@ public function content(Schema $schema): Schema public function save(): void { - $this->tenant()->update(['process_defaults' => ProcessSettingFields::values($this->form->getState(), self::settings())]); + $state = $this->form->getState(); + $this->tenant()->update(['process_defaults' => ProcessSettingFields::values($state, self::settings())]); + foreach (self::releasableKinds() as $kind) { + DocumentReleases::set($kind, (bool) ($state['document_releases'][$kind->value] ?? false), (string) auth()->user()?->name, $this->tenant()); + } Notification::make()->title('Gespeichert')->body('Gilt für neue Vorgänge.')->success()->send(); } + /** + * Document kinds whose texts the landlord releases here: the new kinds that can already be sent. Offer and + * confirmation are in use since the start; the others are drafts of later packages. + * + * @return list + */ + public static function releasableKinds(): array + { + return array_values(array_filter(DocumentKind::cases(), fn (DocumentKind $kind): bool => $kind->isAvailable() && ! $kind->releasedByDefault())); + } + + private static function decisionNote(DocumentKind $kind): string + { + $decision = DocumentReleases::decision($kind); + + return $decision === null || $decision['at'] === null ? ' Bisher: Arbeitsfassung.' : ' Zuletzt geändert am '.CarbonImmutable::parse($decision['at'])->format('d.m.Y').' von '.$decision['by'].'.'; + } + /** * Every deviation of a property or a channel, in plain words. */ diff --git a/app/Filament/Resources/Bookings/Pages/CreateBooking.php b/app/Filament/Resources/Bookings/Pages/CreateBooking.php index 73a9ed7..7a89d2f 100644 --- a/app/Filament/Resources/Bookings/Pages/CreateBooking.php +++ b/app/Filament/Resources/Bookings/Pages/CreateBooking.php @@ -4,6 +4,7 @@ use App\Actions\ConfirmBooking; use App\Actions\CreateReservation; +use App\Actions\SendBookingDocuments; use App\Actions\TakeOverExternalBooking; use App\Exceptions\ReservationException; use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource; @@ -19,6 +20,7 @@ use Filament\Resources\Pages\CreateRecord; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\DB; /** * Entry of a new case that did not come through the website: a request (A1/A2) goes the same way as a website request, @@ -63,7 +65,16 @@ protected function handleRecordCreation(array $data): Model $booking = app(CreateReservation::class)->handle($property, $stay, $guest, source: 'manual', sendMails: $sendMails && ! ($data['confirm_immediately'] ?? false), originChannel: $channel); if ($data['confirm_immediately'] ?? false) { - app(ConfirmBooking::class)->handle($booking, notifyGuest: $sendMails && filled($booking->guest?->email)); + DB::transaction(fn () => app(ConfirmBooking::class)->bind($booking)); + if ($sendMails && filled($booking->guest?->email)) { + // The documents go out only when their composition needs no check; otherwise they wait on the case page. + $waiting = app(SendBookingDocuments::class)->automatically($booking->fresh()); + if ($waiting !== []) { + Notification::make()->title('Gebucht – Unterlagen noch nicht gesendet')->body(implode(' ', $waiting))->warning()->send(); + } + } else { + app(ConfirmBooking::class)->deliver($booking->fresh(), notifyGuest: false); + } } } catch (QuoteException|ReservationException $exception) { Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index e372883..bf87580 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -6,17 +6,21 @@ use App\Actions\ConfirmBooking; use App\Actions\DeclineBooking; use App\Actions\ProvideGuestContact; +use App\Actions\SendBookingDocuments; use App\Actions\SendOffer; use App\Actions\SetBookingStatus; use App\Documents\OfferTerms; use App\Documents\RentalContract; use App\Enums\AdminMode; use App\Enums\BookingStatus; +use App\Enums\DocumentKind; use App\Enums\IntakeKind; use App\Enums\ProcessingMode; +use App\Enums\Responsibility; use App\Exceptions\ReservationException; use App\Filament\Actions\AssignGuestAction; use App\Filament\Forms\Components\EuroInput; +use App\Filament\Forms\DocumentCompositionFields; use App\Filament\Resources\Bookings\BookingResource; use App\Models\Booking; use App\Models\ContractAnnex; @@ -24,18 +28,16 @@ use App\Models\Extra; use App\Models\User; use App\Pricing\PortalPrice; -use App\Pricing\PriceCalculator; use App\Pricing\QuoteException; -use App\Pricing\StayRequest; use App\Process\CaseActivities; use App\Process\CaseAutomation; use App\Process\CaseLog; use App\Support\Money; -use Carbon\CarbonImmutable; use Filament\Actions\Action; use Filament\Actions\ActionGroup; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DateTimePicker; +use Filament\Forms\Components\Hidden; use Filament\Forms\Components\Radio; use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; @@ -44,12 +46,14 @@ use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Resources\Pages\ViewRecord; +use Filament\Schemas\Components\Group; use Filament\Schemas\Components\Section; -use Filament\Schemas\Components\Text; use Filament\Schemas\Components\Utilities\Get; +use Filament\Schemas\Components\Utilities\Set; use Filament\Support\Icons\Heroicon; use Illuminate\Contracts\Support\Htmlable; -use Throwable; +use Illuminate\Support\Arr; +use Illuminate\Support\Facades\DB; /** * The case page. At the top only what matters now: the next step as one large button, "Beenden" and the switch between @@ -84,6 +88,7 @@ protected function getHeaderActions(): array $this->requestContactAction(), AssignGuestAction::make(), $this->confirmAction(), + $this->sendDocumentsAction(), $this->resendConfirmationAction(), $this->portalPriceAction(), $this->extendHoldAction(), @@ -125,10 +130,11 @@ private function sendOfferAction(): Action ->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') - ->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Angaben; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.') + ->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Zusammenstellung; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.') ->modalSubmitActionLabel('Senden') - ->modalWidth('3xl') + ->modalWidth('4xl') ->fillForm(fn (): array => [ + 'expected_version' => $this->record->offer_version, 'arrival' => $this->record->arrival->toDateString(), 'departure' => $this->record->departure->toDateString(), 'guests' => $this->record->guests, @@ -137,16 +143,14 @@ private function sendOfferAction(): Action '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, + 'annex_ids' => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [], 'guest' => $this->record->guest?->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']) ?? [], ]) ->schema([ - Section::make('So geht das Angebot hinaus')->schema([ - Text::make(fn (Get $get): string => $this->offerPricePreview($get)), - Text::make(fn (): string => 'Gast: '.$this->record->guestName().' · '.($this->record->guest?->email ?: 'keine E-Mail-Adresse')), - Text::make(fn (): string => 'Vertragsvorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite')), - Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3), - ]), - Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast')->collapsed()->schema([ + Hidden::make('expected_version'), + ...DocumentCompositionFields::make($this->record, DocumentKind::Offer, 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', 'contract_template_id', 'annex_ids', 'guest']))), + Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true), + Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast – die Zusammenstellung oben rechnet sofort neu.')->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), @@ -155,38 +159,81 @@ private function sendOfferAction(): Action 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), - ]), - Section::make('Vorlage und Anlagen')->schema([ - Select::make('contract_template_id') - ->label('Andere Vorlage für dieses Angebot') - ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) - ->placeholder('wie eingestellt'), - Select::make('annex_ids') - ->label('Anlagen') - ->multiple() - ->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()) - ->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []), + TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true), ]), + ...$this->templateFields(), DateTimePicker::make('valid_until') ->label('Angebot gültig bis') ->helperText(fn (): string => 'Eingestellt: '.$this->record->process()->holdHours().' Stunden. Bis dahin bleibt der Zeitraum reserviert.') ->seconds(false) ->after('now') - ->required(), + ->required() + ->live(onBlur: true), Section::make('Gast – so erscheint er im Vertrag')->columns(2)->schema([ - TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100), - TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100), - TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150), - TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20), - TextInput::make('guest.city')->label('Ort')->maxLength(100), - TextInput::make('guest.phone')->label('Telefon')->maxLength(50), + TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100)->live(onBlur: true), + TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100)->live(onBlur: true), + TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150)->live(onBlur: true), + TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20)->live(onBlur: true), + TextInput::make('guest.city')->label('Ort')->maxLength(100)->live(onBlur: true), + TextInput::make('guest.phone')->label('Telefon')->maxLength(50)->live(onBlur: true), ]), ]), ]) ->action(fn (array $data, SendOffer $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Angebot gesendet')); } + /** + * The documents of a binding case (confirmation with contract, or booking documentation of a portal booking), sent + * after the landlord saw their composition. + */ + private function sendDocumentsAction(): Action + { + return Action::make('sendDocuments') + ->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden') + ->icon(Heroicon::OutlinedPaperAirplane) + ->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null && $this->record->process()->documents() === Responsibility::Landlord) + ->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel()) + ->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.') + ->modalSubmitActionLabel('Senden') + ->modalWidth('4xl') + ->fillForm(fn (): array => ['annex_ids' => $this->record->contract_path === null && $this->record->offer_version === 0 ? (OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []) : null]) + ->schema(fn (): array => [ + ...DocumentCompositionFields::make($this->record, SendBookingDocuments::kindFor($this->record), fn (Get $get): array => $this->documentChanges(self::formState($get, ['contract_template_id', 'annex_ids']))), + Section::make('Anpassen')->description('Vorlage und Anlagen für diesen Vorgang.')->collapsed()->visible($this->record->contract_path === null && $this->record->offer_version === 0)->schema($this->templateFields()), + ]) + ->action(function (array $data, SendBookingDocuments $documents): void { + $this->runWorkflow(function () use ($data, $documents): void { + if (! $documents->handle($this->record, $this->documentChanges($data), (bool) ($data['acknowledged'] ?? false))) { + throw new ReservationException('Der Versand ist fehlgeschlagen (Details im Postfach). Sie können ihn über „Unterlagen erneut senden“ wiederholen.'); + } + }, 'Unterlagen gesendet'); + }); + } + + /** + * Choice of template and annexes for one case; changing the template proposes its annexes. + * + * @return list
+ */ + private function templateFields(): array + { + return [ + Section::make('Vorlage und Anlagen')->schema([ + Select::make('contract_template_id') + ->label('Andere Vorlage für diesen Vorgang') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label().($template->isReleased() ? '' : ' – nicht freigegeben')])->all()) + ->placeholder('wie eingestellt') + ->live() + ->afterStateUpdated(fn (Set $set, $state) => $set('annex_ids', OfferTerms::templateFor($this->record, $state)?->annexesFor($this->record)->pluck('id')->all() ?? [])), + Select::make('annex_ids') + ->label('Anlagen') + ->multiple() + ->live() + ->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()), + ]), + ]; + } + private function provideContactAction(): Action { return Action::make('provideContact') @@ -253,15 +300,40 @@ private function requestContactAction(): Action private function confirmAction(): Action { + $kind = fn (): DocumentKind => $this->record->intake === IntakeKind::Booking ? DocumentKind::ExternalRecord : DocumentKind::Confirmation; + return Action::make('confirm') ->label('Direkt verbindlich bestätigen') ->icon(Heroicon::OutlinedCheckCircle) ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) - ->requiresConfirmation() ->modalHeading('Buchung direkt bestätigen') ->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung schon anders verbindlich vereinbart wurde (z. B. am Telefon). Der Zeitraum wird fest belegt.') - ->schema([Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(fn (): bool => filled($this->record->guest?->email))]) - ->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(fn () => $confirm->handle($this->record, $data['notify']), 'Buchung bestätigt')); + ->modalSubmitActionLabel('Bestätigen') + ->modalWidth('4xl') + ->fillForm(fn (): array => ['notify' => filled($this->record->guest?->email)]) + ->schema(fn (): array => [ + Toggle::make('notify')->label('Unterlagen an den Gast senden')->live(), + Group::make(DocumentCompositionFields::make($this->record, $kind(), fn (Get $get): array => [], fn (Get $get): bool => (bool) $get('notify'))) + ->visible(fn (Get $get): bool => (bool) $get('notify')), + ]) + ->action(function (array $data, ConfirmBooking $confirm, SendBookingDocuments $documents) use ($kind): void { + $notify = (bool) ($data['notify'] ?? false); + $acknowledged = (bool) ($data['acknowledged'] ?? false); + + if ($notify) { + $composition = DocumentCompositionFields::compose($this->record, $kind(), []); + if (! $composition->canSendByHand($acknowledged)) { + Notification::make()->title('Nicht möglich')->body(implode(' ', [...$composition->blockers(), ...$composition->toConfirm()]))->danger()->send(); + + return; + } + } + + $this->runWorkflow(function () use ($confirm, $documents, $notify, $acknowledged): void { + DB::transaction(fn () => $confirm->bind($this->record)); + $notify ? $documents->handle($this->record->fresh(), [], $acknowledged) : $confirm->deliver($this->record->fresh(), notifyGuest: false); + }, 'Buchung bestätigt'); + }); } private function resendConfirmationAction(): Action @@ -273,13 +345,12 @@ private function resendConfirmationAction(): Action default => 'Bestätigung erneut senden', }) ->icon(Heroicon::OutlinedEnvelope) - ->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email)) + ->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email) && ($this->record->confirmation_sent_at !== null || $this->record->confirmation_failed_at !== null)) ->requiresConfirmation() - ->modalDescription(fn (): string => 'Der Gast erhält die Buchungsbestätigung mit dem Vertrag (Vorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite').').') + ->modalDescription(fn (): string => 'Der Gast erhält dieselben Unterlagen noch einmal (Vorlage: '.(isset($this->record->offer_terms['template']['name']) ? $this->record->offer_terms['template']['name'].', Version '.$this->record->offer_terms['template']['version'] : 'Texte der Webseite').').') ->action(function (ConfirmBooking $confirm): void { - $missing = app(CaseAutomation::class)->documentBlockers($this->record); - if ($missing !== []) { - Notification::make()->title('Noch nicht möglich')->body(implode(' ', $missing))->warning()->send(); + if ($this->record->contract_path === null) { + Notification::make()->title('Bitte zuerst prüfen')->body('Die Unterlagen wurden noch nie erstellt – bitte über „Unterlagen prüfen und senden“.')->warning()->send(); return; } @@ -550,28 +621,31 @@ private function offerChanges(array $data): array { return [ ...$data, + 'acknowledged' => (bool) ($data['acknowledged'] ?? false), 'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null, ]; } /** - * Live price shown in the offer modal, calculated exactly like the offer itself. + * The current values of some fields of a modal form. + * + * @param list $fields + * @return array */ - private function offerPricePreview(Get $get): string + private static function formState(Get $get, array $fields): array { - try { - $stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null); - $quote = app(PriceCalculator::class)->calculate($this->record->property, $stay); - } catch (QuoteException $exception) { - return 'Preis: '.$exception->getMessage(); - } catch (Throwable) { - return 'Preis: bitte Termin und Personen angeben.'; - } + return collect($fields)->mapWithKeys(fn (string $field): array => [$field => $get($field)])->all(); + } - $adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0; - $promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : ''; - - return 'Preis im Angebot: '.Money::format($quote->total() + $adjustment).' für '.$stay->arrival->format('d.m.').'–'.$stay->departure->format('d.m.Y').', '.$stay->guests.' Personen'.$promo; + /** + * Form data of the documents modal as composition changes. + * + * @param array $data + * @return array + */ + private function documentChanges(array $data): array + { + return array_filter(Arr::only($data, ['contract_template_id', 'annex_ids']), fn ($value): bool => $value !== null); } private function runWorkflow(callable $workflow, string $successTitle): void diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index e40e0da..b5e259e 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -5,6 +5,7 @@ use App\Documents\OfferTerms; use App\Enums\ActivityState; use App\Enums\AdminMode; +use App\Enums\DocumentKind; use App\Enums\ProcessingMode; use App\Enums\ProcessSetting; use App\Enums\Responsibility; @@ -102,12 +103,9 @@ public static function configure(Schema $schema): Schema ]), Section::make('Dokumente') ->schema([ - TextEntry::make('documents')->hiddenLabel()->state(fn (Booking $record): string => collect([ - $record->offer_path ? 'Angebot Version '.$record->offer_version : null, - $record->contract_path ? 'Mietvertrag' : null, - $record->confirmation_sent_at ? 'Bestätigung gesendet am '.$record->confirmation_sent_at->format('d.m.Y') : null, - ])->filter()->implode(' · ') ?: 'Noch keine'), - TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) + TextEntry::make('documents')->hiddenLabel()->html()->state(fn (Booking $record): HtmlString => self::documents($record)), + TextEntry::make('document_kind')->label('Vorgesehen')->state(fn (Booking $record): string => DocumentKind::forCase($record)?->getLabel() ?? 'Unterlagen schickt das Portal'), + TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) && ($record->contract_path !== null || $record->offer_path !== null) ? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].', festgeschrieben)' : (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'), ]), @@ -163,6 +161,26 @@ private static function nextStep(Booking $booking): HtmlString .'
'.$mode.'
'); } + /** + * The documents made for the case, as recorded when they were created (kind, template, date). + */ + private static function documents(Booking $booking): HtmlString + { + $lines = $booking->events()->where('type', 'document')->whereNotNull('data')->reorder()->orderBy('occurred_at')->orderBy('id')->get() + ->filter(fn ($event): bool => isset($event->data['kind'])) + ->map(fn ($event): string => e($event->occurred_at->format('d.m.Y').' · '.$event->summary)); + + if ($lines->isEmpty()) { + $lines = collect([ + $booking->offer_path ? 'Angebot Version '.$booking->offer_version : null, + $booking->contract_path ? 'Mietvertrag' : null, + $booking->confirmation_sent_at ? 'Bestätigung gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : null, + ])->filter()->map(fn (string $line): string => e($line)); + } + + return new HtmlString($lines->isEmpty() ? 'Noch keine' : $lines->implode('
')); + } + /** * @return list */ diff --git a/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php b/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php index 63cf955..9b0f167 100644 --- a/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php +++ b/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php @@ -3,7 +3,9 @@ namespace App\Filament\Resources\ContractTemplates\Pages; use App\Filament\Resources\ContractTemplates\ContractTemplateResource; +use App\Models\ContractTemplate; use Filament\Resources\Pages\CreateRecord; +use Illuminate\Database\Eloquent\Model; class CreateContractTemplate extends CreateRecord { @@ -21,4 +23,16 @@ protected function mutateFormDataBeforeCreate(array $data): array return $data; } + + /** + * @param array $data + */ + protected function handleRecordCreation(array $data): Model + { + $template = new ContractTemplate(collect($data)->except(['is_released', 'is_portal_terms'])->all()); + $template->applyStatements((bool) ($data['is_released'] ?? false), (bool) ($data['is_portal_terms'] ?? false), (string) auth()->user()?->name); + $template->save(); + + return $template; + } } diff --git a/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php b/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php index 9e13660..5192b00 100644 --- a/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php +++ b/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php @@ -3,8 +3,10 @@ namespace App\Filament\Resources\ContractTemplates\Pages; use App\Filament\Resources\ContractTemplates\ContractTemplateResource; +use App\Models\ContractTemplate; use Filament\Actions\DeleteAction; use Filament\Resources\Pages\EditRecord; +use Illuminate\Database\Eloquent\Model; class EditContractTemplate extends EditRecord { @@ -14,4 +16,26 @@ protected function getHeaderActions(): array { return [DeleteAction::make()]; } + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeFill(array $data): array + { + return [...$data, 'is_released' => $data['released_at'] !== null, 'is_portal_terms' => $data['portal_terms_confirmed_at'] !== null]; + } + + /** + * @param array $data + */ + protected function handleRecordUpdate(Model $record, array $data): Model + { + /** @var ContractTemplate $record */ + $record->fill(collect($data)->except(['is_released', 'is_portal_terms'])->all()); + $record->applyStatements((bool) ($data['is_released'] ?? false), (bool) ($data['is_portal_terms'] ?? false), (string) auth()->user()?->name); + $record->save(); + + return $record; + } } diff --git a/app/Filament/Resources/ContractTemplates/Schemas/ContractTemplateForm.php b/app/Filament/Resources/ContractTemplates/Schemas/ContractTemplateForm.php index c7fe0e1..7b1d967 100644 --- a/app/Filament/Resources/ContractTemplates/Schemas/ContractTemplateForm.php +++ b/app/Filament/Resources/ContractTemplates/Schemas/ContractTemplateForm.php @@ -9,6 +9,7 @@ use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; +use Filament\Forms\Components\Toggle; use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Text; use Filament\Schemas\Schema; @@ -65,6 +66,17 @@ public static function configure(Schema $schema): Schema Textarea::make('texts.closing')->label('Vertragsschluss')->rows(3)->columnSpanFull(), Textarea::make('texts.contract_note')->label('Hinweis im Angebots-PDF')->rows(3)->columnSpanFull(), ]), + Section::make('Freigabe') + ->description('Ihre Erklärung zu genau diesem Text. Ändert sich der Text, gilt sie erst nach erneutem Speichern mit Haken wieder; eine neue Version beginnt ohne Freigabe.') + ->columnSpanFull() + ->schema([ + Toggle::make('is_released') + ->label('Für den Versand an Gäste freigegeben') + ->helperText('Ohne Freigabe wird die Vorlage nie automatisch versendet; von Hand nur nach ausdrücklicher Bestätigung im Vorgang.'), + Toggle::make('is_portal_terms') + ->label('Gibt nur wieder, was Gäste bei der Buchung über das Portal akzeptieren') + ->helperText('Nur für Vorlagen, die bei beim Portal gebuchten Vorgängen verwendet werden. Ohne diesen Haken weist der Vorgang auf Gebühren und Bedingungen der Vorlage hin und verlangt vor dem Versand eine Bestätigung.'), + ]), Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(), ]); } diff --git a/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php b/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php index 3fa8bb4..f3765e1 100644 --- a/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php +++ b/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php @@ -21,6 +21,8 @@ public static function configure(Table $table): Table ->columns([ TextColumn::make('name')->label('Vorlage')->searchable()->weight('medium'), TextColumn::make('version')->label('Version')->badge(), + IconColumn::make('released')->label('Freigegeben')->boolean()->state(fn (ContractTemplate $record): bool => $record->isReleased()), + IconColumn::make('portal_terms')->label('Portalbedingungen')->boolean()->state(fn (ContractTemplate $record): bool => $record->confirmsPortalTerms()), IconColumn::make('used')->label('In Angeboten verwendet')->boolean()->state(fn (ContractTemplate $record): bool => $record->isUsed()), TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y, H:i'), ]) diff --git a/app/Http/Controllers/DocumentPreviewController.php b/app/Http/Controllers/DocumentPreviewController.php new file mode 100644 index 0000000..3609085 --- /dev/null +++ b/app/Http/Controllers/DocumentPreviewController.php @@ -0,0 +1,33 @@ +isForGuests(), 404); + + $changes = json_decode((string) base64_decode((string) $request->query('changes', ''), true), true); + $composition = $composer->compose($booking, $documentKind, is_array($changes) ? $changes : []); + $pdf = $contract->render($composition->draft, $documentKind, draft: $documentKind === DocumentKind::Offer); + + return response($pdf, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="Vorschau-'.$documentKind->fileName().'-'.$booking->reference.'.pdf"', + 'Cache-Control' => 'no-store', + ]); + } +} diff --git a/app/Mail/BookingDocumentation.php b/app/Mail/BookingDocumentation.php new file mode 100644 index 0000000..1d1aff9 --- /dev/null +++ b/app/Mail/BookingDocumentation.php @@ -0,0 +1,47 @@ +booking->portal_reference ?? $this->booking->reference), + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.booking-documentation'); + } + + /** + * @return list + */ + public function attachments(): array + { + $path = app(RentalContract::class)->absolutePath($this->booking); + + return $path ? [Attachment::fromPath($path)->as("Buchungsunterlagen-{$this->booking->reference}.pdf")->withMime('application/pdf')] : []; + } +} diff --git a/app/Models/ContractTemplate.php b/app/Models/ContractTemplate.php index 154f6b4..a7abed7 100644 --- a/app/Models/ContractTemplate.php +++ b/app/Models/ContractTemplate.php @@ -12,13 +12,23 @@ * A version of contract texts for offers (e.g. conditions demanded by a portal). The texts replace the website * texts of the same meaning when an offer is made; the offer then freezes a copy. A version that has been used in * an offer is never edited – a new version is created instead. + * + * A version goes to guests automatically only when it is released; for bookings already binding on a portal it must in + * addition be confirmed as reproducing only what guests accept there (E-004). Both statements belong to the text: they + * lapse when the text changes, and a new version starts without them. */ -#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes'])] +#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes', 'released_at', 'released_by', 'portal_terms_confirmed_at', 'portal_terms_confirmed_by'])] class ContractTemplate extends Model { use BelongsToTenant; /** Form/storage key => website text key it replaces in an offer. */ + /** Attributes whose change makes the release and the portal confirmation lapse. */ + /** Whether the statements were given for the pending save (then a text change does not withdraw them). */ + private bool $statementsApplied = false; + + private const CONTENT = ['texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids']; + public const TEXTS = [ 'intro' => 'contract.intro', 'terms' => 'contract.terms', @@ -35,7 +45,64 @@ class ContractTemplate extends Model */ protected function casts(): array { - return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array']; + return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array', 'released_at' => 'datetime', 'portal_terms_confirmed_at' => 'datetime']; + } + + protected static function booted(): void + { + static::saved(function (ContractTemplate $template): void { + $template->statementsApplied = false; + }); + + static::saving(function (ContractTemplate $template): void { + if ($template->exists && $template->isDirty(self::CONTENT) && ! $template->statementsApplied) { + if (! $template->isDirty('released_at')) { + $template->released_at = null; + $template->released_by = null; + } + if (! $template->isDirty('portal_terms_confirmed_at')) { + $template->portal_terms_confirmed_at = null; + $template->portal_terms_confirmed_by = null; + } + } + }); + } + + /** + * Records the landlord's statements on the (possibly just changed) text: a statement is renewed when it is given for + * a changed text, kept when nothing changed and withdrawn when it is not given. + */ + public function applyStatements(bool $released, bool $portalTerms, string $actor): self + { + $changed = $this->isDirty(self::CONTENT); + $this->statementsApplied = true; + + if (! $released) { + $this->forceFill(['released_at' => null, 'released_by' => null]); + } elseif ($changed || ! $this->isReleased()) { + $this->forceFill(['released_at' => now(), 'released_by' => $actor]); + } + + if (! $portalTerms) { + $this->forceFill(['portal_terms_confirmed_at' => null, 'portal_terms_confirmed_by' => null]); + } elseif ($changed || ! $this->confirmsPortalTerms()) { + $this->forceFill(['portal_terms_confirmed_at' => now(), 'portal_terms_confirmed_by' => $actor]); + } + + return $this; + } + + public function isReleased(): bool + { + return $this->released_at !== null; + } + + /** + * Whether the landlord confirmed that this version only reproduces the terms guests accept when booking on a portal. + */ + public function confirmsPortalTerms(): bool + { + return $this->portal_terms_confirmed_at !== null; } /** diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index d3c489c..4c64eda 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -28,7 +28,7 @@ 'channel_stale_after_minutes', 'channel_task_reminder_after_minutes', 'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections', 'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on', - 'process_defaults', + 'process_defaults', 'document_releases', ])] class Tenant extends Model { @@ -76,6 +76,7 @@ protected function casts(): array 'digest_hour' => 'integer', 'digest_sections' => 'array', 'process_defaults' => 'array', + 'document_releases' => 'array', 'digest_when_empty' => 'boolean', 'digest_daily_sent_on' => 'immutable_date', 'digest_weekly_sent_on' => 'immutable_date', diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index 7be7900..0fd063b 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -2,6 +2,7 @@ namespace App\Process; +use App\Actions\SendBookingDocuments; use App\Enums\ActivityState; use App\Enums\BookingStatus; use App\Enums\BookingTaskStatus; @@ -88,13 +89,24 @@ public static function for(Booking $booking): array default => ActivityState::Open, }; $missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : []; - $activities[] = new Activity('documents', $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden', $later($missing !== [] ? ActivityState::Waiting : $state), + // What the landlord still has to confirm (unreleased texts, terms not shown to be agreed on the portal). + $toConfirm = $binding && $state === ActivityState::Open && $missing === [] ? app(SendBookingDocuments::class)->compose($booking)->toConfirm() : []; + $activities[] = new Activity('documents', match (true) { + $state !== ActivityState::Open => $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden', + $inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden', + default => 'Buchungsunterlagen prüfen und senden', + }, $later($missing !== [] ? ActivityState::Waiting : $state), match (true) { $booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'), $state === ActivityState::Problem => 'Versand fehlgeschlagen', $missing !== [] => 'wartet: '.implode(' ', $missing), + $toConfirm !== [] => 'vor dem Versand zu prüfen: '.implode(' ', $toConfirm), default => null, - }, $binding && $missing === [] && $booking->confirmation_sent_at === null ? 'resendConfirmation' : null); + }, match (true) { + $state === ActivityState::Problem => 'resendConfirmation', + $binding && $missing === [] && $booking->confirmation_sent_at === null => 'sendDocuments', + default => null, + }); } foreach (self::channelTasks($booking) as $task) { diff --git a/app/Process/CaseAutomation.php b/app/Process/CaseAutomation.php index ba46d07..d7e71d7 100644 --- a/app/Process/CaseAutomation.php +++ b/app/Process/CaseAutomation.php @@ -3,7 +3,7 @@ namespace App\Process; use App\Actions\AutoOffer; -use App\Actions\ConfirmBooking; +use App\Actions\SendBookingDocuments; use App\Enums\BookingStatus; use App\Enums\IntakeKind; use App\Enums\ProcessingMode; @@ -13,14 +13,15 @@ /** * Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do - * is what the landlord would do next anyway: send the offer of a request, or send the documents of a booking that is - * binding on a portal once the guest's e-mail address and the price are known. Whatever stops it is returned in plain + * is what the landlord would do next anyway: send the offer of a request, or send the documents of a binding booking + * once their composition is complete and needs no confirmation (template released and, for portal bookings, confirmed + * as the portal's terms). Whatever stops it is returned in plain * words; the case then shows it as a task. Never touches a case whose profile was taken over from the old data (the * automation did not exist for those cases before). */ class CaseAutomation { - public function __construct(private AutoOffer $autoOffer, private ConfirmBooking $confirm) {} + public function __construct(private AutoOffer $autoOffer, private SendBookingDocuments $documents) {} /** * @return list what keeps the case from going on automatically (empty: nothing to do or done) @@ -52,12 +53,7 @@ private function step(Booking $booking): array } if ($booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord && $booking->process()->origin !== 'migration') { - $missing = $this->documentBlockers($booking); - if ($missing !== []) { - return $missing; - } - - return $this->confirm->deliver($booking) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).']; + return $this->documents->automatically($booking); } return []; diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 2bc2639..5705745 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -4,6 +4,7 @@ use App\Enums\AdminMode; use App\Filament\Pages\Dashboard; +use App\Http\Controllers\DocumentPreviewController; use App\Http\Controllers\SwitchPropertyController; use App\Http\Middleware\ResolveTheme; use App\Models\User; @@ -74,6 +75,7 @@ public function panel(Panel $panel): Panel ->renderHook(PanelsRenderHook::SIDEBAR_NAV_START, fn (): View => view('filament.property-switcher')) ->authenticatedRoutes(function (): void { Route::post('wohnung-wechseln', SwitchPropertyController::class)->name('switch-property'); + Route::get('vorgaenge/{booking}/dokument-vorschau/{kind}', DocumentPreviewController::class)->name('document-preview'); }) ->navigationGroups(['Verwaltung', 'Einrichtung', 'Webseite', 'System']) ->colors([ diff --git a/database/migrations/2026_11_02_090000_add_document_releases.php b/database/migrations/2026_11_02_090000_add_document_releases.php new file mode 100644 index 0000000..7688c25 --- /dev/null +++ b/database/migrations/2026_11_02_090000_add_document_releases.php @@ -0,0 +1,44 @@ +timestamp('released_at')->nullable(); + $table->string('released_by', 120)->nullable(); + $table->timestamp('portal_terms_confirmed_at')->nullable(); + $table->string('portal_terms_confirmed_by', 120)->nullable(); + }); + + Schema::table('tenants', function (Blueprint $table): void { + $table->json('document_releases')->nullable(); + }); + + DB::table('contract_templates')->update(['released_at' => now(), 'released_by' => 'Übernahme (bisher schon verwendet)']); + } + + public function down(): void + { + Schema::table('contract_templates', function (Blueprint $table): void { + $table->dropColumn(['released_at', 'released_by', 'portal_terms_confirmed_at', 'portal_terms_confirmed_by']); + }); + + Schema::table('tenants', function (Blueprint $table): void { + $table->dropColumn('document_releases'); + }); + } +}; diff --git a/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md b/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md new file mode 100644 index 0000000..213f40d --- /dev/null +++ b/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md @@ -0,0 +1,206 @@ +# Umsetzungsergebnis Paket 3: Dokumentenzusammenstellung und Vorlagensteuerung + +Stand: 02.11.2026 · Branch `feature/vorgang` · Grundlage: [UMSETZUNGSPLAN_v0.10](UMSETZUNGSPLAN_v0.10.md) §4.5, §5.4, Abnahmekriterien 3.1–3.3; [UMSETZUNGSERGEBNIS_P1_P2](UMSETZUNGSERGEBNIS_P1_P2.md). Die normative Prozessarchitektur v0.10 wurde nicht verändert. + +--- + +## 1. Implementierungsstand + +Paket 3 ist umgesetzt. Alle drei Abnahmekriterien sind durch Tests belegt, die Oberflächen wurden im Browser geprüft. + +| Bereich | Stand | +|---|---| +| Gemeinsame Zusammenstellung für Angebot, Buchungsbestätigung und Buchungsunterlagen extern | umgesetzt | +| Dokumentart je Vorgang automatisch (A1/A2 Angebot bzw. Bestätigung, A3/A4 Buchungsunterlagen, A5 Portal) | umgesetzt | +| Vorlagenwahl über die Einstellungsebenen, Herkunft sichtbar | umgesetzt | +| Freigabe von Vorlagen und Dokumentarten, Bestätigung der Portalbedingungen | umgesetzt | +| Schutz vor unvereinbarten Bedingungen (E-004) mit bewusster Bestätigung | umgesetzt | +| Kein doppelter Versand (Angebot und Unterlagen) | umgesetzt | +| Absicherung Hold = 0 bis Paket 7 | umgesetzt | +| Auskunft unter Vorbehalt (Paket 7) und A6-Aufenthaltsbestätigung (Paket 6) | als Dokumentart und Arbeitsfassung vorbereitet, nicht versendbar | +| Storno- und Änderungsbestätigung (Paket 5) | nicht Teil dieses Pakets | + +Tests: **648 grün** (vorher 634; 13 neue in `DocumentCompositionTest`, ein neuer in `PortalBookingTest`), Pint sauber. + +--- + +## 2. Tatsächlich umgesetzte Geschäftsfunktionen + +**Ein Prüfbild vor jedem Dokument.** Vor dem Versand sieht die Vermieterin immer dieselbe Zusammenstellung: +- Dokumentart, Empfänger mit E-Mail-Adresse, Eingang (z. B. „Gebucht über FeWo-direkt · Buchungsnummer HA-…“) +- Wohnung, Zeitraum, Nächte, Personen (oder „noch nicht bekannt“) +- Preis mit Positionen und **Herkunft** („aus Ihren Preisen berechnet“, „laut FeWo-direkt übernommen, nicht neu berechnet“, „wie im angenommenen Angebot“) +- Zusatzleistungen, Stornoregel, Vorlage mit Herkunft der Einstellung, Anlagen, Annahmelink ja/nein +- Hinweise in drei Stufen: **Fehlt noch** (rot, kein Versand), **Bitte prüfen** (gelb, nur nach Bestätigung), Information (blau) +- aufklappbar: Vorschau der E-Mail und des Dokuments, dazu „Als PDF öffnen“ + +„Anpassen“ ist zugeklappt (Zeitraum, Preis/Nachlass, Vorlage, Anlagen, Gültigkeit, Gast). Jede Änderung rechnet die Zusammenstellung sofort neu. In der Expertenansicht zeigt sie zusätzlich Freigabestand und Portalbestätigung der Vorlage. + +**Wo sie erscheint:** +- „Angebot prüfen und senden“ (ersetzt den bisherigen Angebotsdialog) +- „Bestätigung prüfen und senden“ bzw. „Buchungsunterlagen prüfen und senden“ (neu, ersetzt den ersten Versand über „Unterlagen an den Gast senden“) +- „Direkt verbindlich bestätigen“ mit Schalter „Unterlagen an den Gast senden“ + +„Unterlagen erneut senden“ bleibt für bereits erstellte Unterlagen und schickt unverändert dieselben. + +**Buchungsunterlagen für beim Portal gebuchte Vorgänge (A3/A4).** Eigene Mail „Ihre Buchungsunterlagen“ und PDF „Buchungsunterlagen“: +- Hinweis, dass die Buchung beim Portal verbindlich zustande gekommen ist +- kein Annahmelink, kein eigener Stornolink +- Zahlungsanweisung nur, wenn wir laut Profil zuständig sind, sonst „Die Zahlung läuft über FeWo-direkt“ + +Eigene Buchungen erhalten weiterhin die Buchungsbestätigung mit Mietvertrag. + +**Freigaben.** +- *Vorlagen* (Vorlagen › Bearbeiten › Freigabe): „Für den Versand an Gäste freigegeben“ und „Gibt nur wieder, was Gäste bei der Buchung über das Portal akzeptieren“. Beide Erklärungen gelten für genau diesen Text: Sie entfallen bei einer Textänderung und fehlen bei einer neuen Version. Die Liste zeigt beide Zustände. +- *Dokumentarten* (So arbeite ich › Dokumente): Die Buchungsunterlagen extern sind eine Arbeitsfassung, bis die Vermieterin sie freigibt; Datum und Person werden festgehalten. Angebot und Bestätigung sind seit jeher in Verwendung und bleiben freigegeben. Auskunft und Aufenthaltsbestätigung sind als „Arbeitsfassung vorbereitet, noch nicht nutzbar“ aufgeführt. + +**Verlauf.** +- Jedes erstellte Dokument steht im Verlauf: Art, Vorlage mit Version, Anlagen, Prüfsumme des PDF, beim Angebot auch die Angebotsprüfsumme. +- Bestätigte Hinweise werden mit Person und Wortlaut gespeichert. +- Der Kasten „Dokumente“ der Vorgangsseite liest daraus. + +--- + +## 3. Nachweise zu den Abnahmekriterien + +| ID | Kriterium | Nachweis | Ergebnis | +|---|---|---|---| +| 3.1 | Dasselbe Prüfbild vor jedem Versand; eine Anpassung aktualisiert sofort | `DocumentCompositionTest::test_the_offer_composition_shows_everything_and_an_adjustment_updates_it` prüft Gast, Preis mit Herkunft, Stornoregel, Vorlage, Anlagen, Annahme sowie den neuen Gesamtpreis nach −50 € Nachlass; danach Versand über den Dialog. Browser: Angebots- und Unterlagenzusammenstellung, Neuberechnung nach Nachlass (368,00 € → 318,00 €), E-Mail- und PDF-Vorschau. | **erfüllt** | +| 3.2 | Website-Anfrage → bindendes Angebot mit Annahmelink; verbindliche FeWo-direkt-Buchung → Buchungsunterlagen ohne Annahmelink mit der Vorlage für dieses Portal und diese Eingangsart, ohne manuelle Vorlagenwahl | `test_each_case_gets_its_document_without_choosing_a_template`: Angebot mit Standardvorlage und Link `/angebot/…`. Portalbuchung mit Vorlage „eingestellt für FeWo-direkt (Verbindliche Buchung)“, Datei `Buchungsunterlagen-….pdf`, Mail ohne Annahmelink und ohne Überweisungsaufforderung. | **erfüllt** | +| 3.3 | Nicht nachgewiesene Gebühr in der Vorlage einer extern verbindlichen Buchung → Hinweis und bewusste Bestätigung | `test_an_unconfirmed_fee_in_a_portal_template_needs_a_conscious_confirmation`: Ersatzmieter-Gebühr 35,00 €, Staffel und „60,00 € (im Text)“ werden genannt. Automatik sendet nicht, die Aufgabe nennt den Grund. Versand von Hand wird ohne Haken abgelehnt; mit Haken wird gesendet und die Bestätigung samt Person protokolliert. Dazu `test_without_any_template_a_portal_booking_does_not_get_our_website_terms_unchecked`. | **erfüllt** | + +Weitere Tests: +- Versand der Unterlagen nur einmal bei Wiederholung (Automatik zweimal, dann Handversand) +- Angebot nicht doppelt bei erneuter Freigabe oder Automatiklauf +- Hold = 0 nur mit ausdrücklicher Entscheidung; die Automatik sendet nie +- fehlende Vertragsdaten stoppen das automatische Angebot +- bereits gesendete Dokumente bleiben unverändert, auch nach Vorlagen- und Einstellungsänderung +- Freigaben entfallen bei Textänderung +- Freigabe auf der Einstellungsseite +- A6-Aufenthaltsbestätigung ohne Mietvertrag +- PDF-Vorschau speichert nichts + +--- + +## 4. Änderungen an Dokumentenverarbeitung und Vorlagensteuerung + +| Baustein | Änderung | +|---|---| +| `App\Enums\DocumentKind` (neu) | Dokumentarten Angebot, Auskunft, Bestätigung, Buchungsunterlagen extern, Aufenthaltsbestätigung, intern. `forCase()` leitet die Art aus Vorgangsart und Profil ab, nie aus einer Auswahl. Dazu: Annahmelink, Vertrag ja/nein, versendbar, standardmäßig freigegeben, Dateiname. | +| `App\Documents\DocumentComposer` / `DocumentComposition` / `DocumentFinding` (neu) | Baut die Zusammenstellung auf einer ungespeicherten Kopie des Vorgangs und ermittelt die Hinweise. Für Angebote rechnet er den Preis genau wie `SendOffer` (`SendOffer::quoteFor`, jetzt öffentlich). Prüfkriterien sind ausschließlich objektiv: fehlende oder widersprüchliche Daten, Freigaben, Nachweis der Bedingungen. | +| `App\Documents\DocumentReleases` (neu) | Freigabe je Dokumentart am Mandanten (`tenants.document_releases`) | +| `App\Actions\SendBookingDocuments` (neu) | Einziger Weg für Bestätigung bzw. Buchungsunterlagen eines verbindlichen Vorgangs: `automatically()` oder `handle()` nach Bestätigung. Hat er Erfolg, ist mit dem Versand die Aktivität „Unterlagen“ erledigt. | +| `SendOffer` | Prüft die Zusammenstellung (Bestätigungspunkte nur mit `acknowledged`), `expected_version` gegen Doppelversand, Verlaufseintrag „Dokument“ | +| `AutoOffer` | Zusätzliche Blocker aus der Zusammenstellung (unfreigegebene Vorlage, fehlende Vertragsdaten); ruft `SendOffer` mit `expected_version: 0` auf | +| `ConfirmBooking::deliver` | Kennt die Dokumentart: richtige Mail (`BookingConfirmed` oder `BookingDocumentation`) und richtiges PDF; Verlaufseintrag beim Erstellen | +| `RentalContract` | Je Dokumentart Ansicht und Dateiname; `render()` und `view()` für Vorschauen ohne Speichern | +| `CaseAutomation`, `ProvideGuestContact`, `CreateBooking` (sofort bestätigen) | Senden Unterlagen nur noch über `SendBookingDocuments`. Damit gehen keine Unterlagen mehr ungeprüft an der Zusammenstellung vorbei; vorher sendeten diese Wege direkt. | +| `CaseActivities` | Aktivität „Buchungsunterlagen prüfen und senden“ bzw. „Buchungsbestätigung mit Vertrag prüfen und senden“, Aktion `sendDocuments`, Detail „vor dem Versand zu prüfen: …“ | +| `ContractTemplate` | `released_at/by`, `portal_terms_confirmed_at/by`, `applyStatements()`; Erklärungen entfallen bei Textänderung | +| Oberfläche | `filament/document-composition.blade.php`, `App\Filament\Forms\DocumentCompositionFields`, Route `filament.admin.document-preview` (PDF-Vorschau, nur angemeldet und mandantengebunden), neue Aktionen auf der Vorgangsseite, Freigabe-Schalter für Vorlagen und Dokumentarten | +| Neue Ansichten | `mail/booking-documentation`, `pdf/stay-confirmation` (Arbeitsfassungen); `pdf/contract*` mit Überschrift „Buchungsunterlagen“ für A3/A4 | + +**Vorlagenwahl:** Unverändert über die Einstellungsebenen (Vermieterstandard → Wohnung → Portal je Eingangsart → Vorgang). Über die Eingangsart ist das zugleich die Wahl je Dokumentart: Anfrage → Angebot/Bestätigung, verbindliche Buchung → Buchungsunterlagen. Eine Vorlagenwahl im Vorgang gilt nur für diesen Vorgang und erscheint als „für diesen Vorgang gewählt“. + +--- + +## 5. Automatischer Versand und vertragliche Verbindlichkeit + +**Automatik:** Gesendet wird nur, wenn die Zusammenstellung weder „fehlt noch“ noch „bitte prüfen“ enthält. Sonst entsteht die Aufgabe im Vorgang und unter „Zu erledigen“, mit den Gründen im Klartext. Nach dem Erledigen gelten die Fortsetzungsregeln aus Paket 2. + +**Von Hand:** Dieselbe Zusammenstellung. Bei Prüfpunkten ist der Haken „Ich habe die Hinweise geprüft und möchte das Dokument so senden“ Pflicht. Die bestätigten Hinweise werden mit Person gespeichert. + +**Extern verbindliche Buchungen (E-004):** +- kein Annahmelink, keine zweite Annahme +- der Portalpreis wird nicht neu berechnet +- **Prüfpunkte:** + - Vorlage nicht als Wiedergabe der Portalbedingungen bestätigt + - in der Vorlage genannte Gebühren: Ersatzmieter-Gebühr und Staffel der Stornoregel sowie Eurobeträge im Text + - Zahlungsplatzhalter, obwohl das Portal kassiert + - keine eigene Vorlage (dann stünden die Mietbedingungen der Webseite im Dokument) + +Die Bestätigung erklärt nicht, dass etwas vereinbart *ist*. Sie hält fest, dass die Vermieterin bewusst so sendet; der Hinweistext sagt ausdrücklich: „Zusätzliche Pflichten gelten nur, wenn der Gast ihnen dort zugestimmt hat.“ Eine manuelle Freigabe ersetzt also keine Vereinbarung mit dem Gast. + +**Wirkung auf den Automatikweg aus Paket 2:** Seit Paket 2 konnten Portalbuchungen im Modus „automatisch“ ihre Unterlagen sofort erhalten, sobald E-Mail-Adresse und Preis da waren. Das ist jetzt abgesichert und läuft erst, wenn zwei Freigaben vorliegen: +- die Vermieterin hat die Buchungsunterlagen freigegeben; +- die Vorlage dieses Portals ist freigegeben und als Wiedergabe der Portalbedingungen bestätigt. + +Bis dahin wartet der Vorgang mit Aufgabe. + +**Kein doppelter Versand:** +- *Unterlagen:* Sperre je Vorgang (Cache-Lock), danach eine frische Prüfung von `confirmation_sent_at`. +- *Angebot:* `expected_version` wird unter der Zeilensperre geprüft. Der Dialog übergibt die beim Öffnen gültige Version, die Automatik die Version 0. + +**Hold = 0 bis Paket 7:** +- Wenn Anfragen laut Profil nichts reservieren, kann ein Angebot mit Annahmelink nur nach ausdrücklicher Bestätigung entstehen, mit klarer Erklärung der Folge. +- Die Automatik sendet in diesem Fall nie. +- Die Auskunft unter Vorbehalt selbst kommt mit Paket 7. + +**Eingefrorene Inhalte:** +- Angebote frieren ihre Bedingungen wie bisher ein (`offer_terms`, `offer_hash`). +- Unterlagen frieren beim ersten Erstellen ein: Bis dahin werden Vorlage und Anlagen aus der Zusammenstellung übernommen; danach bleiben PDF, Prüfsumme und Bedingungen unverändert, auch beim erneuten Senden. +- Angenommene Angebote werden nie neu erfasst. + +--- + +## 6. Ergebnisse der Tests und der visuellen Prüfung + +- **Tests:** 648 Tests, 3523 Zusicherungen, alle grün. Pint sauber. +- **Browser** (Chromium über Playwright, lokaler Server, **Kopie** der lokalen Datenbank im Scratchpad, Anmeldung mit Zwei-Faktor-Code): + - Vorgangsseite einer Website-Anfrage + - Angebotszusammenstellung, Neuberechnung nach Nachlass, E-Mail-Vorschau + - Vorgangsseite einer FeWo-direkt-Buchung mit Unterlagenzusammenstellung: drei Prüfpunkte, darunter Ersatzmieter-Gebühr und 60,00 € im Text; Information „Kein Annahmelink“; Preisherkunft „laut FeWo-direkt übernommen“ + - PDF-Vorschau (HTTP 200, `application/pdf`) + - „So arbeite ich“ mit Bereich „Dokumente“ + - **Keine Konsolenfehler.** Zwei kleine Darstellungsmängel (Aufzählungspunkte, Vorlagenangabe „festgeschrieben“ vor dem Versand) wurden behoben. +- Die lokale Arbeitsdatenbank blieb unberührt. +- **Nicht geprüft:** Darstellung auf Tablet oder Smartphone; echte Mailprogramme; Migration auf MariaDB des Testsystems. + +--- + +## 7. Rückwärtskompatibilität und verbleibende Risiken + +**Kompatibilität:** +- Die Migration `2026_11_02_090000_add_document_releases` ist rein additiv. +- **Bestehende Vorlagen gelten als freigegeben** (`released_by` = „Übernahme (bisher schon verwendet)“), damit laufende Angebote und Bestätigungen weiter funktionieren. Keine Vorlage ist als Portalbedingung bestätigt. +- Bestehende Angebote, Annahmelinks, Prüfsummen und Vertrags-PDFs werden nicht verändert. +- Dateinamen von Mietverträgen bleiben gleich; neu sind nur `Buchungsunterlagen-…` und `Aufenthaltsbestaetigung-…`. + +**Verhaltensänderungen, die man kennen sollte:** +1. Portalbuchungen (A3/A4) erhalten künftig „Buchungsunterlagen“ statt „Buchungsbestätigung/Mietvertrag“, mit eigenem Mailtext (Arbeitsfassung). +2. Automatische Angebote halten an, wenn die Vorlage nicht freigegeben ist oder Platzhalter im Vertragstext unbelegt bleiben. +3. „Sofort bestätigen“ beim Anlegen sendet die Unterlagen nur noch, wenn nichts zu prüfen ist; sonst erscheint „Gebucht – Unterlagen noch nicht gesendet“ mit Grund. +4. Wird eine Vorlage bearbeitet, entfällt ihre Freigabe, außer sie wird beim Speichern erneut angehakt. + +**Risiken:** +- Die Gebührenerkennung im Freitext ist eine Heuristik (Eurobeträge). Sie meldet lieber zu viel als zu wenig; Gebühren ohne Betrag im Text erkennt sie nicht. Der Hauptschutz ist die fehlende Portalbestätigung der Vorlage, nicht die Heuristik. +- Die Vorschau zeigt E-Mail und Dokument als HTML. Logos, die als Datei eingebettet sind, fehlen dort; im PDF sind sie enthalten. +- Die Zusammenstellung wird für offene verbindliche Vorgänge auch in „Zu erledigen“ berechnet. Bei sehr vielen offenen Vorgängen könnte das die Startseite verlangsamen; bei 1–3 Wohnungen ist das unkritisch. +- Ältere Portalbuchungen aus „Akte anlegen“ (siehe P1/P2) tragen noch den angenommenen Preis. Werden für sie jetzt Unterlagen gesendet, zeigt die Zusammenstellung diesen Preis als „aus Ihren Preisen berechnet“. Vorher sichten. + +--- + +## 8. Offene Vorlagenfreigaben und erforderliche Entscheidungen + +| Was | Wer | Wirkung bis dahin | +|---|---|---| +| Text der Mail und des PDF „Buchungsunterlagen (beim Portal gebucht)“ prüfen und unter So arbeite ich › Dokumente freigeben | Betreiber/Vermieterin (Zulieferung §8.4, ggf. rechtliche Prüfung) | Kein automatischer Versand; von Hand nur mit Bestätigung | +| FeWo-direkt-Vorlage („FeWo-direkt Direktbuchung“): Stimmen § 13 (Staffel, Ersatzmieter-Gebühr 35 €), die Endreinigung und die ergänzende Vereinbarung mit dem überein, was Gäste bei FeWo-direkt akzeptieren? (Offene Frage **FW-01**) | Betreiber | Jeder Versand verlangt die Bestätigung der Prüfpunkte | +| Vorlage für Destination Solutions (A3, **DS-01/02**) | Betreiber | Ohne Vorlage meldet die Zusammenstellung „keine eigene Vorlage“ | +| Text der Auskunft unter Vorbehalt | Paket 7, Betreiber | Nicht versendbar | +| Text der A6-Aufenthaltsbestätigung | Paket 6, Betreiber | Arbeitsfassung vorhanden, nicht versendbar | +| Prüfung der übernommenen Freigabe bestehender Vorlagen | Betreiber | Sie gelten als freigegeben, weil sie schon verwendet wurden | + +Grundsatzentscheidungen mit Wirkung auf das Geschäftsmodell wurden nicht getroffen. B1, B3, B4 und B5 bleiben offen. + +--- + +## 9. Empfehlung für Paket 4 + +Paket 4 („Ein Eingang für alle Kanäle“) kann direkt auf diesem Stand aufsetzen: +1. **Automatisch übernommene Portalbuchungen** (Portalmail, sicher erkannte iCal-Reservierung) rufen nach `TakeOverExternalBooking` nur `CaseAutomation::advance` auf. Die Unterlagen laufen dann ohne weiteren Code durch die Zusammenstellung und warten, solange Freigaben fehlen. +2. **Vor dem Einschalten der Automatik je Portal** die Freigaben aus §8 erledigen; sonst entstehen viele Prüfaufgaben. +3. **Portalstorno als Ereignis** (Aufgabe „FeWo-direkt meldet Stornierung – prüfen“) gehört zu Paket 4; die Stornobestätigung als Dokumentart folgt in Paket 5 und kann `DocumentKind` und die Zusammenstellung wiederverwenden. +4. **Beobachtungsmodus** für Portalmails (Annahme §8.5) zuerst auf dem Testsystem, bevor Vorgänge ohne Klick entstehen. + +Vor Paket 4 sollte der Stand von Paketen 1–3 auf dem Testsystem abgenommen werden. Dazu gehören die Migration auf MariaDB und die Bedienprobe mit der Vermieterin. diff --git a/docs/STATUS.md b/docs/STATUS.md index dfe6319..d982543 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,7 @@ # Projektstand +**Dokumentenzusammenstellung und Vorlagensteuerung – Paket 3 der Prozessarchitektur v0.10 (02.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Vor jedem Dokument dieselbe Zusammenstellung (`App\Documents\DocumentComposer`, Ansicht `filament/document-composition`): Empfänger, Zeitraum, Preis mit Herkunft, Leistungen, Stornoregel, Vorlage mit Herkunft, Anlagen, Hinweise (fehlt / bitte prüfen / Info), E-Mail- und PDF-Vorschau. Dokumentart je Vorgang automatisch (`App\Enums\DocumentKind`): Anfrage → Angebot mit Annahmelink, eigene Buchung → Bestätigung mit Mietvertrag, beim Portal verbindlich (A3/A4) → **Buchungsunterlagen ohne Annahmelink** (`BookingDocumentation`). Unterlagen verbindlicher Vorgänge nur über `SendBookingDocuments` (automatisch nur ohne Prüfpunkte, von Hand mit bestätigten Hinweisen, einmalig per Sperre); Angebote mit `expected_version` gegen Doppelversand; ohne Vorreservierung (Hold 0) kein Angebot ohne ausdrückliche Entscheidung. Vorlagen haben Freigabe und „gibt nur Portalbedingungen wieder“ (entfallen bei Textänderung); die Buchungsunterlagen extern sind eine Arbeitsfassung bis zur Freigabe unter So arbeite ich › Dokumente. **648 Tests grün**, Browserprüfung durchgeführt. Ergebnis, offene Freigaben (FeWo-direkt-Vorlage FW-01, Unterlagentext) und Empfehlung Paket 4: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md). + **Vorgangskern und geführte Vorgangsbearbeitung – Pakete 1 und 2 der Prozessarchitektur v0.10 (01.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Die Buchung ist der einheitliche Vorgang (Eingangsart, Vorgangsart A1–A6, eingefrorenes Abwicklungsprofil, gespeicherter Verlauf `booking_events`); Gast, Personen und Preis dürfen unbekannt sein, keine Platzhalter-Gäste mehr. Einstellungen in Ebenen: System › **So arbeite ich** (Vermieterstandard) → Abweichung der Wohnung (Expertenansicht) → Abweichung je Portal und Buchungstyp → Vorgang (`App\Process\ProcessSettings`). Ein Übernahmeweg für beim Portal feste Buchungen (`TakeOverExternalBooking`, Portalpreis als eine Position) ersetzt „Portal-Buchung erfassen“ und die Logik von „Akte anlegen“. Startseite **„Zu erledigen“**, neue Vorgangsseite (Stand in einem Satz, „Als Nächstes“, Ablauf, Verlauf, Hauptknopf, Automatik/Freigabe, „Beenden“ nur über Storno), „Neu“-Dialog mit drei Einstiegen, Status von Hand nur im Expertenmodus. Migration übernimmt bisheriges Verhalten unverändert (Bericht `php artisan process:settings-report`). **634 Tests grün**, Pint. Ergebnis, Abnahmekriterien und offene Punkte: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P1_P2.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P1_P2.md). Vor dem Deployment: Migration auf dem Testsystem (MariaDB) prüfen, Bedienprobe mit der Vermieterin. **Buchungsprozess – Übergabe an eine neue Session (30.10.2026, durch v0.10 und `feature/vorgang` weitgehend überholt):** Die Portal-Erweiterungen des Buchungsprozesses (Portal-Direktbuchung erfassen, „Akte anlegen“, Statuswechsel von Hand, Menü) wurden neben dem Angebotsablauf statt auf ihm gebaut und sind für den Betreiber nicht brauchbar. **Vor jeder Arbeit am Buchungsprozess `docs/UEBERGABE-BUCHUNGSPROZESS.md` lesen** (Anforderungen, Stand, Mängelliste, empfohlenes Vorgehen) und das Konzept dort mit dem Betreiber abstimmen, bevor Code entsteht. diff --git a/resources/views/filament/document-composition.blade.php b/resources/views/filament/document-composition.blade.php new file mode 100644 index 0000000..5ec53cc --- /dev/null +++ b/resources/views/filament/document-composition.blade.php @@ -0,0 +1,75 @@ +{{-- The one composition shown before every document (UMSETZUNGSPLAN_v0.10 §4.5). --}} +@php + /** @var \App\Documents\DocumentComposition $composition */ + $c = $composition; + $money = fn (?int $cents): string => $cents === null ? 'noch nicht bekannt' : \App\Support\Money::format($cents); + $row = 'display:grid;grid-template-columns:11rem 1fr;gap:.75rem;padding:.55rem 0;border-bottom:1px solid rgba(128,128,128,.18)'; + $label = 'color:#6b7280'; + $box = fn (string $color): string => "border-left:4px solid {$color};background:rgba(128,128,128,.06);padding:.6rem .8rem;border-radius:.375rem;margin-bottom:.5rem"; +@endphp +
+ @if ($c->blockers() !== []) +
+ Fehlt noch – so kann nichts gesendet werden +
    @foreach ($c->blockers() as $message)
  • {{ $message }}
  • @endforeach
+
+ @endif + @if ($c->toConfirm() !== []) +
+ Bitte prüfen – automatisch wird so nichts versendet; von Hand erst nach Ihrer Bestätigung unten. +
    @foreach ($c->toConfirm() as $message)
  • {{ $message }}
  • @endforeach
+
+ @endif + @if ($c->information() !== []) +
+
    @foreach ($c->information() as $message)
  • {{ $message }}
  • @endforeach
+
+ @endif + +
Dokument
{{ $c->kind->getLabel() }}
+
An
{{ $c->recipientName() ?? 'Gast noch nicht bekannt' }} · {{ $c->recipientEmail() ?? 'keine E-Mail-Adresse' }}
+
Eingang
{{ $c->intakeLabel }}@if ($c->draft->portal_reference) · Buchungsnummer {{ $c->draft->portal_reference }}@endif
+
+
Wohnung und Zeitraum
+
{{ $c->draft->property->name }} · {{ $c->draft->arrival->format('d.m.Y') }} – {{ $c->draft->departure->format('d.m.Y') }} ({{ $c->draft->nights() }} Nächte) · {{ $c->draft->guests ? $c->draft->guests.' Personen' : 'Personen noch nicht bekannt' }}
+
+
+
Preis
+
+ @foreach ($c->priceLines as $line) +
{{ $line['label'] }}{{ $money($line['amount']) }}
+ @endforeach +
Gesamtpreis{{ $money($c->draft->total) }}
+
Herkunft: {{ $c->priceSource }}
+
+
+
Leistungen
{{ $c->services === [] ? 'keine Zusatzleistungen' : implode(', ', $c->services) }}
+ @if ($c->kind->isForGuests()) +
Stornoregel
@foreach ($c->cancellation as $line)
{{ $line }}
@endforeach
+
+
Vorlage
+
{{ $c->templateLabel() }} – {{ $c->templateSource }} + @if ($expert && $c->template) +
Freigegeben: {{ $c->template->isReleased() ? 'ja, '.$c->template->released_at->format('d.m.Y').' ('.$c->template->released_by.')' : 'nein' }} · Portalbedingungen bestätigt: {{ $c->template->confirmsPortalTerms() ? 'ja' : 'nein' }}
+ @endif +
+
+
Anlagen
{{ $c->annexes === [] ? 'keine' : implode(', ', array_column($c->annexes, 'label')) }}
+
+
Annahme
+
{{ $c->kind->hasAcceptanceLink() ? 'Mit Link zum Annehmen, gültig bis '.$c->draft->hold_expires_at?->format('d.m.Y, H:i').' Uhr' : 'Kein Annahmelink' }}
+
+ @endif + + @if ($c->kind->isAvailable() && $c->kind->isForGuests()) +
+ Vorschau der E-Mail + +
+
+ Vorschau des Dokuments +

Als PDF öffnen (zeigt den aktuellen Stand dieser Zusammenstellung)

+ +
+ @endif +
diff --git a/resources/views/mail/booking-documentation.blade.php b/resources/views/mail/booking-documentation.blade.php new file mode 100644 index 0000000..b0f70c6 --- /dev/null +++ b/resources/views/mail/booking-documentation.blade.php @@ -0,0 +1,44 @@ +{{-- Working draft (package 3): released by the landlord under "So arbeite ich › Dokumente" before it goes out automatically. --}} +@php($portal = $booking->processChannel()?->name ?? 'das Portal') + +# Ihre Buchung der {{ $booking->property->name }} + +Guten Tag {{ $booking->guest->full_name }}, + +vielen Dank für Ihre Buchung über {{ $portal }}. Ihre Buchung ist dort verbindlich zustande gekommen. Hier erhalten Sie Ihre Buchungsunterlagen von uns als Gastgeber. + +**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
+@if ($booking->guests) +**Personen:** {{ $booking->guests }}
+@endif +@if ($booking->portal_reference) +**Buchungsnummer bei {{ $portal }}:** {{ $booking->portal_reference }}
+@endif +**Unsere Nummer:** {{ $booking->reference }} + +@if ($booking->total !== null) +**Gesamtpreis laut {{ $portal }}:** {{ \App\Support\Money::format($booking->total) }} +@endif + +@if ($booking->wantsPaymentTasks()) +## Zahlung + +Bitte überweisen Sie die **Anzahlung von {{ \App\Support\Money::format($booking->deposit) }}** bis zum **{{ $booking->deposit_due_on?->format('d.m.Y') }}** und den **Restbetrag von {{ \App\Support\Money::format($booking->total - $booking->deposit) }}** bis zum **{{ $booking->balance_due_on?->format('d.m.Y') }}**. + +@include('mail.partials.bank') +@else +Die Zahlung läuft über {{ $portal }}. +@endif + +Ihre **Buchungsunterlagen** finden Sie als PDF im Anhang. + +@if ($booking->process()->guestMessages() === \App\Enums\Responsibility::Landlord) +Kurz vor Ihrer Anreise erhalten Sie von uns alle Informationen zu Schlüsselübergabe, Parken und WLAN. +@endif + +Bei Fragen antworten Sie einfach auf diese E-Mail. + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/pdf/contract-document.blade.php b/resources/views/pdf/contract-document.blade.php index fbe66fb..5126931 100644 --- a/resources/views/pdf/contract-document.blade.php +++ b/resources/views/pdf/contract-document.blade.php @@ -3,7 +3,7 @@ - Mietvertrag {{ $booking->reference }} + {{ ($kind ?? null) === \App\Enums\DocumentKind::ExternalRecord ? 'Buchungsunterlagen' : 'Mietvertrag' }} {{ $booking->reference }} + + + + + @if ($logo ?? null) + + @endif + +

Aufenthaltsbestätigung

+

Nummer {{ $booking->reference }} · ausgestellt am {{ now()->format('d.m.Y') }}

+ +

Hiermit bestätigen wir den folgenden Aufenthalt. Es handelt sich um eine private Überlassung, nicht um einen Mietvertrag.

+ + + + + + + @if ($booking->guests) + + @endif + @if ($booking->total) + + @endif +
Gast{{ $booking->guestName() }}
Wohnung{{ $booking->property->name }}, {{ $booking->property->address }}
Anreise{{ $booking->arrival->translatedFormat('l, d.m.Y') }}
Abreise{{ $booking->departure->translatedFormat('l, d.m.Y') }}
Personen{{ $booking->guests }}
Vereinbarter Betrag{{ \App\Support\Money::format($booking->total) }}
+ +

{{ $owner['name'] ?? '' }}

+ + diff --git a/tests/Feature/BookingFileTest.php b/tests/Feature/BookingFileTest.php index 740b006..aa579a0 100644 --- a/tests/Feature/BookingFileTest.php +++ b/tests/Feature/BookingFileTest.php @@ -62,7 +62,7 @@ public function test_next_step_follows_the_state_of_the_booking(): void $this->assertStringContainsString('Angebot liegt beim Gast', CaseActivities::situation($offer)); $confirmed = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05', 'deposit_due_on' => '2026-10-25', 'balance_due_on' => '2026-11-20', 'total' => 100000, 'deposit' => 30000]); - $this->assertSame('resendConfirmation', CaseActivities::next($confirmed)?->action); + $this->assertSame('sendDocuments', CaseActivities::next($confirmed)?->action); $this->travelTo(CarbonImmutable::parse('2026-12-02 12:00')); $confirmed->update(['status' => BookingStatus::Paid, 'total' => 0, 'deposit' => 0]); @@ -77,7 +77,7 @@ public function test_portal_booking_is_recognised_without_payment_steps_and_asks $this->assertSame(CaseType::A4, $booking->caseType()); $this->assertStringContainsString('Gebucht über FeWo-direkt', CaseActivities::situation($booking)); - $this->assertSame('resendConfirmation', CaseActivities::next($booking)?->action); + $this->assertSame('sendDocuments', CaseActivities::next($booking)?->action); $keys = array_map(fn ($activity) => $activity->key, CaseActivities::for($booking)); $this->assertContains('payment', $keys); $this->assertNotContains('deposit', $keys); diff --git a/tests/Feature/CancellationPolicyTest.php b/tests/Feature/CancellationPolicyTest.php index 81717c3..769c07c 100644 --- a/tests/Feature/CancellationPolicyTest.php +++ b/tests/Feature/CancellationPolicyTest.php @@ -88,7 +88,7 @@ public function test_cost_is_calculated_from_the_rent_or_from_the_total_as_the_r public function test_the_offer_freezes_the_rule_and_the_contract_can_show_it(): void { $policy = $this->policy(); - $template = ContractTemplate::query()->create(['name' => 'Direkt', 'version' => 1, 'body' => '

Storno:

{{ storno_regel }}', 'cancellation_policy_id' => $policy->id]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'Direkt', 'version' => 1, 'body' => '

Storno:

{{ storno_regel }}', 'cancellation_policy_id' => $policy->id]); $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); $policy->update(['tiers' => [['min_days' => 0, 'percent' => 5]]]); @@ -168,7 +168,7 @@ private function booking(string $arrival = '2026-11-07', string $departure = '20 private function offerWith(CancellationPolicy $policy, string $arrival = '2026-11-07', string $departure = '2026-11-10', bool $confirm = false): Booking { - $template = ContractTemplate::query()->firstOrCreate(['name' => 'T'.$policy->id, 'version' => 1], ['cancellation_policy_id' => $policy->id]); + $template = ContractTemplate::query()->firstOrCreate(['name' => 'T'.$policy->id, 'version' => 1], ['cancellation_policy_id' => $policy->id, 'released_at' => now()]); $offer = app(SendOffer::class)->handle($this->booking($arrival, $departure), ['contract_template_id' => $template->id]); if ($confirm) { $offer->update(['status' => BookingStatus::Confirmed, 'hold_expires_at' => null]); diff --git a/tests/Feature/CaseCoreTest.php b/tests/Feature/CaseCoreTest.php index 1da0fb5..c306272 100644 --- a/tests/Feature/CaseCoreTest.php +++ b/tests/Feature/CaseCoreTest.php @@ -128,8 +128,8 @@ public function test_a_property_deviation_sits_between_landlord_default_and_chan /** 1.5 */ public function test_one_mixed_portal_handles_requests_and_bindings_differently(): void { - $inquiryTemplate = ContractTemplate::query()->create(['name' => 'Anfrage', 'terms' => '

A

']); - $bookingTemplate = ContractTemplate::query()->create(['name' => 'Portalbuchung', 'terms' => '

B

']); + $inquiryTemplate = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'Anfrage', 'terms' => '

A

']); + $bookingTemplate = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'Portalbuchung', 'terms' => '

B

']); $portal = Channel::factory()->for($this->property)->create(['booking_model' => 'mixed', 'process_overrides' => [ 'inquiry' => ['contract_template_id' => $inquiryTemplate->id], 'booking' => ['contract_template_id' => $bookingTemplate->id, 'payments' => 'portal'], diff --git a/tests/Feature/ContractAnnexTest.php b/tests/Feature/ContractAnnexTest.php index 28106e6..494d1ee 100644 --- a/tests/Feature/ContractAnnexTest.php +++ b/tests/Feature/ContractAnnexTest.php @@ -53,7 +53,7 @@ public function test_conditions_decide_which_annexes_fit_a_booking(): void $withLinen = $this->annex('Wäsche', ContractAnnex::EXTRA, $linen->id); $viaPortal = $this->annex('Portal', ContractAnnex::CHANNEL, $portal->id); $manual = $this->annex('Key', ContractAnnex::MANUAL); - $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$always->id, $withLinen->id, $viaPortal->id, $manual->id]]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'T', 'version' => 1, 'annex_ids' => [$always->id, $withLinen->id, $viaPortal->id, $manual->id]]); $plain = $this->booking(); $this->assertSame(['WLAN'], $template->annexesFor($plain)->pluck('name')->all()); @@ -68,7 +68,7 @@ public function test_conditions_decide_which_annexes_fit_a_booking(): void public function test_the_offer_freezes_the_matching_annexes_and_shows_them_everywhere(): void { $annex = $this->annex('WLAN', ContractAnnex::ALWAYS, null, 'Anlage WLAN', '

WLAN für {{ mieter }}

'); - $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'body' => '

Vertrag

', 'annex_ids' => [$annex->id]]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'T', 'version' => 1, 'body' => '

Vertrag

', 'annex_ids' => [$annex->id]]); $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); @@ -86,7 +86,7 @@ public function test_an_explicit_selection_in_the_offer_replaces_the_automatic_o { $auto = $this->annex('WLAN', ContractAnnex::ALWAYS); $manual = $this->annex('Key', ContractAnnex::MANUAL); - $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$auto->id]]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'T', 'version' => 1, 'annex_ids' => [$auto->id]]); $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id, 'annex_ids' => [$manual->id]]); $this->assertSame(['Key'], array_column($offer->offer_terms['annexes'], 'name')); @@ -98,7 +98,7 @@ public function test_an_explicit_selection_in_the_offer_replaces_the_automatic_o public function test_used_annex_versions_are_locked_and_new_versions_can_be_made(): void { $annex = $this->annex('WLAN', ContractAnnex::ALWAYS); - $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); $this->assertTrue(ContractAnnexResource::canEdit($annex)); app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); @@ -113,7 +113,7 @@ public function test_recording_extra_services_in_the_booking_changes_the_presele { $linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 0, 'pricing' => 'per_item', 'is_active' => true]); $annex = $this->annex('Wäsche', ContractAnnex::EXTRA, $linen->id); - $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); + $template = ContractTemplate::query()->create(['released_at' => now(), 'name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); $this->property->update(['contract_template_id' => $template->id]); $booking = $this->booking(); $this->actingAs(User::factory()->create()); diff --git a/tests/Feature/ContractDocumentTest.php b/tests/Feature/ContractDocumentTest.php index f31acdd..5240bbf 100644 --- a/tests/Feature/ContractDocumentTest.php +++ b/tests/Feature/ContractDocumentTest.php @@ -8,6 +8,7 @@ use App\Documents\OfferTerms; use App\Enums\BookingStatus; use App\Mail\BookingConfirmed; +use App\Mail\BookingDocumentation; use App\Models\Booking; use App\Models\Channel; use App\Models\ContractTemplate; @@ -81,7 +82,8 @@ public function test_offer_with_a_document_template_freezes_body_and_property_fa public function test_template_without_a_body_keeps_the_text_blocks(): void { $template = $this->template('Bausteine', null, null, null); - $template->update(['texts' => ['terms' => '

NUR BAUSTEIN

']]); + $template->fill(['texts' => ['terms' => '

NUR BAUSTEIN

']])->applyStatements(released: true, portalTerms: false, actor: 'Test'); + $template->save(); $offer = $this->offer(['contract_template_id' => $template->id]); @@ -106,7 +108,9 @@ public function test_portal_reservation_uses_the_reservation_template_and_a_conf $this->assertSame('FeWo-direkt', $booking->offer_terms['template']['name']); $this->assertStringContainsString('PORTAL-VERTRAG', OfferTerms::document($booking)['body']); Storage::disk('local')->assertExists($booking->contract_path); - Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => ! str_contains($mail->render(), 'überweisen')); + // Binding on the portal: booking documentation without payment instructions (payments run via the portal). + Mail::assertSent(BookingDocumentation::class, fn (BookingDocumentation $mail): bool => ! str_contains($mail->render(), 'überweisen') && str_contains($mail->render(), 'Die Zahlung läuft über')); + Mail::assertNotSent(BookingConfirmed::class); $inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'process_overrides' => ['inquiry' => ['contract_template_id' => $inquiry->id], 'booking' => ['contract_template_id' => $reservation->id]]]); $this->assertSame($inquiry->id, OfferTerms::templateFor($this->booking(['import_channel_id' => $inquiryPortal->id, 'source' => 'portal', 'arrival' => '2026-12-01', 'departure' => '2026-12-03']))->id); @@ -129,7 +133,7 @@ public function test_installer_creates_the_fewo_direkt_template_once_and_sets_pr private function template(string $name, ?string $body, ?string $annexTitle, ?string $annexBody): ContractTemplate { - return ContractTemplate::query()->create(['name' => $name, 'version' => 1, 'body' => $body, 'annex_title' => $annexTitle, 'annex_body' => $annexBody]); + return ContractTemplate::query()->create(['released_at' => now(), 'name' => $name, 'version' => 1, 'body' => $body, 'annex_title' => $annexTitle, 'annex_body' => $annexBody]); } /** diff --git a/tests/Feature/ContractTemplateTest.php b/tests/Feature/ContractTemplateTest.php index b440bf7..18b6ef7 100644 --- a/tests/Feature/ContractTemplateTest.php +++ b/tests/Feature/ContractTemplateTest.php @@ -120,7 +120,7 @@ public function test_final_contract_is_a_document_of_record_that_is_never_rewrit */ private function template(string $name, array $texts): ContractTemplate { - return ContractTemplate::query()->create(['name' => $name, 'version' => 1, 'texts' => $texts]); + return ContractTemplate::query()->create(['released_at' => now(), 'name' => $name, 'version' => 1, 'texts' => $texts]); } /** diff --git a/tests/Feature/DocumentCompositionTest.php b/tests/Feature/DocumentCompositionTest.php new file mode 100644 index 0000000..d1d0474 --- /dev/null +++ b/tests/Feature/DocumentCompositionTest.php @@ -0,0 +1,375 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + $this->portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'process_overrides' => ['booking' => ['payments' => 'portal']]]); + Mail::fake(); + Storage::fake('local'); + Http::fake(['*' => Http::response('', 500)]); + $this->withoutVite(); + $this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple])); + } + + /** 3.1 */ + public function test_the_offer_composition_shows_everything_and_an_adjustment_updates_it(): void + { + $booking = $this->request(); + $composition = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer); + + $this->assertSame('Gesa Gast', $composition->recipientName()); + $this->assertSame('gesa@example.org', $composition->recipientEmail()); + $this->assertSame('aus Ihren Preisen berechnet', $composition->priceSource); + $this->assertTrue($composition->kind->hasAcceptanceLink()); + $this->assertTrue($composition->canSendAutomatically()); + $total = $composition->draft->total; + + // The same picture the landlord sees in the dialog; an adjustment recalculates it. + $adjusted = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer, ['price_adjustment' => -5000, 'price_adjustment_label' => 'Stammgast']); + $html = view('filament.document-composition', ['composition' => $adjusted, 'expert' => false, 'mailPreview' => '', 'documentPreview' => '', 'pdfUrl' => '#'])->render(); + foreach (['Angebot mit Annahmelink', 'Gesa Gast · gesa@example.org', 'Herkunft: aus Ihren Preisen berechnet', 'Stornoregel', 'Vorlage', 'Anlagen', 'Stammgast', Money::format($total - 5000)] as $text) { + $this->assertStringContainsString(e($text), $html); + } + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('sendOffer', ['price_adjustment' => '-50', 'price_adjustment_label' => 'Stammgast']) + ->assertHasNoFormErrors() + ->assertNotified('Angebot gesendet'); + + $this->assertSame($total - 5000, $booking->fresh()->total); + $this->assertSame('offer', $booking->events()->where('type', 'document')->sole()->data['kind']); + } + + /** 3.2 */ + public function test_each_case_gets_its_document_without_choosing_a_template(): void + { + $inquiryTemplate = $this->template('Direktanfrage', '

ANGEBOTSVERTRAG {{ mieter }}

'); + $portalTemplate = $this->template('FeWo-direkt', '

PORTALUNTERLAGEN {{ mieter }}

', portalTerms: true); + Settings::tenant()->update(['process_defaults' => ['contract_template_id' => $inquiryTemplate->id]]); + $this->portal->update(['process_overrides' => ['booking' => ['payments' => 'portal', 'contract_template_id' => $portalTemplate->id]]]); + DocumentReleases::set(DocumentKind::ExternalRecord, true, 'Ingrid'); + + $request = app(SendOffer::class)->handle($this->request()); + $this->assertSame('Direktanfrage', $request->offer_terms['template']['name']); + Mail::assertSent(OfferMade::class, fn (OfferMade $mail): bool => str_contains($mail->offerUrl, '/angebot/')); + + $portalBooking = $this->portalBooking(); + $composition = app(SendBookingDocuments::class)->compose($portalBooking); + $this->assertSame(DocumentKind::ExternalRecord, $composition->kind); + $this->assertFalse($composition->kind->hasAcceptanceLink()); + $this->assertStringContainsString('eingestellt für FeWo-direkt', $composition->templateSource); + $this->assertTrue($composition->canSendAutomatically()); + + $this->assertTrue(app(SendBookingDocuments::class)->handle($portalBooking)); + + $portalBooking->refresh(); + $this->assertSame('FeWo-direkt', $portalBooking->offer_terms['template']['name']); + $this->assertStringEndsWith('Buchungsunterlagen-'.$portalBooking->reference.'.pdf', $portalBooking->contract_path); + Mail::assertSent(BookingDocumentation::class, function (BookingDocumentation $mail): bool { + $html = $mail->render(); + + return ! str_contains($html, '/angebot/') && str_contains($html, 'Die Zahlung läuft über FeWo-direkt') && ! str_contains($html, 'überweisen'); + }); + Mail::assertNotSent(BookingConfirmed::class); + [$view, $data] = app(RentalContract::class)->view($portalBooking, DocumentKind::ExternalRecord); + $this->assertStringContainsString('Buchungsunterlagen', view($view, $data)->render()); + } + + /** 3.3 */ + public function test_an_unconfirmed_fee_in_a_portal_template_needs_a_conscious_confirmation(): void + { + $policy = CancellationPolicy::query()->create(['name' => 'Direktbuchung Standard', 'base' => CancellationPolicy::BASE_RENT, 'tiers' => [['min_days' => 30, 'percent' => 0], ['min_days' => 0, 'percent' => 100]], 'replacement_fee' => 3500]); + $template = $this->template('FeWo-direkt Direktbuchung', '

Mietvertrag mit {{ mieter }}. Endreinigung 60,00 € extra.

'); + $template->fill(['cancellation_policy_id' => $policy->id])->applyStatements(released: true, portalTerms: false, actor: 'Ingrid'); + $template->save(); + $this->portal->update(['process_overrides' => ['booking' => ['payments' => 'portal', 'contract_template_id' => $template->id]]]); + DocumentReleases::set(DocumentKind::ExternalRecord, true, 'Ingrid'); + $booking = $this->portalBooking(); + + $points = app(SendBookingDocuments::class)->compose($booking)->toConfirm(); + $this->assertStringContainsString('nicht als Wiedergabe der Bedingungen von FeWo-direkt bestätigt', implode(' ', $points)); + $this->assertStringContainsString('Ersatzmieter-Gebühr '.Money::format(3500), implode(' ', $points)); + $this->assertStringContainsString('60,00 € (im Text)', implode(' ', $points)); + + // Automatic: nothing goes out, the case says what to check. + $booking->update(['processing_mode' => 'automatic']); + $this->assertNotSame([], app(SendBookingDocuments::class)->automatically($booking->fresh())); + Mail::assertNothingSent(); + $this->assertStringContainsString('vor dem Versand zu prüfen', CaseActivities::next($booking->fresh())->detail); + + // By hand: refused without, sent with the explicit confirmation, which is recorded. + try { + app(SendBookingDocuments::class)->handle($booking->fresh()); + $this->fail('Sending without confirmation must be refused.'); + } catch (ReservationException $exception) { + $this->assertStringContainsString('ausdrücklich bestätigen', $exception->getMessage()); + } + Mail::assertNothingSent(); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('sendDocuments', ['acknowledged' => false]) + ->assertHasFormErrors(['acknowledged']); + Mail::assertNothingSent(); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('sendDocuments', ['acknowledged' => true]) + ->assertNotified('Unterlagen gesendet'); + + Mail::assertSent(BookingDocumentation::class, 1); + $confirmed = $booking->events()->where('type', 'document')->where('summary', 'Hinweise vor dem Versand bestätigt')->sole(); + $this->assertSame('Ingrid', $confirmed->actor); + $this->assertStringContainsString('Ersatzmieter-Gebühr', implode(' ', $confirmed->data['confirmed'])); + } + + public function test_without_any_template_a_portal_booking_does_not_get_our_website_terms_unchecked(): void + { + DocumentReleases::set(DocumentKind::ExternalRecord, true, 'Ingrid'); + $booking = $this->portalBooking(); + + $this->assertStringContainsString('keine eigene Vorlage', implode(' ', app(SendBookingDocuments::class)->compose($booking)->toConfirm())); + } + + public function test_documents_are_sent_once_whatever_runs_again(): void + { + $template = $this->template('FeWo-direkt', '

Buchung {{ mieter }}

', portalTerms: true); + $this->portal->update(['process_overrides' => ['booking' => ['payments' => 'portal', 'contract_template_id' => $template->id]]]); + DocumentReleases::set(DocumentKind::ExternalRecord, true, 'Ingrid'); + $booking = $this->portalBooking(); + + $this->assertSame([], app(SendBookingDocuments::class)->automatically($booking)); + $this->assertSame([], app(SendBookingDocuments::class)->automatically($booking->fresh())); + $this->assertTrue(app(SendBookingDocuments::class)->handle($booking)); + + Mail::assertSent(BookingDocumentation::class, 1); + } + + public function test_an_offer_is_not_sent_twice_by_a_repeated_release_or_automatic_run(): void + { + $booking = $this->request(); + $send = app(SendOffer::class); + + $send->handle($booking, ['expected_version' => 0]); + try { + $send->handle($booking->fresh(), ['expected_version' => 0]); + $this->fail('A repeated release must not send a second offer.'); + } catch (ReservationException $exception) { + $this->assertStringContainsString('schon ein Angebot gesendet', $exception->getMessage()); + } + + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]); + app(AutoOffer::class)->handle($booking->fresh()); + + $this->assertSame(1, $booking->fresh()->offer_version); + Mail::assertSent(OfferMade::class, 1); + } + + /** Hold = 0 until package 7: no binding offer by accident. */ + public function test_without_reservation_an_offer_with_acceptance_link_needs_an_explicit_decision(): void + { + Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]); + $booking = $this->request(); + $this->assertNull($booking->hold_expires_at); + + try { + app(SendOffer::class)->handle($booking); + $this->fail('An offer must not be made by accident when requests reserve nothing.'); + } catch (ReservationException $exception) { + $this->assertStringContainsString('reservieren Anfragen den Zeitraum nicht', $exception->getMessage()); + } + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + Mail::assertNothingSent(); + + Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false, 'processing' => 'automatic']]); + $this->assertNotSame([], app(AutoOffer::class)->handle($booking->fresh())); + Mail::assertNothingSent(); + + app(SendOffer::class)->handle($booking->fresh(), ['acknowledged' => true]); + $this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status); + } + + public function test_missing_contract_data_stops_the_automatic_offer(): void + { + $template = $this->template('Direkt', '

WLAN: {{ wohnung.wlan_passwort }}

'); + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'contract_template_id' => $template->id]]); + Storage::fake('local'); + + $booking = $this->request(sendMails: true); + + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + $this->assertStringContainsString('wohnung.wlan_passwort', implode(' ', app(AutoOffer::class)->blockers($booking->fresh()))); + Mail::assertNotSent(OfferMade::class); + } + + public function test_documents_already_sent_stay_as_they_were(): void + { + $template = $this->template('Direkt', '

ALTER TEXT {{ mieter }}

'); + Settings::tenant()->update(['process_defaults' => ['contract_template_id' => $template->id]]); + $booking = app(SendOffer::class)->handle($this->request()); + $offerHash = $booking->offer_hash; + app(ConfirmBooking::class)->handle($booking->fresh()); + $booking->refresh(); + $contract = $booking->contract_path; + $pdfHash = $booking->contract_pdf_sha256; + + $template->fill(['body' => '

NEUER TEXT

'])->applyStatements(released: true, portalTerms: false, actor: 'Ingrid'); + $template->save(); + Settings::tenant()->update(['process_defaults' => ['contract_template_id' => null]]); + + $composition = app(SendBookingDocuments::class)->compose($booking->fresh()); + $this->assertTrue($composition->termsFrozen); + $this->assertStringContainsString('ALTER TEXT', $composition->terms['document']['body']); + $this->assertSame([], $composition->toConfirm()); + + app(ConfirmBooking::class)->resend($booking->fresh()); + $booking->refresh(); + $this->assertSame($contract, $booking->contract_path); + $this->assertSame($pdfHash, $booking->contract_pdf_sha256); + $this->assertSame($offerHash, $booking->offer_hash); + $this->assertStringContainsString('ALTER TEXT', $booking->offer_terms['document']['body']); + } + + public function test_a_template_statement_lapses_when_its_text_changes(): void + { + $template = $this->template('Direkt', '

Text

', portalTerms: true); + $this->assertTrue($template->isReleased() && $template->confirmsPortalTerms()); + + $template->update(['body' => '

Geänderter Text

']); + + $this->assertFalse($template->fresh()->isReleased()); + $this->assertFalse($template->fresh()->confirmsPortalTerms()); + $this->assertFalse($template->newVersion()->isReleased()); + } + + public function test_the_landlord_releases_the_booking_documentation_on_the_settings_page(): void + { + $this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Expert])); + $this->assertFalse(DocumentReleases::isReleased(DocumentKind::ExternalRecord)); + + Livewire::test(HandlingSettings::class) + ->assertSee('Buchungsunterlagen (beim Portal gebucht) – freigegeben') + ->fillForm(['document_releases' => ['external_record' => true]]) + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertTrue(DocumentReleases::isReleased(DocumentKind::ExternalRecord)); + $this->assertSame('Ingrid', DocumentReleases::decision(DocumentKind::ExternalRecord)['by']); + } + + /** A6 is prepared: a private stay gets a confirmation that is no rental contract, and it cannot be sent yet. */ + public function test_a_private_stay_confirmation_is_prepared_without_a_rental_contract(): void + { + $booking = $this->request(); + $booking->forceFill(['intake' => IntakeKind::Internal])->save(); + + $composition = app(DocumentComposer::class)->compose($booking->fresh()); + + $this->assertSame(DocumentKind::StayConfirmation, $composition->kind); + $this->assertFalse($composition->kind->containsContract()); + $this->assertStringContainsString('späteren Ausbauschritt', implode(' ', $composition->blockers())); + [$view, $data] = app(RentalContract::class)->view($booking, DocumentKind::StayConfirmation); + $html = view($view, $data)->render(); + $this->assertStringContainsString('nicht um einen Mietvertrag', $html); + $this->assertStringNotContainsString('Mietbedingungen', $html); + } + + public function test_the_pdf_preview_shows_the_composition_without_saving_anything(): void + { + $booking = $this->request(); + + $response = $this->get(route('filament.admin.document-preview', ['booking' => $booking->getRouteKey(), 'kind' => 'offer', 'changes' => base64_encode(json_encode(['price_adjustment' => -5000]))])); + + $response->assertOk()->assertHeader('Content-Type', 'application/pdf'); + $this->assertSame(0, $booking->fresh()->offer_version); + $this->assertNull($booking->fresh()->offer_path); + } + + private function request(bool $sendMails = false): Booking + { + return app(CreateReservation::class)->handle( + $this->property->fresh(), + new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), + ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'], + sendMails: $sendMails, + ); + } + + private function portalBooking(): Booking + { + return app(TakeOverExternalBooking::class)->handle( + $this->property, + $this->portal, + CarbonImmutable::parse('2026-12-05'), + CarbonImmutable::parse('2026-12-12'), + ['portal_total' => 97951, 'portal_reference' => 'HA-77', 'guest' => ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.org']], + ); + } + + private function template(string $name, string $body, bool $portalTerms = false): ContractTemplate + { + return ContractTemplate::query()->create([ + 'name' => $name, + 'version' => 1, + 'body' => $body, + 'released_at' => now(), + 'portal_terms_confirmed_at' => $portalTerms ? now() : null, + ]); + } +} diff --git a/tests/Feature/GuidedCaseHandlingTest.php b/tests/Feature/GuidedCaseHandlingTest.php index 93cbede..e5d817f 100644 --- a/tests/Feature/GuidedCaseHandlingTest.php +++ b/tests/Feature/GuidedCaseHandlingTest.php @@ -232,6 +232,7 @@ public function test_the_landlord_sets_defaults_on_one_page_and_a_portal_deviate Livewire::test(HandlingSettings::class) ->fillForm(['processing' => 'automatic', 'hold_hours' => 24, 'pre_reservation' => null]) ->call('save') + ->assertHasNoFormErrors() ->assertNotified('Gespeichert'); $this->assertSame(['processing' => 'automatic', 'hold_hours' => 24], Settings::tenant()->fresh()->process_defaults); diff --git a/tests/Feature/PortalBookingTest.php b/tests/Feature/PortalBookingTest.php index 211109c..1c32038 100644 --- a/tests/Feature/PortalBookingTest.php +++ b/tests/Feature/PortalBookingTest.php @@ -8,11 +8,13 @@ use App\Actions\SetBookingStatus; use App\Actions\TakeOverExternalBooking; use App\Availability\AvailabilityChecker; +use App\Documents\DocumentReleases; use App\Enums\AdminMode; use App\Enums\BookingStatus; use App\Enums\BookingTaskKind; use App\Enums\CaseType; use App\Enums\ChannelBookingModel; +use App\Enums\DocumentKind; use App\Enums\OccupationKind; use App\Enums\ProcessingMode; use App\Exceptions\ReservationException; @@ -22,10 +24,12 @@ use App\Filament\Resources\Bookings\Schemas\BookingForm; use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation; use App\Mail\BookingConfirmed; +use App\Mail\BookingDocumentation; use App\Models\BlockedPeriod; use App\Models\Booking; use App\Models\BookingTask; use App\Models\Channel; +use App\Models\ContractTemplate; use App\Models\Property; use App\Models\User; use App\Process\CaseActivities; @@ -83,21 +87,41 @@ public function test_a_binding_portal_booking_is_taken_over_without_offer_accept public function test_entering_the_contact_data_can_send_the_documents_automatically(): void { + $this->releaseDocumentation(); $booking = $this->takeOver(total: 50000); $message = app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'Gast@Example.test', 'street' => 'Hauptstr. 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn'], ProvideGuestContact::AUTOMATIC, guestConfirmed: true); $booking->refresh(); - $this->assertSame('Kontaktdaten gespeichert, Vertrag gesendet', $message); + $this->assertSame('Kontaktdaten gespeichert, Unterlagen gesendet', $message); $this->assertSame('gast@example.test', $booking->guest->email); $this->assertNotNull($booking->contract_path); $this->assertNotNull($booking->guest_confirmed_at); $this->assertSame(ProcessingMode::Automatic, $booking->processing_mode); - Mail::assertSent(BookingConfirmed::class, 1); + Mail::assertSent(BookingDocumentation::class, 1); + Mail::assertNotSent(BookingConfirmed::class); + } + + public function test_without_released_documentation_the_automatic_run_stops_and_says_what_to_check(): void + { + $booking = $this->takeOver(total: 50000); + + try { + app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'gast@example.test'], ProvideGuestContact::AUTOMATIC); + $this->fail('The documents must not be sent automatically.'); + } catch (ReservationException $exception) { + $this->assertStringContainsString('Arbeitsfassung', $exception->getMessage()); + $this->assertStringContainsString('keine eigene Vorlage', $exception->getMessage()); + } + + $this->assertNull($booking->fresh()->contract_path); + Mail::assertNothingSent(); + $this->assertSame('sendDocuments', CaseActivities::next($booking->fresh())?->action); } public function test_automatic_documents_wait_for_the_portal_price(): void { + $this->releaseDocumentation(); $booking = $this->takeOver(); $this->expectException(ReservationException::class); @@ -112,7 +136,7 @@ public function test_entering_the_contact_data_by_hand_sends_nothing_and_the_doc app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'gast@example.test'], ProvideGuestContact::MANUAL); $this->assertNull($booking->fresh()->contract_path); - $this->assertSame('resendConfirmation', CaseActivities::next($booking->fresh())?->action); + $this->assertSame('sendDocuments', CaseActivities::next($booking->fresh())?->action); Mail::assertNothingSent(); } @@ -317,4 +341,15 @@ private function takeOver(?int $total = null, ?string $reference = null, string ['portal_total' => $total, 'portal_reference' => $reference, 'guest' => $guest], ); } + + /** + * The landlord released the booking documentation and set a template for bookings via the portal that only + * reproduces the portal's terms. + */ + private function releaseDocumentation(): void + { + DocumentReleases::set(DocumentKind::ExternalRecord, true, 'Test'); + $template = ContractTemplate::query()->create(['name' => 'FeWo-direkt', 'version' => 1, 'body' => '

Buchung von {{ mieter }}

', 'released_at' => now(), 'portal_terms_confirmed_at' => now()]); + $this->portal->update(['process_overrides' => ['booking' => ['contract_template_id' => $template->id]]]); + } }