Files
fewo-stommer/app/Documents/DocumentComposer.php
T
LarsandClaude Opus 5.5 3bcfc09417
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
- Paket 8: Zahlungsarten (Gast an uns, laut Portal, Auszahlung, Erstattung),
  Portalbeträge als Angaben mit Quelle, Übersicht nach Zuständigkeit (R09).
- Paket 5: Ändern mit Folgenvorschau, vereinbart oder dem Gast vorgeschlagen
  (signierter Link), ein Stornoweg mit Grund und Erstattung, Portalstorno erst
  nach Bestätigung.
- Paket 6: eigene Nutzung, Besuch und Sperre als Vorgang mit Kurabgabe und
  Aufenthaltsbestätigung; Bestandsübernahme der Sperren mit identischem Export.
- Wirksame Einstellungen (Expertenansicht), Abnahmekatalog T01–T14, Ergebnis-,
  Abnahme- und Konfigurationsdokument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:16:47 +01:00

406 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\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) {
$kind === DocumentKind::StayConfirmation => null,
$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'));
}
}