Dokumentenzusammenstellung und Vorlagensteuerung (Paket 3, Prozessarchitektur v0.10)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m59s

Eine Zusammenstellung vor jedem Dokument (Angebot, Bestaetigung, Buchungsunterlagen
extern), Dokumentart je Vorgangsart, Freigaben fuer Vorlagen und Dokumentarten,
Schutz vor unvereinbarten Bedingungen bei Portalbuchungen (E-004), kein doppelter
Versand, Absicherung Hold 0 bis Paket 7, A6-Aufenthaltsbestaetigung vorbereitet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-01 19:44:52 +01:00
1 parent 64248c09fa
commit cf11c8a474
45 files changed
+2385 -144

No files matched your search

+9 -2
View File
@@ -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()];
+16 -3
View File
@@ -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;
+16 -10
View File
@@ -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<string, ?string> $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';
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Actions;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Enums\DocumentKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use Illuminate\Support\Facades\Cache;
/**
* Sends the documents of a binding case – the confirmation with the rental contract, or the booking documentation of a
* booking already binding on a portal – from its composition ({@see DocumentComposer}). Automatically only when nothing
* is missing and nothing has to be confirmed; by hand after the landlord confirmed every point. The documents go out
* once: a lock and a fresh look at the case keep repeated runs, double clicks and parallel jobs from sending twice.
* Until the first document exists the terms are taken from the composition (template and annexes as chosen); after
* that they stay as they were sent.
*/
class SendBookingDocuments
{
public function __construct(private DocumentComposer $composer, private ConfirmBooking $confirm) {}
/**
* @param array<string, mixed> $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<string> 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<string, mixed> $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();
}
}
}
+28 -3
View File
@@ -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<int|string>, guest?: array<string, ?string>} $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<int|string>, guest?: array<string, ?string>, 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) {
+4 -4
View File
@@ -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'),
+404
View File
@@ -0,0 +1,404 @@
<?php
namespace App\Documents;
use App\Actions\SendOffer;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Throwable;
/**
* Prepares the document a case needs (UMSETZUNGSPLAN_v0.10 §4.5, package 3): applies the landlord's adjustments to a copy
* of the case, takes template and annexes from the process settings, captures the terms the document would freeze and
* lists – in plain words – what is missing, what has to be confirmed and what is only worth knowing. Nothing is saved.
*
* Only objective criteria lead to findings (missing or contradictory data, unreleased texts, terms not shown to be
* agreed); nationality or origin of a guest never do.
*/
class DocumentComposer
{
/** Placeholders that state payments to the landlord. */
private const PAYMENT_PLACEHOLDERS = ['anzahlung', 'restzahlung', 'restzahlung_faellig'];
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private ProcessSettings $settings,
) {}
/**
* @param array<string, mixed> $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<string, mixed> $changes
* @return list<DocumentFinding>
*/
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<DocumentFinding>
*/
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<string, mixed>|null $terms
* @return list<DocumentFinding>
*/
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<DocumentFinding>
*/
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<string>
*/
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<string, mixed>|null $terms
* @return list<string>
*/
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<string>
*/
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<string, mixed>|null $terms
* @return list<string>
*/
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<string, mixed>|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<string, mixed>|null $terms
* @return list<string>
*/
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<string, mixed> $changes
* @return array<string, ?string>
*/
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'));
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Booking;
use App\Models\ContractTemplate;
/**
* Everything a document of a case consists of before it is sent (UMSETZUNGSPLAN_v0.10 §4.5): recipient, stay, how the
* case came in, price with its origin, services, cancellation rule, template and annexes, and what has to be checked.
* The same composition is shown to the landlord, decides whether the automatic run may send, and is what is sent.
*/
final class DocumentComposition
{
/**
* @param Booking $draft the case as the document will show it (never saved)
* @param list<array{label: string, amount: int}> $priceLines
* @param list<string> $services
* @param list<string> $cancellation
* @param list<array{id: int, label: string}> $annexes
* @param array<string, mixed>|null $terms the terms the document freezes (null: the website texts apply live)
* @param list<DocumentFinding> $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<string>
*/
public function blockers(): array
{
return $this->messages(DocumentFinding::BLOCKER);
}
/**
* @param list<string> $except codes of findings left out
* @return list<string>
*/
public function toConfirm(array $except = []): array
{
return $this->messages(DocumentFinding::CONFIRM, $except);
}
/**
* @return list<string>
*/
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<string, mixed>
*/
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<string> $except
* @return list<string>
*/
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))));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Documents;
/**
* One finding of a document composition. A blocker stops the document (data missing or contradictory); a point to
* confirm stops the automatic run and needs the landlord's explicit confirmation before sending by hand; information
* only explains.
*/
final class DocumentFinding
{
public const BLOCKER = 'blocker';
public const CONFIRM = 'confirm';
public const INFO = 'info';
/** Code of the finding "the settings reserve nothing for requests" (Hold = 0, package 7). */
public const HOLD_ZERO = 'hold_zero';
public function __construct(
public readonly string $severity,
public readonly string $message,
public readonly ?string $code = null,
) {}
public static function blocker(string $message): self
{
return new self(self::BLOCKER, $message);
}
public static function confirm(string $message, ?string $code = null): self
{
return new self(self::CONFIRM, $message, $code);
}
public static function info(string $message): self
{
return new self(self::INFO, $message);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Tenant;
use App\Support\Settings;
/**
* Which document kinds the landlord has released for guests (tenants.document_releases). A kind that is not released is
* a working draft: it is never sent automatically, and by hand only after an explicit confirmation in the case.
*/
class DocumentReleases
{
public static function isReleased(DocumentKind $kind, ?Tenant $tenant = null): bool
{
$entry = self::entries($tenant)[$kind->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<string, mixed>
*/
private static function entries(?Tenant $tenant): array
{
return (array) (($tenant ?? Settings::tenant())?->document_releases ?? []);
}
}
+42 -19
View File
@@ -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<string, mixed>}
*/
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;
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Enums;
use App\Models\Booking;
use Filament\Support\Contracts\HasLabel;
/**
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case
* type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the
* confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation
* without an acceptance link (E-004). Information "unter Vorbehalt" (package 7) and the stay confirmation of A6
* (package 6) are prepared as working drafts but cannot be sent yet.
*/
enum DocumentKind: string implements HasLabel
{
case Offer = 'offer';
case Information = 'information';
case Confirmation = 'confirmation';
case ExternalRecord = 'external_record';
case StayConfirmation = 'stay_confirmation';
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Offer => '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',
};
}
}
@@ -0,0 +1,110 @@
<?php
namespace App\Filament\Forms;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation;
use App\Mail\OfferMade;
use App\Models\Booking;
use App\Models\User;
use Closure;
use Filament\Forms\Components\Checkbox;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Throwable;
/**
* The composition of a document inside an action modal: the same picture for offer, confirmation and booking
* documentation, recalculated whenever the landlord adjusts something, plus the explicit confirmation that is
* required when there is something to check.
*/
class DocumentCompositionFields
{
/** @var array<string, DocumentComposition> */
private static array $compositions = [];
/**
* @param Closure(Get): array<string, mixed> $changes the adjustments currently in the form
* @return list<View|Checkbox>
*/
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<string, mixed> $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<string, mixed> $changes
* @return array<string, mixed>
*/
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 '<p style="font-family:sans-serif">Keine Vorschau: Der Gast ist noch nicht bekannt.</p>';
}
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 '<p style="font-family:sans-serif">Die Vorschau der E-Mail ist gerade nicht möglich.</p>';
}
}
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 '<p style="font-family:sans-serif">Die Vorschau des Dokuments ist gerade nicht möglich.</p>';
}
}
}
+42 -2
View File
@@ -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('<ul style="list-style:disc;padding-left:1.25rem">'.collect(DocumentKind::cases())
->reject(fn (DocumentKind $kind): bool => in_array($kind, self::releasableKinds(), true) || ! $kind->isForGuests())
->map(fn (DocumentKind $kind): string => '<li><strong>'.e($kind->getLabel()).'</strong>: '.e($kind->description()).' '.e($kind->isAvailable() ? '(in Verwendung; Texte unter Webseite › Texte bzw. Vorlagen)' : '(Arbeitsfassung vorbereitet, noch nicht nutzbar)').'</li>')
->implode('').'</ul>')),
]),
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<DocumentKind>
*/
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.
*/
@@ -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();
@@ -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<Section>
*/
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<string> $fields
* @return array<string, mixed>
*/
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<string, mixed> $data
* @return array<string, mixed>
*/
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
@@ -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
.'<div style="margin-top:.5rem;color:#6b7280;font-size:.9rem">'.$mode.'</div>');
}
/**
* 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('<br>'));
}
/**
* @return list<string>
*/
@@ -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<string, mixed> $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;
}
}
@@ -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<string, mixed> $data
* @return array<string, mixed>
*/
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<string, mixed> $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;
}
}
@@ -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(),
]);
}
@@ -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'),
])
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Controllers;
use App\Documents\DocumentComposer;
use App\Documents\RentalContract;
use App\Enums\DocumentKind;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* The PDF of a document composition as it would be sent, for the landlord's preview in the admin area. Nothing is
* stored; the case is only read (and only within the current landlord, by the tenant scope of the route binding).
*/
class DocumentPreviewController extends Controller
{
public function __invoke(Request $request, Booking $booking, string $kind, DocumentComposer $composer, RentalContract $contract): Response
{
$documentKind = DocumentKind::tryFrom($kind);
abort_if($documentKind === null || ! $documentKind->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',
]);
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Mail;
use App\Documents\RentalContract;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* The booking documentation for a booking already binding on a portal (A3/A4): the stay as booked there and our
* document, without an acceptance link and without a cancellation link of our own (E-004).
*/
class BookingDocumentation extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Buchungsunterlagen '.($this->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<Attachment>
*/
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')] : [];
}
}
+69 -2
View File
@@ -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;
}
/**
+2 -1
View File
@@ -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',
+14 -2
View File
@@ -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) {
+6 -10
View File
@@ -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<string> 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 [];
@@ -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([