Compare commits

...
Author SHA1 Message Date
LarsandClaude Opus 5.5 234e642e4d Pakete 7 und 9 abgeschlossen: Wirksamkeit, Browserbefunde, Gesamtabnahme
- Wirksame Einstellungen: Antwort auf Anfragen, Aufenthalt je Wohnung,
  Dokument und beide Abschlüsse je Vorgang
- Schritte vor dem Aufenthalt entfallen nach der Abreise; direkt bestaetigte
  Vorgaenge zeigen keine Auskunft; "Als Naechstes" ohne fremden Detailtext
- Automatische Wunschbestaetigung nur mit freigegebenen Vertragstexten
- Taeglicher Lauf bewertet auch bereits abgeschlossene Vorgaenge kaufmaennisch
- Dokumente: UMSETZUNGSERGEBNIS_P7_P9, END_TO_END_ABNAHME (T01-T25),
  KONFIGURATION_UND_WIRKSAMKEIT, GESAMTABNAHME_v0.10, STATUS; Screenshots

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 08:51:24 +01:00
LarsandClaude Opus 5.5 40d20cb7d1 Pakete 7 und 9: Auskunft und Buchungswunsch, Aufenthalt und Abschluss (Zwischenstand)
- Haltefrist 0: unverbindliche Auskunft mit signiertem Link "Buchung anfragen",
  erneute Prüfung unter Sperre, automatische oder manuelle Bestätigung, Absage
  bei vergebenem Zeitraum, Ablauf unbeantworteter Auskünfte
- Aufenthalt: Anreisedaten, Aufgaben je Wohnung, gebuchte Leistungen,
  Abweichungen und Folgeaufgaben als Aufgaben am Vorgang
- Abschluss getrennt: Aufenthalt abgeschlossen / kaufmännisch abgeschlossen,
  Nachläufer (Forderung, Auszahlung) bleiben sichtbar
- Zahlungsstatus nur aus Geld auf unserem Konto; Altbestand per Vorschau-Befehl
- Verlauf weist Testzustellungen als solche aus
- Abnahmetests T16-T25, T23 über isolierten SMTP-Empfänger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 08:29:19 +01:00
LarsandClaude Opus 5.5 3bcfc09417 Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
- 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
126 changed files with 7245 additions and 201 deletions

No files matched your search

+22 -8
View File
@@ -19,6 +19,9 @@
* Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every * Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every
* release rule is met, otherwise leaves the request untouched for manual processing and says why. * release rule is met, otherwise leaves the request untouched for manual processing and says why.
* *
* A request without a hold (pre-reservation "no") gets the information "unter Vorbehalt" instead of the offer (package 7);
* its rules are the same except the reservation.
*
* Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract * 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), * texts released by the landlord (not the sample text; skipped while mails only go to the test recipient),
* the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an * the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an
@@ -30,6 +33,7 @@ public function __construct(
private SendOffer $sendOffer, private SendOffer $sendOffer,
private CalendarClearance $clearance, private CalendarClearance $clearance,
private AvailabilityChecker $availability, private AvailabilityChecker $availability,
private SendInformation $sendInformation,
) {} ) {}
public function applies(Booking $booking): bool public function applies(Booking $booking): bool
@@ -44,11 +48,12 @@ public function blockers(Booking $booking): array
{ {
$property = $booking->property; $property = $booking->property;
$reasons = []; $reasons = [];
$information = ! $booking->process()->preReservation();
if (! $booking->process()->preReservation()) { if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) {
$reasons[] = 'Anfragen reservieren den Zeitraum nicht (Einstellung „Vorreservierung“); ohne Sperre im Kalender wird kein Angebot automatisch erteilt.'; $reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.';
} }
if ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive()) { if (! $information && ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive())) {
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).'; $reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
} }
if (blank($booking->guest?->email)) { if (blank($booking->guest?->email)) {
@@ -61,10 +66,11 @@ public function blockers(Booking $booking): array
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).'; $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. // Status, e-mail and dates are checked above; the composition adds what concerns the document.
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])]; $reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, $information ? DocumentKind::Information : DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)]; // An information reserves nothing and binds nobody: the calendar is checked again when the guest asks for the booking.
return $information ? $reasons : [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
} }
/** /**
@@ -86,7 +92,11 @@ public function handle(Booking $booking): array
} }
try { try {
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]); if (! $booking->process()->preReservation()) {
$this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]);
} else {
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
}
} catch (QuoteException|ReservationException $exception) { } catch (QuoteException|ReservationException $exception) {
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link. // A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
return [$exception->getMessage()]; return [$exception->getMessage()];
@@ -95,7 +105,11 @@ public function handle(Booking $booking): array
return []; return [];
} }
private function contractTextsReleased(): bool /**
* Whether the landlord's own contract terms, cancellation terms and bank account are in place (always true while
* mails only go to the test recipient).
*/
public function contractTextsReleased(): bool
{ {
if (! Settings::isLive()) { if (! Settings::isLive()) {
return true; return true;
+89 -17
View File
@@ -5,11 +5,14 @@
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind; use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
use App\Mail\BookingCancelled; use App\Mail\BookingCancelled;
use App\Mail\CancellationRequested; use App\Mail\CancellationRequested;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask; use App\Models\BookingTask;
use App\Process\CaseClosure;
use App\Process\CaseLog;
use App\Support\CancellationCost; use App\Support\CancellationCost;
use App\Support\Money; use App\Support\Money;
use App\Support\Settings; use App\Support\Settings;
@@ -19,44 +22,57 @@
use Throwable; use Throwable;
/** /**
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail * The one way to cancel a binding booking (package 5). Own bookings: the dates are free again; the guest and the
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for * landlord are informed by e-mail – the guest's e-mail can be switched off, e.g. when the guest cancelled by phone –, the
* the cancellation costs is created. Open cancellation requests of the guest are completed. * cancellation is recorded with who initiated it, why and who entered it, a task for the cancellation costs and – when
* the guest paid us more than the costs – a refund task are created. Open cancellation requests of the guest are done.
*
* Bookings binding on a portal (A3–A5) are cancelled where the contract was made: here the cancellation is only
* requested (task "Stornierung im Portal veranlassen bzw. prüfen", the dates stay occupied) until somebody confirms that
* it is effective on the portal ({@see confirmOnPortal()}) – nothing is released silently.
*/ */
class CancelBooking class CancelBooking
{ {
public const INITIATORS = ['guest' => 'vom Gast', 'landlord' => 'vom Vermieter', 'portal' => 'über das Portal'];
/** /**
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed) * @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
* *
* @throws ReservationException * @throws ReservationException
*/ */
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord'): bool public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord', ?string $reason = null, bool $confirmedOnPortal = false): bool
{ {
if ($booking->caseType()->isExternallyBinding() && ! $confirmedOnPortal) {
$this->requestOnPortal($booking, $by, $initiatedBy, $reason);
return true;
}
if ($notifyGuest && blank($booking->guest?->email)) { if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.'); throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
} }
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy): void { DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy, $reason): void {
$booking->lockForTransition(); $booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) { if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert'); throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
} }
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now(), 'portal_cancellation_requested_at' => null]);
app(RecordCancellation::class)->handle($booking, $initiatedBy); app(RecordCancellation::class)->handle($booking, $initiatedBy)->update(['reason' => $reason, 'recorded_by' => $by]);
if ($booking->caseType()->isExternallyBinding()) { BookingTask::query()->where('booking_id', $booking->id)
// The contract was made on the portal: the cancellation has to happen (or be checked) there as well. ->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [ ->where('status', BookingTaskStatus::Open)
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => 'Stornierung auch im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ veranlassen bzw. prüfen, ob sie dort wirksam ist.',
]);
}
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]); ->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
// The stay will not take place: its preparation is no longer needed (package 9); issues and follow-ups stay.
BookingTask::query()->where('booking_id', $booking->id)
->whereIn('kind', [BookingTaskKind::ArrivalDetails, BookingTaskKind::Service, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Storniert – entfällt.', 'completed_by' => $by, 'completed_at' => now()]);
$this->refundTask($booking);
if ($costsTask) { if ($costsTask) {
$cost = CancellationCost::calculate($booking); $cost = CancellationCost::calculate($booking);
@@ -69,10 +85,66 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
}); });
$booking->loadMissing(['guest', 'property']); $booking->loadMissing(['guest', 'property']);
// A cancellation without anything to settle is closed commercially at once; costs or a refund keep it open.
CaseClosure::refresh($booking->fresh());
return $this->notify($booking, $notifyGuest); return $this->notify($booking, $notifyGuest);
} }
/**
* A booking binding on a portal was cancelled there (the landlord saw it on the portal, or the portal reported it):
* now the case is cancelled as well. The portal informs the guest; costs are a task only when we collect the money.
*
* @throws ReservationException
*/
public function confirmOnPortal(Booking $booking, string $by, string $initiatedBy = 'portal', ?string $reason = null): bool
{
return $this->handle($booking, notifyGuest: false, costsTask: $booking->process()->payments() === Responsibility::Landlord, by: $by, initiatedBy: $initiatedBy, reason: $reason, confirmedOnPortal: true);
}
/**
* @throws ReservationException
*/
private function requestOnPortal(Booking $booking, string $by, string $initiatedBy, ?string $reason): void
{
DB::transaction(function () use ($booking, $by, $initiatedBy, $reason): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$portal = $booking->processChannel()?->name ?? 'Portal';
$booking->update(['portal_cancellation_requested_at' => now()]);
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Stornierung im Portal „'.$portal.'“ veranlassen und prüfen, ob sie dort wirksam ist. Erst dann „Stornierung bestätigen“ – bis dahin bleibt der Zeitraum belegt.',
]);
CaseLog::record($booking, 'status', 'Stornierung beim Portal '.$portal.' veranlasst ('.(self::INITIATORS[$initiatedBy] ?? $initiatedBy).') – der Vorgang bleibt gebucht, bis sie bestätigt ist', $reason, actor: $by);
});
}
/**
* When the guest paid us more than the cancellation costs, the difference is a refund to check.
*/
private function refundTask(Booking $booking): void
{
if ($booking->process()->payments() !== Responsibility::Landlord || $booking->paidToUs() <= 0) {
return;
}
$cost = CancellationCost::calculate($booking);
$fee = $cost['fee'] ?? null;
$paid = $booking->paidToUs();
if ($fee !== null && $paid <= $fee) {
return;
}
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Bezahlt: '.Money::format($paid).($fee !== null ? ' · Stornokosten laut Regel: '.Money::format($fee).' · zu erstatten: '.Money::format($paid - $fee) : ' · Stornokosten von Hand festlegen, den Rest erstatten').'. Erstattung als Zahlung „Erstattung an den Gast“ erfassen.',
]);
}
private function notify(Booking $booking, bool $notifyGuest): bool private function notify(Booking $booking, bool $notifyGuest): bool
{ {
$informed = true; $informed = true;
+480
View File
@@ -0,0 +1,480 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\QuoteLineType;
use App\Exceptions\ReservationException;
use App\Mail\BookingChanged;
use App\Mail\ChangeProposed;
use App\Models\Booking;
use App\Models\BookingChange;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Pricing\PortalPrice;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Changes a booking after it became binding (package 5, UMSETZUNGSPLAN §4.6): dates, length of stay, number of guests,
* services and price. Before anything changes the consequences are put together – calendar and portals, price and its
* origin, payment plan, refund or additional payment, confirmation – and the person confirms them.
*
* Two ways, kept strictly apart:
* - **agreed**: the change was already agreed with the guest (phone, e-mail, in person, on the portal); it takes effect
* at once and the case keeps who asked, why, from when and on which basis. An updated confirmation only informs the
* guest – it is not taken as the guest's consent.
* - **proposed**: the guest still has to agree; nothing changes until the guest accepts through the signed link.
*
* Own bookings get their price recalculated (kept adjustments, or an agreed price); bookings binding on a portal take the
* portal's new total; internal cases (A6) keep their agreed rent and recalculate services and tourist tax.
*/
class ChangeBooking
{
public const REQUESTED_BY = ['guest', 'landlord', 'portal'];
public function __construct(
private PriceCalculator $calculator,
private PrivateStayPrice $privateStay,
private AvailabilityChecker $availability,
private PortalPrice $portalPrice,
private RecordPayment $payments,
) {}
/**
* The consequences of a change, without changing anything.
*
* @param array{arrival?: ?string, departure?: ?string, guests?: ?int, extras?: ?array<int, int>, portal_total?: ?int, agreed_total?: ?int, agreed_total_label?: ?string, rent?: ?int, tourist_tax_persons?: ?int} $changes
* @return array{errors: list<string>, before: array<string, mixed>, after: array<string, mixed>, summary: list<string>, calendar: list<string>, portals: list<string>, price: array{before: ?int, after: ?int, difference: ?int, source: string}, payment: list<string>, refund: int, confirmation: bool}
*/
public function preview(Booking $booking, array $changes): array
{
$booking->loadMissing(['property', 'payments', 'guest']);
$errors = [];
$before = self::snapshot($booking);
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
$guests = array_key_exists('guests', $changes) && filled($changes['guests']) ? (int) $changes['guests'] : $booking->guests;
$extras = array_key_exists('extras', $changes) && is_array($changes['extras']) ? array_filter(array_map('intval', $changes['extras'])) : (array) ($booking->extras ?? []);
if ($departure->lessThanOrEqualTo($arrival)) {
$errors[] = 'Die Abreise muss nach der Anreise liegen.';
} elseif (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
$errors[] = 'Der neue Zeitraum ist nicht frei.';
}
if ($guests !== null && $guests > $booking->property->max_guests) {
$errors[] = 'Höchstens '.$booking->property->max_guests.' Personen.';
}
[$quote, $source, $priceError] = $departure->greaterThan($arrival) ? $this->price($booking, $changes, $arrival, $departure, $guests, $extras) : [null, '–', null];
if ($priceError !== null) {
$errors[] = $priceError;
}
$paid = $booking->paidAmount();
$total = $quote !== null ? $quote['total'] : $booking->total;
$depositPaid = $booking->deposit !== null && $paid >= $booking->deposit && $paid > 0;
$deposit = $quote === null ? $booking->deposit : ($depositPaid ? $booking->deposit : ($quote['deposit'] ?? $booking->deposit));
$after = [
'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString(), 'guests' => $guests, 'extras' => $extras,
'quote' => $quote['quote'] ?? $booking->quote, 'total' => $total, 'deposit' => $deposit,
'balance_due_on' => $quote['balance_due_on'] ?? $booking->balance_due_on?->toDateString(),
'rent' => $changes['rent'] ?? null, 'tourist_tax_persons' => array_key_exists('tourist_tax_persons', $changes) ? $changes['tourist_tax_persons'] : $booking->tourist_tax_persons,
];
[$calendar, $portals] = $this->calendarConsequences($booking, $arrival, $departure);
$difference = $total !== null && $booking->total !== null ? $total - $booking->total : null;
$refund = $total !== null ? max(0, $paid - $total) : 0;
$payment = array_values(array_filter([
$booking->wantsPaymentTasks() || ($total !== null && $total > 0 && $booking->process()->payments()->value === 'landlord' && ! $booking->isInternal()) ? 'Bezahlt bisher: '.Money::format($paid).' · danach offen: '.Money::format(max(0, (int) $total - $paid)) : null,
$refund > 0 ? 'Der Gast hat mehr bezahlt als der neue Preis: '.Money::format($refund).' zu erstatten (Aufgabe wird angelegt).' : null,
$depositPaid ? 'Die Anzahlung ist bezahlt und bleibt unverändert.' : null,
$after['balance_due_on'] !== ($booking->balance_due_on?->toDateString()) && $after['balance_due_on'] !== null && ! $booking->isInternal() ? 'Restzahlung neu fällig am '.CarbonImmutable::parse($after['balance_due_on'])->format('d.m.Y').'.' : null,
$booking->process()->payments()->value === 'portal' ? 'Die Zahlung läuft weiter über das Portal.' : null,
]));
return [
'errors' => $errors,
'before' => $before,
'after' => $after,
'summary' => self::summary($before, $after),
'calendar' => $calendar,
'portals' => $portals,
'price' => ['before' => $booking->total, 'after' => $total, 'difference' => $difference, 'source' => $source],
'payment' => $payment,
'refund' => $refund,
'confirmation' => ! $booking->isInternal() && filled($booking->guest?->email),
];
}
/**
* An agreed change (or a change of an internal case): takes effect at once.
*
* @param array<string, mixed> $changes
* @param array{requested_by: string, reason: string, basis: ChangeBasis, agreed_at?: ?string, effective_on?: ?string, send_confirmation?: bool} $meta
*
* @throws ReservationException
*/
public function apply(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
{
$this->guard($booking);
if ($meta['basis'] === ChangeBasis::GuestLink) {
throw new ReservationException('Eine Zustimmung über den Link entsteht nur, wenn der Gast selbst annimmt.');
}
$change = DB::transaction(function () use ($booking, $changes, $meta, $by): BookingChange {
$booking->lockForTransition();
$preview = $this->preview($booking, $changes);
if ($preview['errors'] !== []) {
throw new ReservationException(implode(' ', $preview['errors']));
}
$change = $booking->changes()->create([
'status' => ChangeStatus::Applied, 'requested_by' => $meta['requested_by'], 'basis' => $meta['basis'],
'reason' => trim((string) $meta['reason']), 'effective_on' => $meta['effective_on'] ?? today()->toDateString(),
'agreed_at' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($meta['agreed_at'] ?? now()),
'agreed_by' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($booking->guest?->full_name ?? 'Gast'),
'before' => $preview['before'], 'after' => $preview['after'], 'consequences' => self::consequences($preview),
'applied_at' => now(), 'recorded_by' => $by,
]);
$change->tenant_id = $booking->tenant_id;
$change->save();
$this->write($booking, $preview, $meta['reason'], $by, $change);
return $change;
});
if ($meta['send_confirmation'] ?? false) {
$this->confirm($booking->fresh(), $change);
}
return $change->fresh();
}
/**
* A change the guest still has to agree to: nothing changes; the guest gets a link to accept or decline.
*
* @param array<string, mixed> $changes
* @param array{requested_by: string, reason: string, effective_on?: ?string, valid_days?: int} $meta
*
* @throws ReservationException
*/
public function propose(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
{
$this->guard($booking);
if ($booking->isInternal() || $booking->caseType()->isExternallyBinding()) {
throw new ReservationException('Ein Vorschlag mit Zustimmungslink ist nur für eigene Buchungen möglich – Portalbuchungen werden im Portal geändert.');
}
if (blank($booking->guest?->email)) {
throw new ReservationException('Für einen Vorschlag wird die E-Mail-Adresse des Gastes benötigt.');
}
if ($booking->changes()->where('status', ChangeStatus::Proposed)->exists()) {
throw new ReservationException('Es liegt schon ein Änderungsvorschlag beim Gast. Bitte zuerst zurückziehen.');
}
$preview = $this->preview($booking, $changes);
if ($preview['errors'] !== []) {
throw new ReservationException(implode(' ', $preview['errors']));
}
$change = $booking->changes()->create([
'status' => ChangeStatus::Proposed, 'requested_by' => $meta['requested_by'], 'reason' => trim((string) $meta['reason']),
'effective_on' => $meta['effective_on'] ?? null, 'before' => $preview['before'], 'after' => $preview['after'],
'consequences' => self::consequences($preview), 'expires_at' => now()->addDays((int) ($meta['valid_days'] ?? 7)), 'recorded_by' => $by,
]);
$change->tenant_id = $booking->tenant_id;
$change->save();
CaseLog::record($booking, 'change', 'Änderung dem Gast vorgeschlagen: '.implode(' · ', $preview['summary']), $meta['reason'], data: ['booking_change_id' => $change->id]);
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ChangeProposed($booking, $change, $this->link($change)));
} catch (Throwable $exception) {
Log::warning('Änderungsvorschlag nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
throw new ReservationException('Der Vorschlag ist gespeichert, aber die E-Mail konnte nicht versendet werden.');
}
return $change;
}
/**
* The guest accepts a proposed change through the signed link: the dates are checked again, then it takes effect.
*
* @throws ReservationException
*/
public function accept(BookingChange $change, ?string $ip = null): BookingChange
{
return DB::transaction(function () use ($change, $ip): BookingChange {
$booking = $change->booking;
$booking->lockForTransition();
$change = BookingChange::query()->whereKey($change->id)->lockForUpdate()->firstOrFail();
if ($change->status !== ChangeStatus::Proposed) {
throw new ReservationException('Dieser Vorschlag ist nicht mehr offen.');
}
if ($change->expires_at !== null && $change->expires_at->isPast()) {
$change->update(['status' => ChangeStatus::Expired]);
throw new ReservationException('Dieser Vorschlag ist abgelaufen. Bitte melden Sie sich bei uns.');
}
$after = (array) $change->after;
$preview = $this->preview($booking, [...$after, 'agreed_total' => $after['total'] ?? null, 'portal_total' => null]);
if ($preview['errors'] !== []) {
throw new ReservationException('Die Änderung ist leider nicht mehr möglich: '.implode(' ', $preview['errors']));
}
$change->update(['status' => ChangeStatus::Applied, 'basis' => ChangeBasis::GuestLink, 'agreed_at' => now(), 'agreed_by' => $booking->guest?->full_name,
'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null, 'applied_at' => now()]);
CaseLog::context(fn () => $this->write($booking, $preview, (string) $change->reason, CaseLog::GUEST, $change), actor: CaseLog::GUEST);
return $change->fresh();
});
}
public function decline(BookingChange $change, ?string $ip = null): void
{
if ($change->status !== ChangeStatus::Proposed) {
return;
}
$change->update(['status' => ChangeStatus::Declined, 'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null]);
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag vom Gast abgelehnt', actor: CaseLog::GUEST, data: ['booking_change_id' => $change->id]);
}
public function withdraw(BookingChange $change, ?string $by = null): void
{
if ($change->status === ChangeStatus::Proposed) {
$change->update(['status' => ChangeStatus::Withdrawn, 'decided_at' => now()]);
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag zurückgezogen', actor: $by);
}
}
/**
* The guest's signed link to a proposed change (valid while the proposal is).
*/
public function link(BookingChange $change): string
{
$until = $change->expires_at ?? now()->addDays(7);
return $change->booking->website()?->temporarySignedRoute('changes.show', $until, ['change' => $change])
?? URL::temporarySignedRoute('changes.show', $until, ['change' => $change]);
}
/**
* Sends the updated confirmation of an agreed change (information, not consent).
*/
public function confirm(Booking $booking, BookingChange $change): bool
{
if ($booking->isInternal() || blank($booking->guest?->email)) {
return false;
}
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingChanged($booking, $change));
$change->update(['confirmation_sent_at' => now()]);
return true;
} catch (Throwable $exception) {
Log::warning('Änderungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
return false;
}
}
/**
* @throws ReservationException
*/
private function guard(Booking $booking): void
{
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw new ReservationException('Ändern lässt sich nur eine bestehende Buchung oder Belegung. Ein Angebot wird über „Angebot ändern & neu senden“ geändert.');
}
}
/**
* Writes the new state on the case (inside the transaction of the caller).
*
* @param array<string, mixed> $preview
*/
private function write(Booking $booking, array $preview, string $reason, ?string $by, BookingChange $change): void
{
$after = $preview['after'];
$booking->update([
'arrival' => $after['arrival'], 'departure' => $after['departure'], 'guests' => $after['guests'], 'extras' => $after['extras'],
'quote' => $after['quote'], 'total' => $after['total'], 'deposit' => $after['deposit'], 'balance_due_on' => $after['balance_due_on'],
'tourist_tax_persons' => $after['tourist_tax_persons'],
]);
CaseLog::record($booking, 'change', 'Geändert: '.implode(' · ', $preview['summary']), $reason, data: ['booking_change_id' => $change->id], actor: $by);
$this->payments->updateStatus($booking->fresh());
if ($preview['refund'] > 0) {
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(),
'note' => 'Nach der Änderung zu viel bezahlt: '.Money::format($preview['refund']).' an den Gast erstatten (als „Erstattung“ erfassen).',
'completed_by' => null, 'completed_at' => null,
]);
}
}
/**
* The new price and where it comes from.
*
* @param array<string, mixed> $changes
* @param array<int, int> $extras
* @return array{0: ?array{quote: array<string, mixed>, total: int, deposit: ?int, balance_due_on: ?string}, 1: string, 2: ?string}
*/
private function price(Booking $booking, array $changes, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras): array
{
if ($booking->isInternal()) {
try {
$rent = array_key_exists('rent', $changes) && $changes['rent'] !== null ? (int) $changes['rent'] : PrivateStayPrice::rentOf($booking->quote);
$taxPersons = array_key_exists('tourist_tax_persons', $changes) ? ($changes['tourist_tax_persons'] === null ? null : (int) $changes['tourist_tax_persons']) : $booking->tourist_tax_persons;
$quote = $this->privateStay->quote($booking->property, $arrival, $departure, $guests, $extras, $rent, $taxPersons);
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => null, 'balance_due_on' => null], 'vereinbart (Miete, Leistungen, Kurabgabe)', null];
} catch (QuoteException $exception) {
return [null, '–', $exception->getMessage()];
}
}
if ($booking->caseType()->isExternallyBinding() || ($booking->quote['source'] ?? null) === 'portal') {
$total = filled($changes['portal_total'] ?? null) ? (int) $changes['portal_total'] : $booking->total;
if ($total === null) {
return [null, 'laut Portal – noch nicht bekannt', null];
}
$columns = $this->portalPrice->columns($booking->property, $arrival, $departure, $guests, $total, $booking->processChannel()?->name);
return [['quote' => $columns['quote'], 'total' => (int) $columns['total'], 'deposit' => $columns['deposit'], 'balance_due_on' => $columns['balance_due_on']],
filled($changes['portal_total'] ?? null) ? 'neuer Gesamtpreis laut Portal' : 'Gesamtpreis laut Portal unverändert – bitte neuen Betrag eintragen, falls das Portal ihn geändert hat', null];
}
$agreed = filled($changes['agreed_total'] ?? null) ? (int) $changes['agreed_total'] : null;
try {
$quote = $this->calculator->calculate($booking->property, new StayRequest($arrival, $departure, max(1, (int) $guests), $extras, $booking->promo_code));
foreach ((array) ($booking->quote['lines'] ?? []) as $line) {
if (($line['type'] ?? null) === QuoteLineType::Adjustment->value) {
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, (string) $line['label'], 1, (int) $line['amount'], (int) $line['amount']));
}
}
$source = 'aus Ihren Preisen neu berechnet';
} catch (QuoteException $exception) {
if ($agreed === null) {
return [null, '–', 'Preis: '.$exception->getMessage().' Bitte einen vereinbarten Preis eintragen.'];
}
$quote = new PriceQuote($arrival, $departure, (int) $guests, [new QuoteLine(QuoteLineType::Accommodation, 'Vereinbarter Preis', 1, $agreed, $agreed)], $booking->property->deposit_percent, $arrival->subDays($booking->property->balance_due_days_before_arrival));
$source = 'vereinbarter Preis';
}
if ($agreed !== null && $agreed !== $quote->total()) {
$label = trim((string) ($changes['agreed_total_label'] ?? '')) ?: 'Vereinbarte Preisanpassung';
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $agreed - $quote->total(), $agreed - $quote->total()));
$source = 'vereinbarter Preis';
}
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()], $source, null];
}
/**
* What happens in the calendar and on the portals that are blocked by hand.
*
* @return array{0: list<string>, 1: list<string>}
*/
private function calendarConsequences(Booking $booking, CarbonImmutable $arrival, CarbonImmutable $departure): array
{
$oldStart = $booking->arrival;
$oldEnd = $booking->departure;
if ($arrival->equalTo($oldStart) && $departure->equalTo($oldEnd)) {
return [['Kalender unverändert.'], []];
}
$added = array_values(array_filter([
$arrival->lessThan($oldStart) ? [$arrival, $oldStart->min($departure)] : null,
$departure->greaterThan($oldEnd) ? [$oldEnd->max($arrival), $departure] : null,
]));
$freed = array_values(array_filter([
$oldStart->lessThan($arrival) ? [$oldStart, $arrival->min($oldEnd)] : null,
$oldEnd->greaterThan($departure) ? [$departure->max($oldStart), $oldEnd] : null,
]));
$range = fn (array $pair): string => $pair[0]->format('d.m.').'–'.$pair[1]->format('d.m.Y');
$calendar = [
...array_map(fn (array $pair): string => 'Neu belegt: '.$range($pair), $added),
...array_map(fn (array $pair): string => 'Wieder frei: '.$range($pair), $freed),
'Die Kalender für die Portale zeigen den neuen Zeitraum beim nächsten Abruf.',
];
$origin = $booking->origin_channel_id ?? $booking->import_channel_id;
$portals = $booking->property->channels()->active()->where('requires_manual_blocking', true)->get()
->filter(fn (Channel $channel): bool => $channel->exportsOccupations() && $channel->id !== $origin)
->map(fn (Channel $channel): string => 'Aufgabe für '.$channel->name.': '.implode(', ', [...array_map(fn (array $pair): string => 'sperren '.$range($pair), $added), ...array_map(fn (array $pair): string => 'freigeben '.$range($pair), $freed)]))
->values()->all();
if ($booking->caseType()->isExternallyBinding()) {
$portals[] = 'Die Änderung selbst muss im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ vorliegen – hier wird sie nur nachgetragen.';
}
return [$calendar, $portals];
}
/**
* @return array<string, mixed>
*/
private static function snapshot(Booking $booking): array
{
return [
'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(), 'guests' => $booking->guests,
'extras' => (array) ($booking->extras ?? []), 'quote' => $booking->quote, 'total' => $booking->total, 'deposit' => $booking->deposit,
'balance_due_on' => $booking->balance_due_on?->toDateString(), 'tourist_tax_persons' => $booking->tourist_tax_persons,
];
}
/**
* @param array<string, mixed> $before
* @param array<string, mixed> $after
* @return list<string>
*/
private static function summary(array $before, array $after): array
{
$date = fn (?string $value): string => $value ? CarbonImmutable::parse($value)->format('d.m.Y') : '–';
$lines = [];
if ($before['arrival'] !== $after['arrival'] || $before['departure'] !== $after['departure']) {
$lines[] = 'Zeitraum '.$date($before['arrival']).'–'.$date($before['departure']).' → '.$date($after['arrival']).'–'.$date($after['departure']);
}
if ($before['guests'] !== $after['guests']) {
$lines[] = 'Personen '.($before['guests'] ?? '?').' → '.($after['guests'] ?? '?');
}
if ((array) $before['extras'] != (array) $after['extras']) {
$lines[] = 'Zusatzleistungen geändert';
}
if ($before['total'] !== $after['total']) {
$lines[] = 'Preis '.($before['total'] === null ? '–' : Money::format($before['total'])).' → '.($after['total'] === null ? '–' : Money::format($after['total']));
}
return $lines === [] ? ['keine inhaltliche Änderung'] : $lines;
}
/**
* @param array<string, mixed> $preview
* @return array<string, mixed>
*/
private static function consequences(array $preview): array
{
return ['summary' => $preview['summary'], 'calendar' => $preview['calendar'], 'portals' => $preview['portals'], 'price' => $preview['price'], 'payment' => $preview['payment'], 'refund' => $preview['refund']];
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\CaseMoney;
use App\Process\CaseClosure;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* Package 9, P05 (gate B4 as decided by the operator): closes the stay after the departure – automatically once no task
* of the stay is open any more, or by the landlord, who marks the remaining stay tasks as done or handed over. Open
* money does not hold the stay up: it becomes a follow-up on the same case (claim against the guest, payout of the
* portal) and keeps the commercial closing open until it is clear.
*/
class CloseStay
{
/**
* Daily: closes every stay whose departure has passed and nothing of the stay is open any more.
*
* @return int the number of stays closed now
*/
public function due(): int
{
$closed = 0;
$stays = Booking::query()
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])
->whereDate('departure', '<', CarbonImmutable::today())
->with(['guest', 'property', 'payments', 'importChannel', 'originChannel'])
->get();
foreach ($stays as $booking) {
// After the departure the arrival details are of no use any more.
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->get() as $task) {
$task->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Nach der Abreise nicht mehr nötig.', 'completed_by' => CaseLog::SYSTEM, 'completed_at' => now()]);
}
if (CaseClosure::stayBlockers($booking)->isNotEmpty()) {
continue;
}
CaseLog::context(fn () => $this->close($booking), actor: CaseLog::SYSTEM.' (automatisch)');
$closed++;
}
// Cases closed before package 9 (or whose money became clear without a payment) get their commercial closing too.
$unsettled = Booking::query()->whereIn('status', [BookingStatus::Completed, BookingStatus::Cancelled])->whereNull('settled_at')
->whereDate('departure', '>', CarbonImmutable::today()->subYear())->with(['payments', 'importChannel', 'originChannel'])->get();
foreach ($unsettled as $booking) {
CaseLog::context(fn () => CaseClosure::refresh($booking), actor: CaseLog::SYSTEM.' (automatisch)');
}
return $closed;
}
/**
* The landlord closes the stay; open tasks of the stay are marked as done or handed over with the note.
*
* @throws ReservationException
*/
public function byHand(Booking $booking, string $by, ?string $note = null): void
{
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgeschlossen');
}
if ($booking->departure->isAfter(CarbonImmutable::today())) {
throw new ReservationException('Der Aufenthalt endet erst am '.$booking->departure->format('d.m.Y').'.');
}
CaseLog::context(function () use ($booking, $by, $note): void {
foreach (CaseClosure::stayBlockers($booking) as $task) {
$task->complete($by, filled($note) ? $note : 'Mit dem Abschluss des Aufenthalts erledigt bzw. übergeben.');
}
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Dismissed, 'completed_by' => $by, 'completed_at' => now()]);
$this->close($booking);
}, actor: $by, reason: $note);
}
private function close(Booking $booking): void
{
DB::transaction(function () use ($booking): void {
$booking->lockForTransition();
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
return;
}
$booking->update(['status' => BookingStatus::Completed, 'completed_at' => now()]);
$this->followUps($booking);
});
CaseClosure::refresh($booking->fresh());
}
/**
* Open money becomes a follow-up of the closed stay, so it stays visible and assigned.
*/
private function followUps(Booking $booking): void
{
$booking->unsetRelation('payments');
$money = CaseMoney::of($booking);
if ($money->collector() === Responsibility::Landlord && $money->openForUs() > 0) {
$chasing = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()->contains(fn (BookingTask $task): bool => $task->kind->isPayment());
if (! $chasing) {
BookingTask::openOnce($booking, BookingTaskKind::OpenClaim, '', ['due_on' => today(), 'note' => 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.']);
}
}
if ($money->collector() === Responsibility::Portal) {
$payout = $money->payout();
if ($payout['received'] === 0 || ($payout['outstanding'] ?? 0) > 0) {
$portal = $booking->processChannel()?->name ?? 'des Portals';
BookingTask::openOnce($booking, BookingTaskKind::PayoutCheck, '', [
'due_on' => $booking->departure->addDays(14),
'responsible' => $booking->processChannel()?->name,
'note' => match (true) {
$payout['values'] !== [] => 'Angekündigt: '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).'; erhalten: '.Money::format($payout['received']).'.',
default => 'Auszahlung von '.$portal.' noch nicht erfasst.',
},
]);
}
}
}
}
+6 -1
View File
@@ -12,6 +12,7 @@
use App\Filament\Resources\Bookings\BookingResource; use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\BookingConfirmed; use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation; use App\Mail\BookingDocumentation;
use App\Mail\StayConfirmed;
use App\Models\Booking; use App\Models\Booking;
use App\Process\CaseLog; use App\Process\CaseLog;
use App\Support\Inbox; use App\Support\Inbox;
@@ -108,7 +109,11 @@ public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKin
return true; return true;
} }
Mail::to($booking->guest->email, $booking->guest->full_name)->send($kind === DocumentKind::ExternalRecord ? new BookingDocumentation($booking) : new BookingConfirmed($booking)); Mail::to($booking->guest->email, $booking->guest->full_name)->send(match ($kind) {
DocumentKind::ExternalRecord => new BookingDocumentation($booking),
DocumentKind::StayConfirmation => new StayConfirmed($booking),
default => new BookingConfirmed($booking),
});
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save(); $booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save();
return true; return true;
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Process\CaseLog;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Own use, a private stay or a block as a case (A6, package 6): the dates are occupied at once and the portals are
* blocked like for any booking. A block has nothing but dates and an occasion; own use and private stays may have
* guests, services, an agreed rent (0 by default), the tourist tax and payments – but never a rental contract, payment
* reminders, reviews or marketing (the A6 profile switches them off).
*/
class CreateInternalCase
{
public function __construct(private AvailabilityChecker $availability, private PrivateStayPrice $price) {}
/**
* @param array{occasion?: ?string, guest?: ?array<string, ?string>, guests?: ?int, extras?: ?array<int, int>, rent?: ?int, tourist_tax_persons?: ?int, tourist_tax_note?: ?string, notes?: ?string} $data
*
* @throws ReservationException
* @throws QuoteException
*/
public function handle(Property $property, InternalKind $kind, CarbonImmutable $arrival, CarbonImmutable $departure, array $data = []): Booking
{
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Das Ende muss nach dem Beginn liegen.');
}
return DB::transaction(function () use ($property, $kind, $arrival, $departure, $data): Booking {
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if (! $this->availability->isAvailable($property, $arrival, $departure)) {
throw ReservationException::notAvailable();
}
$guests = $kind === InternalKind::Block ? null : (filled($data['guests'] ?? null) ? (int) $data['guests'] : null);
$extras = $kind === InternalKind::Block ? [] : array_filter(array_map('intval', (array) ($data['extras'] ?? [])));
$taxPersons = $kind === InternalKind::Block ? null : (filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null);
$quote = $kind === InternalKind::Block ? null : $this->price->quote($property, $arrival, $departure, $guests, $extras, (int) ($data['rent'] ?? 0), $taxPersons);
$guest = $kind->hasGuests() ? $this->guest((array) ($data['guest'] ?? [])) : null;
$booking = $property->bookings()->create([
'guest_id' => $guest?->id,
'status' => BookingStatus::Confirmed,
'source' => 'internal',
'intake' => IntakeKind::Internal,
'internal_kind' => $kind,
'occasion' => filled($data['occasion'] ?? null) ? trim((string) $data['occasion']) : null,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $guests,
'extras' => $extras,
'quote' => $quote?->toArray(),
'total' => $quote?->total(),
'tourist_tax_persons' => $taxPersons,
'tourist_tax_note' => filled($data['tourist_tax_note'] ?? null) ? trim((string) $data['tourist_tax_note']) : null,
'confirmed_at' => now(),
'internal_notes' => filled($data['notes'] ?? null) ? trim((string) $data['notes']) : null,
]);
CaseLog::record($booking, 'intake', $kind->getLabel().' eingetragen'.($booking->occasion ? ': '.$booking->occasion : ''));
return $booking;
});
}
/**
* The guest of a private stay – only with a real name; a known e-mail address finds the existing guest.
*
* @param array<string, ?string> $data
*/
private function guest(array $data): ?Guest
{
$data = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']));
if (blank($data['first_name'] ?? null) || blank($data['last_name'] ?? null)) {
return null;
}
$email = filled($data['email'] ?? null) ? mb_strtolower($data['email']) : null;
if ($email !== null && ($known = Guest::query()->where('email', $email)->whereNull('anonymized_at')->first()) !== null) {
return $known;
}
return Guest::query()->create([...array_filter($data, fn ($value) => $value !== null), 'email' => $email ?? '']);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingWishAnswered;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The landlord decides on a booking wish (package 7, "Buchungswunsch bestätigen?"): confirm it – availability is checked
* once more under the lock, so two wishes for the same dates can never both become bookings – or decline it with a
* friendly answer. The price is the one the guest was told; a lower price of today may be granted, a higher one needs a
* new information the guest asks for again.
*/
class DecideBookingWish
{
public function __construct(private ConfirmBooking $confirm, private SendOffer $offer) {}
/**
* @return bool whether the guest has the confirmation
*
* @throws ReservationException
*/
public function confirm(Booking $booking, bool $useTodaysPrice = false, bool $notifyGuest = true): bool
{
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
DB::transaction(function () use ($booking, $useTodaysPrice): void {
$booking->lockForTransition();
if ($booking->status !== BookingStatus::Reserved || $booking->wish_at === null) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Buchungswunsch bestätigt');
}
if ($useTodaysPrice) {
$quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, (string) ($booking->price_adjustment_label ?: 'Zuschlag'));
if ($quote->total() > (int) $booking->total) {
throw new ReservationException('Der heutige Preis ist höher als der Preis der Auskunft. Ohne Zustimmung des Gastes geht das nicht – bitte eine neue Auskunft senden.');
}
$booking->update(['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()]);
}
$this->confirm->bind($booking);
$booking->update([
'accepted_at' => $booking->wish_at,
'acceptance' => [
'via' => 'booking_wish',
'information_version' => $booking->wish['information_version'] ?? $booking->information_version,
'wish_at' => $booking->wish_at?->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => SendInformation::quoteHash($booking),
'terms_sha256' => $booking->wish['terms_sha256'] ?? null,
'confirmed_by' => CaseLog::actor(),
'confirmed_at' => now()->toIso8601String(),
],
]);
$this->closeTasks($booking, 'Bestätigt.');
});
$booking->refresh();
CaseLog::record($booking, 'wish', 'Buchungswunsch bestätigt – Buchung verbindlich');
return $this->confirm->deliver($booking, $notifyGuest);
}
/**
* @throws ReservationException
*/
public function decline(Booking $booking, ?string $reason = null, bool $notifyGuest = true): void
{
DB::transaction(function () use ($booking): void {
$booking->lockForTransition();
if ($booking->status !== BookingStatus::Reserved) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgesagt');
}
$booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'us', 'hold_expires_at' => null]);
$this->closeTasks($booking, 'Abgesagt.');
});
CaseLog::record($booking, 'wish', 'Buchungswunsch abgesagt', reason: $reason);
if ($notifyGuest && filled($booking->guest?->email)) {
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking->fresh(), 'declined'));
} catch (Throwable $exception) {
Log::warning('Absage zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
}
private function closeTasks(Booking $booking, string $note): void
{
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)->get() as $task) {
$task->complete(CaseLog::actor(), $note);
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use Illuminate\Support\Facades\DB;
/**
* Lifts a block or calls off an own use / private stay (A6). It is no cancellation: no costs, no refund rule, no mails –
* the dates are free again and the portals are released like for any booking that ends.
*/
class EndInternalCase
{
/**
* @throws ReservationException
*/
public function handle(Booking $booking, string $reason, ?string $by = null): void
{
if (! $booking->isInternal()) {
throw new ReservationException('Nur eigene Nutzung, private Aufenthalte und Sperren werden so beendet.');
}
DB::transaction(function () use ($booking, $reason, $by): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'aufgehoben');
}
CaseLog::context(fn () => $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]), actor: $by, reason: $reason);
CaseLog::record($booking, 'status', self::label($booking), $reason, actor: $by);
});
}
public static function label(Booking $booking): string
{
return $booking->internal_kind === InternalKind::Block ? 'Sperre aufgehoben' : 'Aufenthalt abgesagt';
}
}
+7 -2
View File
@@ -9,7 +9,8 @@
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
/** /**
* Marks reservations whose hold time is over as expired and tells the landlord. * Marks reservations whose hold time is over – and information without a hold whose link expired unanswered – as
* expired and tells the landlord.
* The calendar already treats them as free once the hold time is over; this only updates the status. * The calendar already treats them as free once the hold time is over; this only updates the status.
*/ */
class ExpireReservations class ExpireReservations
@@ -18,7 +19,11 @@ public function handle(): int
{ {
$expired = Booking::query() $expired = Booking::query()
->whereIn('status', BookingStatus::holding()) ->whereIn('status', BookingStatus::holding())
->where('hold_expires_at', '<=', now()) ->where(fn ($query) => $query
->where('hold_expires_at', '<=', now())
// An information without a hold (package 7) ends when its link expires and the guest did not ask for the booking.
->orWhere(fn ($information) => $information->where('status', BookingStatus::Reserved)->whereNull('hold_expires_at')
->where('information_valid_until', '<=', now())->whereNull('wish_at')))
->with(['guest', 'property']) ->with(['guest', 'property'])
->get(); ->get();
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\InternalKind;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Extra;
use App\Process\CaseLog;
use Carbon\CarbonImmutable;
/**
* Package 9, P04: prepares the stays of the coming two weeks – once per case and task, however often it runs.
*
* - **Arrival details:** a few days before the arrival information is due, a task asks for what is missing (a way to
* reach the guest; the arrival time where the property asks for it). It closes itself once the data is there. For a
* portal booking the contact may have to be fetched from the portal.
* - **Stay tasks of the property:** cleaning, linen, key handover … as configured on the property, with their due date.
* - **Booked services:** every extra of our own price (or of a private stay) becomes a task to provide it.
*
* Nothing is sent to guests here; the arrival information keeps going out by itself where we are responsible.
*/
class PrepareStays
{
/** How far ahead stays are prepared. */
public const LEAD_DAYS = 14;
/** Days before the arrival information that the arrival details are checked. */
private const DETAILS_BEFORE_INFO = 2;
/**
* @return array{arrival_details: int, stay_tasks: int}
*/
public function handle(): array
{
$today = CarbonImmutable::today();
$created = ['arrival_details' => 0, 'stay_tasks' => 0];
$stays = Booking::query()
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])
->whereDate('arrival', '<=', $today->addDays(self::LEAD_DAYS))
->whereDate('departure', '>=', $today)
->with(['guest', 'property', 'importChannel', 'originChannel'])
->get();
foreach ($stays as $booking) {
$created['arrival_details'] += $this->arrivalDetails($booking, $today) ? 1 : 0;
$created['stay_tasks'] += $this->stayTasks($booking);
}
return $created;
}
/**
* What is still missing for the arrival, in plain words (empty: nothing).
*
* @return list<string>
*/
public static function missingArrivalDetails(Booking $booking): array
{
if ($booking->isInternal()) {
return [];
}
return array_values(array_filter([
$booking->guest === null ? 'Name und Kontakt des Gastes' : null,
$booking->guest !== null && blank($booking->guest->email) && blank($booking->guest->phone) ? 'eine E-Mail-Adresse oder Telefonnummer des Gastes' : null,
$booking->property?->asks_arrival_time && blank($booking->arrival_time) ? 'die Anreisezeit' : null,
]));
}
/**
* Opens (or closes) the task for missing arrival details.
*/
private function arrivalDetails(Booking $booking, CarbonImmutable $today): bool
{
$missing = self::missingArrivalDetails($booking);
$open = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->first();
if ($missing === []) {
$open?->complete(CaseLog::SYSTEM, 'Die Angaben liegen jetzt vor.');
return false;
}
$checkFrom = $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore() + self::DETAILS_BEFORE_INFO);
if ($today->lessThan($checkFrom)) {
return false;
}
$portal = $booking->caseType()->isExternallyBinding() ? ' (ggf. im Portal '.($booking->processChannel()?->name ?? '').' nachsehen)' : '';
$task = BookingTask::openOnce($booking, BookingTaskKind::ArrivalDetails, '', [
'due_on' => $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore()),
'note' => 'Es fehlt: '.implode(', ', $missing).$portal.'.',
]);
return $task->wasRecentlyCreated;
}
/**
* Opens the configured stay tasks and the tasks for booked services; returns how many were opened now.
*/
private function stayTasks(Booking $booking): int
{
$kind = match (true) {
! $booking->isInternal() => 'rental',
$booking->internal_kind === InternalKind::PrivateStay => 'private',
$booking->internal_kind === InternalKind::OwnUse => 'own',
default => 'block',
};
$opened = 0;
foreach ($booking->property?->stayTaskDefinitions() ?? [] as $definition) {
if (! in_array($kind, $definition['applies_to'], true)) {
continue;
}
$due = match ($definition['when']) {
'after_departure' => $booking->departure,
'on_arrival' => $booking->arrival,
default => $booking->arrival->subDays($definition['days']),
};
$task = BookingTask::openOnce($booking, BookingTaskKind::Service, $definition['key'], [
'title' => $definition['title'],
'responsible' => $definition['responsible'],
'due_on' => $due,
]);
// Dates of the stay may have changed since the task was opened.
if (! $task->wasRecentlyCreated && $task->status === BookingTaskStatus::Open && ! $task->due_on?->equalTo($due)) {
$task->update(['due_on' => $due]);
}
$opened += $task->wasRecentlyCreated ? 1 : 0;
}
// Booked services of our own price (a portal's extras are not known item by item).
if (($booking->quote['source'] ?? null) !== 'portal') {
$extras = array_filter((array) ($booking->extras ?? []), fn ($quantity): bool => (int) $quantity > 0);
foreach (Extra::query()->whereIn('id', array_keys($extras))->get() as $extra) {
$task = BookingTask::openOnce($booking, BookingTaskKind::Service, 'extra:'.$extra->id, [
'title' => 'Bereitstellen: '.((int) $extras[$extra->id] > 1 ? $extras[$extra->id].' × ' : '').$extra->name,
'due_on' => $booking->arrival->subDay(),
]);
$opened += $task->wasRecentlyCreated ? 1 : 0;
}
}
return $opened;
}
}
+90 -17
View File
@@ -3,52 +3,125 @@
namespace App\Actions; namespace App\Actions;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod; use App\Enums\PaymentMethod;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Payment; use App\Models\Payment;
use App\Pricing\CaseMoney;
use App\Process\CaseClosure;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonInterface; use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
/** /**
* Records a received payment (or a refund with a negative amount) and moves the booking along: * Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
* Bestätigt → Anzahlung erhalten → Bezahlt. * portal paid out to us, or we refunded the guest. A refund is stored as a negative amount.
*
* Only money of the guest that arrived on our account moves the booking along (Bestätigt → Anzahlung erhalten →
* Bezahlt). "Paid according to the portal" and a payout of the portal are facts of their own: they appear in the money
* overview and the history with their own words, never as "Anzahlung erhalten" (package 9, Abschnitt 5).
*/ */
class RecordPayment class RecordPayment
{ {
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null, PaymentKind $kind = PaymentKind::Guest, ?string $source = null): Payment
{ {
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment { $amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
$payment = DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment {
$payment = $booking->payments()->create([ $payment = $booking->payments()->create([
'amount' => $amount, 'amount' => $amount,
'paid_on' => $paidOn->toDateString(), 'paid_on' => $paidOn->toDateString(),
'method' => $method, 'method' => $method,
'note' => $note, 'note' => $note,
'recorded_by' => $recordedBy, 'recorded_by' => $recordedBy,
'kind' => $kind,
'source' => $source,
]); ]);
$booking->unsetRelation('payments'); $booking->unsetRelation('payments');
$this->updateStatus($booking); $this->updateStatus($booking);
$this->settleTasks($booking, $kind, $recordedBy ?? CaseLog::actor());
return $payment; return $payment;
}); });
CaseClosure::refresh($booking->fresh());
return $payment;
} }
public function updateStatus(Booking $booking): void public function updateStatus(Booking $booking): void
{ {
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid]; $status = self::statusFor($booking);
if (! in_array($booking->status, $paymentStatuses, true)) { if ($status !== null && $status !== $booking->status) {
return;
}
$paid = $booking->paidAmount();
$status = match (true) {
$paid >= $booking->total => BookingStatus::Paid,
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
default => BookingStatus::Confirmed,
};
if ($status !== $booking->status) {
$booking->update(['status' => $status]); $booking->update(['status' => $status]);
} }
} }
/**
* The payment status the booking should have by the guest's money on our account, or null when payments do not move
* this booking (not binding, closed, cancelled).
*/
public static function statusFor(Booking $booking): ?BookingStatus
{
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
return null;
}
$paid = $booking->paidToUs();
return match (true) {
$booking->total !== null && $booking->total > 0 && $paid >= $booking->total => BookingStatus::Paid,
$booking->deposit !== null && $paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
default => BookingStatus::Confirmed,
};
}
/**
* The history line in the words of what really happened.
*/
public static function summary(Booking $booking, PaymentKind $kind, int $amount, CarbonInterface $paidOn, ?string $source): string
{
$portal = $source ?: ($booking->processChannel()?->name ?? 'Portal');
return match ($kind) {
PaymentKind::Guest => 'Zahlung des Gastes auf unserem Konto eingegangen: '.Money::format($amount),
PaymentKind::GuestViaPortal => 'Laut '.$portal.' hat der Gast '.Money::format($amount).' an das Portal gezahlt – noch kein Geld bei uns',
PaymentKind::PortalPayout => 'Auszahlung von '.$portal.' auf unserem Konto eingegangen: '.Money::format($amount),
PaymentKind::Refund => 'Erstattung an den Gast: '.Money::format(abs($amount)),
}.' (vom '.$paidOn->format('d.m.Y').')';
}
/**
* Tasks that the payment settles: the payout check once nothing is outstanding, the claim after the stay once the
* guest owes nothing more.
*/
private function settleTasks(Booking $booking, PaymentKind $kind, string $by): void
{
$money = CaseMoney::of($booking);
$open = fn (BookingTaskKind $taskKind) => BookingTask::query()->where('booking_id', $booking->id)->where('kind', $taskKind)->where('status', BookingTaskStatus::Open)->get();
if ($kind === PaymentKind::PortalPayout) {
$payout = $money->payout();
if (($payout['outstanding'] ?? 0) === 0) {
$open(BookingTaskKind::PayoutCheck)->each->complete($by, 'Auszahlung erfasst: '.Money::format($payout['received']).'.');
}
}
if (in_array($kind, [PaymentKind::Guest, PaymentKind::GuestViaPortal], true)) {
// A reminder that is no longer needed is closed by the payment itself.
if ($booking->openDeposit() === 0) {
$open(BookingTaskKind::DepositReminder)->each->complete($by, 'Anzahlung eingegangen.');
}
if ($booking->openAmount() === 0) {
foreach ([BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim] as $settled) {
$open($settled)->each->complete($by, 'Betrag vollständig erhalten.');
}
}
}
}
} }
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Actions;
use App\Enums\AmountKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Models\Booking;
use App\Pricing\PortalPrice;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* Takes over what a portal shows about a booking (package 8): the guest's total as the agreed price ("Gesamtpreis laut
* Portal"), and – as far as the portal shows them – price positions, collective amounts, commission, announced payouts,
* instalments and what the guest has paid to the portal. Every value is stored with its source and date as stated; the
* total is never recalculated from the positions, and a statement entered twice is stored once.
*/
class RecordPortalAmounts
{
public function __construct(private PortalPrice $price, private RecordPayment $payments) {}
/**
* @param list<array{kind: AmountKind|string, label?: ?string, amount: int, due_on?: ?string, note?: ?string}> $amounts
* @param list<array{amount: int, paid_on: string}> $paidViaPortal instalments the portal shows as paid by the guest
*/
public function handle(Booking $booking, ?int $guestTotal, array $amounts, array $paidViaPortal, string $source, ?CarbonImmutable $statedOn = null, ?string $by = null): void
{
$statedOn ??= CarbonImmutable::today();
DB::transaction(function () use ($booking, $guestTotal, $amounts, $paidViaPortal, $source, $statedOn, $by): void {
if ($guestTotal !== null && $guestTotal !== $booking->total) {
$before = $booking->total;
$booking->update($this->price->columns($booking->property, $booking->arrival, $booking->departure, $booking->guests, $guestTotal, $source));
CaseLog::record($booking, 'price', 'Gesamtpreis laut '.$source.': '.Money::format($guestTotal).($before !== null ? ' (vorher '.Money::format($before).')' : ''));
}
foreach ($amounts as $row) {
$kind = $row['kind'] instanceof AmountKind ? $row['kind'] : AmountKind::from((string) $row['kind']);
$label = filled($row['label'] ?? null) ? trim((string) $row['label']) : null;
$exists = $booking->amounts()->where('kind', $kind)->where('amount', (int) $row['amount'])->where('source', $source)
->where(fn ($query) => $label === null ? $query->whereNull('label') : $query->where('label', $label))->exists();
if ($exists) {
continue;
}
$booking->amounts()->create([
'kind' => $kind, 'label' => $label, 'amount' => (int) $row['amount'], 'source' => $source,
'stated_on' => $statedOn->toDateString(), 'due_on' => filled($row['due_on'] ?? null) ? $row['due_on'] : null,
'note' => filled($row['note'] ?? null) ? trim((string) $row['note']) : null, 'recorded_by' => $by,
]);
}
foreach ($paidViaPortal as $row) {
$paidOn = CarbonImmutable::parse($row['paid_on']);
$known = $booking->payments()->where('kind', PaymentKind::GuestViaPortal)->where('amount', (int) $row['amount'])->whereDate('paid_on', $paidOn)->exists();
if (! $known) {
$this->payments->handle($booking, (int) $row['amount'], $paidOn, PaymentMethod::Other, 'laut '.$source, $by, PaymentKind::GuestViaPortal, $source);
}
}
});
app(CaseAutomation::class)->advance($booking->fresh());
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ public static function kindFor(Booking $booking): DocumentKind
{ {
$kind = DocumentKind::forCase($booking); $kind = DocumentKind::forCase($booking);
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord], true) ? $kind : DocumentKind::Confirmation; return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord, DocumentKind::StayConfirmation], true) ? $kind : DocumentKind::Confirmation;
} }
private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool
+8 -8
View File
@@ -17,7 +17,8 @@
* Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord * Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord
* (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click * (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click
* ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured * ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured
* number of days before arrival. Completion after departure. * number of days before arrival. Preparation of the stays and their closing after departure ({@see PrepareStays},
* {@see CloseStay}).
*/ */
class SendBookingReminders class SendBookingReminders
{ {
@@ -27,7 +28,7 @@ class SendBookingReminders
private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14; private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14;
/** /**
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int} * @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int, prepared: int}
*/ */
public function handle(): array public function handle(): array
{ {
@@ -68,18 +69,17 @@ public function handle(): array
$booking->update(['arrival_info_sent_at' => now()]); $booking->update(['arrival_info_sent_at' => now()]);
} }
$completed = Booking::query() // Package 9: prepare the coming stays, close the stays whose departure has passed (open money stays as follow-up).
->where('status', BookingStatus::Paid) $prepared = app(PrepareStays::class)->handle();
->whereDate('departure', '<', $today) $completed = app(CloseStay::class)->due();
->get();
$completed->each->update(['status' => BookingStatus::Completed]);
return [ return [
'deposit_overdue' => $depositTasks, 'deposit_overdue' => $depositTasks,
'balance_request' => $requestTasks, 'balance_request' => $requestTasks,
'balance_overdue' => $overdueTasks, 'balance_overdue' => $overdueTasks,
'arrival_info' => $arrivals->count(), 'arrival_info' => $arrivals->count(),
'completed' => $completed->count(), 'completed' => $completed,
'prepared' => $prepared['arrival_details'] + $prepared['stay_tasks'],
]; ];
} }
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\DocumentComposer;
use App\Documents\OfferTerms;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\InformationSent;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Inbox;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Package 7 (E-026, P02 "Haltefrist = 0"): answers a request that reserves nothing with an information "unter Vorbehalt" –
* price and availability as checked now, no reservation and no acceptance link that could conclude a contract. The guest
* gets a signed link to ask for the booking ({@see SubmitBookingWish}); everything is checked again then.
*
* Sending again replaces the previous information: older links stop working and a booking wish made on them is void.
*/
class SendInformation
{
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private Inbox $inbox,
) {}
/**
* @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
*/
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
{
if ($sendMail && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
$toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Information, $changes)->toConfirm();
if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) {
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm));
}
DB::transaction(function () use ($booking, $changes): void {
$booking->lockForTransition();
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true) || $booking->isHoldActive()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Auskunft beantwortet');
}
if (isset($changes['expected_version']) && $booking->information_version !== (int) $changes['expected_version']) {
throw new ReservationException('Inzwischen wurde schon eine Auskunft gesendet (Version '.$booking->information_version.'). Es wurde nichts erneut gesendet.');
}
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$promoCode = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->offer->quoteFor($booking, $stay, $adjustment, $adjustmentLabel);
if (filled($changes['guest'] ?? null)) {
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
}
$validUntil = filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours());
$booking->update([
'status' => BookingStatus::Reserved,
'hold_expires_at' => null,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $stay->guests,
'promo_code' => $quote->promoCodeApplied ? $promoCode : null,
'price_adjustment' => $adjustment !== 0 ? $adjustment : null,
'price_adjustment_label' => $adjustment !== 0 ? $adjustmentLabel : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'information_version' => $booking->information_version + 1,
'information_sent_at' => now(),
'information_valid_until' => $validUntil,
'offer_message' => $changes['offer_message'] ?? null,
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
// A wish on an older information is void; the guest asks again on the new one.
'wish_at' => null,
'wish' => null,
]);
$booking->refresh();
$booking->update(['information' => [
'version' => $booking->information_version,
'sent_at' => $booking->information_sent_at?->toIso8601String(),
'valid_until' => $validUntil->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => self::quoteHash($booking),
'terms_sha256' => hash('sha256', json_encode($booking->offer_terms['texts'] ?? [])),
]]);
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Durch eine neue Auskunft ersetzt.', 'completed_at' => now(), 'completed_by' => CaseLog::actor()]);
});
$booking->refresh();
CaseLog::record($booking, 'document', 'Auskunft unter Vorbehalt Version '.$booking->information_version.' erstellt (Preis '.Money::format((int) $booking->total).', ohne Reservierung)', data: array_filter([
'kind' => DocumentKind::Information->value,
'template' => $booking->offer_terms['template'] ?? null,
'information' => $booking->information,
'confirmed' => $toConfirm,
]));
if ($sendMail) {
$this->deliver($booking);
}
return $booking;
}
/**
* Sends the information mail; a failing mail server keeps the saved information and is reported in the inbox.
*
* @throws ReservationException
*/
public function deliver(Booking $booking): void
{
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new InformationSent($booking, $this->informationUrl($booking)));
} catch (Throwable $exception) {
Log::warning('Auskunft nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$this->inbox->post(
InboxMessageKind::OfferMailFailed,
'booking-'.$booking->id.':i'.$booking->information_version,
'Auskunft '.$booking->reference.' nicht zugestellt',
'Die Auskunft ist gespeichert, aber die E-Mail konnte nicht versendet werden. Auf der Vorgangsseite kann der Link kopiert und dem Gast anders übermittelt werden.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
throw new ReservationException('Die Auskunft wurde gespeichert, aber die E-Mail konnte nicht versendet werden.');
}
}
/**
* The guest's link to the information page; valid while the information is valid and only for this version.
*/
public function informationUrl(Booking $booking): string
{
$parameters = ['booking' => $booking, 'v' => $booking->information_version];
$until = $booking->information_valid_until ?? now()->addDay();
return $booking->website()?->temporarySignedRoute('information.show', $until, $parameters)
?? URL::temporarySignedRoute('information.show', $until, $parameters);
}
/**
* Fingerprint of the price lines the guest was told.
*/
public static function quoteHash(Booking $booking): string
{
return hash('sha256', json_encode([$booking->quote['lines'] ?? [], $booking->total, $booking->arrival?->toDateString(), $booking->departure?->toDateString(), $booking->guests]));
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Availability\CalendarClearance;
use App\Documents\DocumentComposer;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\BookingWishAnswered;
use App\Mail\BookingWishNotice;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Inbox;
use App\Support\Money;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Package 7 (E-026, E-030): the guest asks for the booking from an information "unter Vorbehalt". Everything is checked
* again in one locked step – the whole stay still free, the imported portal calendars current, the price the guest was
* told still the price of today, the data for the booking complete. Then the effective processing decides:
* automatically the booking is confirmed at once (only when nothing at all stands in the way), otherwise the landlord
* gets the task "Buchungswunsch bestätigen?". When the dates were given away meanwhile, no booking comes about; the
* guest gets a friendly answer and the landlord a note.
*
* Asking again for the same information is harmless (no second booking, no second mail); a link of an older information
* no longer works.
*/
class SubmitBookingWish
{
public const CONFIRMED = 'confirmed';
public const PENDING = 'pending';
public const UNAVAILABLE = 'unavailable';
public const ALREADY = 'already';
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private CalendarClearance $clearance,
private ConfirmBooking $confirm,
private Inbox $inbox,
) {}
/**
* @return string one of the outcome constants
*
* @throws ReservationException when the link is outdated, expired or the request is no longer open
*/
public function handle(Booking $booking, int $version, ?string $ip = null): string
{
$booking->loadMissing(['guest', 'property']);
if ($this->alreadyAsked($booking, $version)) {
return self::ALREADY;
}
$this->ensureCurrent($booking, $version);
// Network access (calendar imports) stays outside the transaction.
rescue(fn () => $this->clearance->refresh($booking->property), report: false);
$stale = $this->clearance->staleImports($booking->property)->pluck('name')->all();
$outcome = DB::transaction(function () use ($booking, $version, $ip, $stale): string {
$booking->lockForTransition();
if ($this->alreadyAsked($booking, $version)) {
return self::ALREADY;
}
$this->ensureCurrent($booking, $version);
$record = [
'information_version' => $version,
'at' => now()->toIso8601String(),
'ip_hash' => $ip !== null ? hash('sha256', $ip.config('app.key')) : null,
'total_told' => $booking->information['total'] ?? $booking->total,
'terms_sha256' => $booking->information['terms_sha256'] ?? null,
'via' => 'information_link',
];
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
$booking->update([
'wish_at' => now(),
'wish' => [...$record, 'outcome' => self::UNAVAILABLE, 'findings' => ['Der Zeitraum ist inzwischen vergeben.']],
'status' => BookingStatus::Declined,
'declined_by' => 'us',
]);
return self::UNAVAILABLE;
}
$findings = $this->findings($booking, $stale);
$automatic = $booking->processingMode() === ProcessingMode::Automatic;
$booking->update([
'wish_at' => now(),
'wish' => [...$record, 'total_now' => $findings['total_now'], 'findings' => $findings['findings'], 'outcome' => $automatic && $findings['findings'] === [] ? self::CONFIRMED : self::PENDING],
]);
if ($automatic && $findings['findings'] === []) {
$this->confirm->bind($booking);
$booking->update([
'accepted_at' => now(),
'acceptance' => [
'via' => 'booking_wish',
'information_version' => $version,
'wish_at' => $booking->wish_at?->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => SendInformation::quoteHash($booking),
'terms_sha256' => $record['terms_sha256'],
'confirmed_by' => 'automatisch nach erneuter Prüfung',
],
]);
return self::CONFIRMED;
}
BookingTask::openOnce($booking, BookingTaskKind::BookingWish, 'v'.$version, [
'due_on' => today(),
'note' => $findings['findings'] === [] ? 'Zeitraum frei, Preis unverändert.' : implode(' ', $findings['findings']),
]);
return self::PENDING;
});
$booking->refresh();
CaseLog::record($booking, 'wish', match ($outcome) {
self::CONFIRMED => 'Buchungswunsch des Gastes – automatisch geprüft und verbindlich bestätigt',
self::PENDING => 'Buchungswunsch des Gastes eingegangen – wartet auf Ihre Bestätigung',
self::UNAVAILABLE => 'Buchungswunsch des Gastes – Zeitraum inzwischen vergeben, keine Buchung',
default => 'Buchungswunsch wiederholt (ohne Wirkung)',
}, data: $outcome === self::ALREADY ? [] : ['wish' => $booking->wish], actor: CaseLog::GUEST);
$this->notify($booking, $outcome);
return $outcome;
}
/**
* Checks that the page shows the form for: the information is the current one, still valid and the request open.
*
* @throws ReservationException
*/
public function ensureCurrent(Booking $booking, int $version): void
{
if ($booking->information_version === 0 || $version !== $booking->information_version) {
throw new ReservationException('Diese Auskunft ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.');
}
if ($booking->wish_at !== null) {
throw new ReservationException('Zu dieser Auskunft liegt Ihr Buchungswunsch bereits vor.');
}
if ($booking->status !== BookingStatus::Reserved) {
throw new ReservationException(in_array($booking->status, BookingStatus::occupying(), true)
? 'Ihre Buchung ist bereits verbindlich bestätigt – Sie müssen nichts weiter tun.'
: 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.');
}
if (! $booking->information_valid_until?->isFuture()) {
throw new ReservationException('Diese Auskunft ist abgelaufen. Gern können Sie über unsere Webseite neu anfragen; wir prüfen dann Preis und Verfügbarkeit erneut.');
}
}
/**
* Everything that keeps the wish from being confirmed automatically, and the price of today.
*
* @param list<string> $stale names of portals whose calendar is not current
* @return array{findings: list<string>, total_now: ?int}
*/
public function findings(Booking $booking, array $stale = []): array
{
$findings = [];
$totalNow = null;
try {
$label = (string) ($booking->price_adjustment_label ?: 'Zuschlag');
$quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, $label);
$totalNow = $quote->total();
$told = (int) ($booking->information['total'] ?? $booking->total);
if ($totalNow !== $told) {
$findings[] = 'Der Preis hat sich seit der Auskunft geändert: damals '.Money::format($told).', heute '.Money::format($totalNow).'.';
}
} catch (QuoteException $exception) {
$findings[] = 'Der Preis lässt sich heute nicht berechnen: '.$exception->getMessage();
}
if ($stale !== []) {
$findings[] = 'Der Kalenderstand von '.implode(', ', $stale).' ist nicht aktuell.';
}
$findings = [...$findings, ...app(CaseAutomation::class)->documentBlockers($booking)];
if (! app(AutoOffer::class)->contractTextsReleased()) {
$findings[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
}
// What the confirmation with the contract would need to be confirmed by the landlord (unreleased texts, gaps).
foreach (app(DocumentComposer::class)->compose($booking, DocumentKind::Confirmation)->toConfirm() as $point) {
$findings[] = $point;
}
return ['findings' => array_values(array_unique($findings)), 'total_now' => $totalNow];
}
private function alreadyAsked(Booking $booking, int $version): bool
{
return $booking->wish_at !== null && ($booking->wish['information_version'] ?? null) === $version;
}
/**
* Mails after the commit; none of them can undo what was decided.
*/
private function notify(Booking $booking, string $outcome): void
{
if ($outcome === self::ALREADY) {
return;
}
if ($outcome === self::CONFIRMED) {
$this->confirm->deliver($booking);
}
try {
if ($outcome !== self::CONFIRMED && filled($booking->guest?->email)) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking, $outcome));
}
Mail::to(Settings::notificationRecipients())->send(new BookingWishNotice($booking, $outcome));
} catch (Throwable $exception) {
Log::warning('Mail zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
if ($outcome === self::UNAVAILABLE) {
$this->inbox->post(
InboxMessageKind::OfferRejected,
'wish-'.$booking->id.':i'.$booking->information_version,
'Buchungswunsch '.$booking->reference.': Zeitraum inzwischen vergeben',
'Der Gast hat aus der Auskunft die Buchung angefragt, aber der Zeitraum ist inzwischen belegt. Es ist keine Buchung entstanden; der Gast hat eine freundliche Absage erhalten.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
}
}
}
+10
View File
@@ -41,6 +41,16 @@ public function properties(Channel $channel, Booking|BlockedPeriod $occupation):
/** @return array<string, string|null> */ /** @return array<string, string|null> */
public function context(Booking|BlockedPeriod $occupation): array public function context(Booking|BlockedPeriod $occupation): array
{ {
// Own use, private stays and blocks (A6) are exported exactly like the manual blocks they replace: no reference;
// a guest's name only where the channel exports names at all.
if ($occupation instanceof Booking && $occupation->isInternal()) {
$guest = $occupation->guest?->anonymized_at === null ? $occupation->guest : null;
return ['occupation_label' => 'Belegt', 'property_name' => $occupation->property->name, 'arrival' => $occupation->arrival->format('d.m.Y'),
'departure' => $occupation->departure->format('d.m.Y'), 'nights' => (string) (int) $occupation->arrival->diffInDays($occupation->departure), 'channel_name' => null,
...($guest !== null ? ['guest_first_name' => $guest->first_name, 'guest_full_name' => filled($guest->last_name) ? $guest->full_name : null] : [])];
}
$booking = $occupation instanceof Booking; $booking = $occupation instanceof Booking;
$start = $booking ? $occupation->arrival : $occupation->starts_on; $start = $booking ? $occupation->arrival : $occupation->starts_on;
$end = $booking ? $occupation->departure : $occupation->ends_on; $end = $booking ? $occupation->departure : $occupation->ends_on;
+2 -1
View File
@@ -33,7 +33,8 @@ public function build(Channel $channel): string
} }
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) { foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
/** @var Booking $booking */ /** @var Booking $booking */
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking)); // A block taken over as a case keeps the identity the portals already know.
$events[] = $this->event(($booking->export_uid ?? "booking-{$booking->id}").$suffix, $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
} }
$blocks = $property->blockedPeriods() $blocks = $property->blockedPeriods()
+159
View File
@@ -0,0 +1,159 @@
<?php
namespace App\Console\Commands;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Tenant;
use App\Process\CaseLog;
use App\Process\ProcessSettings;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#[Signature('cases:adopt-blocks
{--apply : Wirklich übernehmen (ohne: nur Vorschau)}
{--revert= : Eine frühere Übernahme anhand ihres Berichts zurücknehmen}')]
#[Description('Bisherige manuelle Sperren als A6-Vorgänge übernehmen (Vorschau, Bericht, wiederholbar, rücknehmbar); der Kalenderexport für die Portale bleibt gleich')]
class AdoptManualBlocks extends Command
{
private const DIRECTORY = 'block-adoptions';
private const ADOPTED = 'übernommen';
public function handle(TenantRunner $runner, ProcessSettings $settings): int
{
if (filled($this->option('revert'))) {
return $this->revert((string) $this->option('revert'));
}
$apply = (bool) $this->option('apply');
$report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => []];
$succeeded = $runner->each(function (Tenant $tenant) use ($apply, $settings, &$report): void {
$blocks = BlockedPeriod::query()->with(['property', 'guest'])->where('source', 'manual')->whereNull('linked_booking_id')->orderBy('starts_on')->get();
foreach ($blocks as $block) {
$kind = $block->guest_id !== null ? InternalKind::PrivateStay : InternalKind::fromPurpose($block->block_purpose);
$entry = [
'tenant' => $tenant->id, 'blocked_period_id' => $block->id, 'property' => $block->property?->name,
'period' => $block->starts_on->format('d.m.Y').'–'.$block->ends_on->format('d.m.Y'), 'kind' => $kind->value,
'occasion' => $block->block_note ?: $block->reason, 'booking_id' => null, 'result' => 'neu',
];
if (Booking::query()->where('export_uid', 'block-'.$block->id)->exists()) {
$entry['result'] = 'schon übernommen';
} elseif (Booking::query()->occupying()->where('property_id', $block->property_id)->overlapping($block->starts_on, $block->ends_on)->exists()) {
$entry['result'] = 'unklar: überschneidet sich mit einem Vorgang – nicht übernommen';
} elseif ($apply) {
$entry['booking_id'] = $this->adopt($block, $kind, $settings)->id;
$entry['result'] = self::ADOPTED;
}
$report['entries'][] = $entry;
}
});
$this->table(['Wohnung', 'Zeitraum', 'Art', 'Anlass', 'Ergebnis', 'Vorgang'], array_map(fn (array $entry): array => [
$entry['property'], $entry['period'], InternalKind::from($entry['kind'])->getLabel(), $entry['occasion'], $entry['result'], $entry['booking_id'] ? '#'.$entry['booking_id'] : '–',
], $report['entries']));
$suffix = $apply ? '' : '-vorschau';
$path = self::DIRECTORY.'/'.$report['run'].$suffix.'.json';
for ($number = 2; Storage::disk('local')->exists($path); $number++) {
$path = self::DIRECTORY.'/'.$report['run'].$suffix.'-'.$number.'.json';
}
Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$counts = collect($report['entries'])->countBy('result')->map(fn (int $count, string $result): string => $result.' '.$count)->implode(', ');
$this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.($counts ?: 'keine manuellen Sperren'));
$this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : ''));
if ($succeeded < $runner->tenants()->count()) {
$this->error('Bei mindestens einem Vermieter ist ein Fehler aufgetreten – Details im Protokoll (storage/logs).');
return self::FAILURE;
}
return self::SUCCESS;
}
/**
* The block becomes a case without any side effect: no portal tasks and no mails (the portals have the dates
* already), the same export identity and time stamp; the block is kept (deleted softly) for a revert.
*/
private function adopt(BlockedPeriod $block, InternalKind $kind, ProcessSettings $settings): Booking
{
return DB::transaction(function () use ($block, $kind, $settings): Booking {
$profile = $settings->resolve($block->property, null, IntakeKind::Internal)->withOrigin('migration');
$booking = Model::withoutEvents(function () use ($block, $kind, $profile): Booking {
$booking = new Booking([
'status' => BookingStatus::Confirmed, 'source' => 'internal', 'intake' => IntakeKind::Internal, 'internal_kind' => $kind,
'occasion' => $block->block_note ?: $block->reason, 'arrival' => $block->starts_on->toDateString(), 'departure' => $block->ends_on->toDateString(),
'export_uid' => 'block-'.$block->id, 'confirmed_at' => $block->created_at,
]);
$booking->forceFill([
'tenant_id' => $block->tenant_id, 'property_id' => $block->property_id, 'guest_id' => $block->guest_id,
'case_type' => $profile->caseType, 'profile' => $profile->toArray(),
'created_at' => $block->created_at, 'updated_at' => $block->updated_at,
]);
$booking->timestamps = false;
$booking->save();
// Dates are only cast while timestamps are on; the reference counts by the year of creation.
$booking->timestamps = true;
$reference = $booking->refresh()->nextReference();
$booking->timestamps = false;
$booking->forceFill(['reference' => $reference])->save();
$block->forceFill(['linked_booking_id' => $booking->id, 'review_note' => 'In Vorgang übernommen (A6).'])->saveQuietly();
$block->deleteQuietly();
return $booking;
});
CaseLog::record($booking, 'intake', 'Aus der bisherigen Sperrzeitenliste übernommen'.($booking->occasion ? ': '.$booking->occasion : ''), actor: CaseLog::SYSTEM, data: ['blocked_period_id' => $block->id]);
return $booking;
});
}
/**
* Takes an adoption back: the block comes back as it was and the case created by the run goes – unless somebody has
* worked on the case since (then it is reported and kept).
*/
private function revert(string $path): int
{
if (! Storage::disk('local')->exists($path)) {
$this->error('Bericht nicht gefunden: '.$path);
return self::FAILURE;
}
$report = json_decode((string) Storage::disk('local')->get($path), true);
$kept = [];
foreach ((array) ($report['entries'] ?? []) as $entry) {
if (($entry['result'] ?? null) !== self::ADOPTED) {
continue;
}
$booking = Booking::query()->withoutGlobalScopes()->find($entry['booking_id']);
if ($booking !== null && $booking->events()->where('type', '!=', 'intake')->exists()) {
$kept[] = $booking->reference;
continue;
}
Model::withoutEvents(function () use ($entry, $booking): void {
$block = BlockedPeriod::query()->withoutGlobalScopes()->withTrashed()->find($entry['blocked_period_id']);
$block?->forceFill(['linked_booking_id' => null, 'review_note' => null, 'deleted_at' => null])->saveQuietly();
$booking?->delete();
});
}
$this->info('Zurückgenommen.'.($kept === [] ? '' : ' Nicht entfernt, weil seitdem bearbeitet: '.implode(', ', $kept)));
return self::SUCCESS;
}
}
@@ -38,7 +38,7 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
$report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => [], 'channel_task_ids' => []]; $report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => [], 'channel_task_ids' => []];
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id'); $firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
$runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void { $succeeded = $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
$channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get(); $channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
foreach ($channels as $channel) { foreach ($channels as $channel) {
$entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id') $entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
@@ -75,6 +75,12 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
$this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.$counts->map(fn (int $count, string $outcome): string => IntakeOutcome::from($outcome)->getLabel().' '.$count)->implode(', ')); $this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.$counts->map(fn (int $count, string $outcome): string => IntakeOutcome::from($outcome)->getLabel().' '.$count)->implode(', '));
$this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : '')); $this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : ''));
if ($succeeded < $runner->tenants()->count()) {
$this->error('Bei mindestens einem Vermieter ist ein Fehler aufgetreten – Details im Protokoll (storage/logs).');
return self::FAILURE;
}
return self::SUCCESS; return self::SUCCESS;
} }
@@ -0,0 +1,58 @@
<?php
namespace App\Console\Commands;
use App\Actions\RecordPayment;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\Tenant;
use App\Process\CaseLog;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('cases:recheck-payment-status
{--apply : Wirklich korrigieren (ohne: nur Vorschau)}')]
#[Description('Zahlungsstatus bestehender Vorgänge nach der neuen Regel prüfen: nur Geld des Gastes auf unserem Konto zählt als „Anzahlung erhalten“/„Bezahlt“, nicht „laut Portal bezahlt“ (Vorschau, Korrektur nur mit --apply und mit Eintrag im Verlauf)')]
class RecheckPaymentStatus extends Command
{
public function handle(TenantRunner $runner): int
{
$apply = (bool) $this->option('apply');
$rows = [];
$succeeded = $runner->each(function (Tenant $tenant) use ($apply, &$rows): void {
$cases = Booking::query()->with(['payments', 'property', 'importChannel', 'originChannel'])
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])->get();
foreach ($cases as $booking) {
$target = RecordPayment::statusFor($booking);
if ($target === null || $target === $booking->status) {
continue;
}
$rows[] = [$tenant->name, $booking->reference, $booking->status->getLabel(), $target->getLabel(), $apply ? 'korrigiert' : 'Vorschau'];
if ($apply) {
CaseLog::context(fn () => $booking->update(['status' => $target]), actor: CaseLog::SYSTEM, reason: 'Zahlungsstatus nach neuer Regel: „laut Portal bezahlt“ ist kein Eingang auf unserem Konto (cases:recheck-payment-status).');
}
}
});
if ($rows === []) {
$this->info('Kein Vorgang mit abweichendem Zahlungsstatus.');
} else {
$this->table(['Vermieter', 'Vorgang', 'bisher', 'nach neuer Regel', 'Ergebnis'], $rows);
if (! $apply) {
$this->comment('Nur Vorschau. Mit --apply werden die Status korrigiert und im Verlauf vermerkt.');
}
}
if ($succeeded < $runner->tenants()->count()) {
$this->error('Für mindestens einen Vermieter ist die Prüfung fehlgeschlagen (siehe Log).');
return self::FAILURE;
}
return self::SUCCESS;
}
}
@@ -25,10 +25,13 @@ public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
$pending = Booking::query() $pending = Booking::query()
->where('status', BookingStatus::Reserved) ->where('status', BookingStatus::Reserved)
->where('offer_version', 0) ->where('offer_version', 0)
->where('hold_expires_at', '>', now()) ->where('information_version', 0)
// Held requests while their hold runs; requests without a hold (information, package 7) for two weeks.
->where(fn ($query) => $query->where('hold_expires_at', '>', now())->orWhere(fn ($open) => $open->whereNull('hold_expires_at')->where('created_at', '>', now()->subDays(14))))
->where(fn ($query) => $query->whereNull('intake')->orWhere('intake', 'inquiry'))
->with(['property', 'guest', 'importChannel', 'originChannel']) ->with(['property', 'guest', 'importChannel', 'originChannel'])
->get() ->get()
->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && $booking->process()->preReservation()); ->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && ($booking->isHoldActive() || ! $booking->process()->preReservation()));
$sent = 0; $sent = 0;
foreach ($pending as $booking) { foreach ($pending as $booking) {
+29 -10
View File
@@ -2,6 +2,7 @@
namespace App\Documents; namespace App\Documents;
use App\Actions\SendInformation;
use App\Actions\SendOffer; use App\Actions\SendOffer;
use App\Availability\AvailabilityChecker; use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
@@ -55,13 +56,15 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha
$draft = clone $booking; $draft = clone $booking;
$draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null); $draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null);
if ($kind === DocumentKind::Offer) { $quoted = in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true);
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes)]; if ($quoted) {
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes, $kind)];
} }
$frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms))); $frozen = ! $quoted && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms)));
$explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null); $explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null);
$template = match (true) { $template = match (true) {
$kind === DocumentKind::StayConfirmation => null,
$frozen => isset($booking->offer_terms['template']['id']) ? ContractTemplate::query()->find($booking->offer_terms['template']['id']) : 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), default => OfferTerms::templateFor($booking, $explicitTemplate ? $changes['contract_template_id'] : null),
}; };
@@ -98,17 +101,19 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha
} }
/** /**
* Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will. * Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} (and the information
* of a request without a hold, {@see SendInformation}) will.
* *
* @param array<string, mixed> $changes * @param array<string, mixed> $changes
* @return list<DocumentFinding> * @return list<DocumentFinding>
*/ */
private function prepareOffer(Booking $booking, Booking $draft, array $changes): array private function prepareOffer(Booking $booking, Booking $draft, array $changes, DocumentKind $kind = DocumentKind::Offer): array
{ {
$findings = []; $findings = [];
$information = $kind === DocumentKind::Information;
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) { if (! in_array($booking->status, $information ? [BookingStatus::Reserved, BookingStatus::Expired] : [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
$findings[] = DocumentFinding::blocker('Für diesen Vorgang ist kein Angebot mehr möglich ('.$booking->status->getLabel().').'); $findings[] = DocumentFinding::blocker('Für diesen Vorgang ist '.($information ? 'keine Auskunft' : 'kein Angebot').' mehr möglich ('.$booking->status->getLabel().').');
} }
try { try {
@@ -140,6 +145,20 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes):
$findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.'); $findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.');
} }
if ($information) {
$draft->forceFill([
'information_valid_until' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'information_version' => $booking->information_version + 1,
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
]);
$findings[] = DocumentFinding::info('Unverbindliche Auskunft: Der Zeitraum wird nicht reserviert, und der Gast kann nicht direkt annehmen. Fragt er die Buchung an, wird erneut geprüft.');
if ($booking->information_version > 0) {
$findings[] = DocumentFinding::info('Ersetzt Auskunft Version '.$booking->information_version.'; deren Link wird ungültig.');
}
return $findings;
}
$draft->forceFill([ $draft->forceFill([
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()), '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_version' => $booking->offer_version + 1,
@@ -148,7 +167,7 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes):
]); ]);
if (! $booking->process()->preReservation()) { if (! $booking->process()->preReservation()) {
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Ein Angebot mit Annahmelink reserviert ihn trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen. Eine Auskunft ohne Reservierung gibt es erst in einem späteren Ausbauschritt.', DocumentFinding::HOLD_ZERO); $findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht; vorgesehen ist eine unverbindliche Auskunft. Ein Angebot mit Annahmelink reserviert den Zeitraum für diesen Vorgang trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen.', DocumentFinding::HOLD_ZERO);
} }
if ($booking->offer_version > 0) { if ($booking->offer_version > 0) {
$findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.'); $findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.');
@@ -175,7 +194,7 @@ private function commonFindings(Booking $booking, Booking $draft, DocumentKind $
} elseif (blank($draft->guest->email)) { } elseif (blank($draft->guest->email)) {
$findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.'); $findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.');
} }
if ($kind !== DocumentKind::Offer && $booking->total === null) { if (! in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) && $booking->total === null) {
$findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.'); $findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.');
} }
if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) { if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) {
@@ -248,7 +267,7 @@ private function priceSource(Booking $booking, Booking $draft, DocumentKind $kin
return match (true) { return match (true) {
$draft->total === null => 'noch nicht bekannt', $draft->total === null => 'noch nicht bekannt',
($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet', ($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet',
$kind === DocumentKind::Offer => 'aus Ihren Preisen berechnet', in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) => 'aus Ihren Preisen berechnet',
$booking->accepted_at !== null => 'wie im angenommenen Angebot', $booking->accepted_at !== null => 'wie im angenommenen Angebot',
default => 'aus Ihren Preisen berechnet', default => 'aus Ihren Preisen berechnet',
}; };
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* A stated amount of a case as a portal or another source shows it (package 8, K01): stored as stated, never derived.
* Positions of the guest's price, what the landlord pays the portal, and what the portal announces to pay out stay
* apart; an unexplained collective amount stays unexplained.
*/
enum AmountKind: string implements HasLabel
{
case Accommodation = 'accommodation';
case Service = 'service';
case Discount = 'discount';
case Fee = 'fee';
case Unexplained = 'unexplained';
case Commission = 'commission';
case PayoutAnnounced = 'payout_announced';
case InstallmentDue = 'installment_due';
public function getLabel(): string
{
return match ($this) {
self::Accommodation => 'Übernachtung',
self::Service => 'Leistung / Zusatzleistung',
self::Discount => 'Rabatt (mit Minus)',
self::Fee => 'Gebühr oder Steuer',
self::Unexplained => 'Sammelposten, nicht aufgeschlüsselt',
self::Commission => 'Provision / an das Portal gezahlt',
self::PayoutAnnounced => 'Angekündigte Auszahlung an uns',
self::InstallmentDue => 'Rate des Gastes laut Portal fällig',
};
}
/**
* Whether the amount is part of the guest's price (and adds up to the guest total).
*/
public function isPricePosition(): bool
{
return in_array($this, [self::Accommodation, self::Service, self::Discount, self::Fee, self::Unexplained], true);
}
}
+51 -2
View File
@@ -8,6 +8,10 @@
/** /**
* What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is * What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is
* sent to the guest until the landlord has checked the payment and chooses to send the mail. * sent to the guest until the landlord has checked the payment and chooses to send the mail.
*
* Package 9 sorts every task into what it holds up: tasks of the stay ({@see self::blocksStay()}) keep the stay from
* being closed, commercial tasks ({@see self::isCommercial()}) keep the case from being settled, follow-ups hold up
* neither and simply stay on the case until they are done.
*/ */
enum BookingTaskKind: string implements HasLabel enum BookingTaskKind: string implements HasLabel
{ {
@@ -19,6 +23,14 @@ enum BookingTaskKind: string implements HasLabel
case PortalCancellation = 'portal_cancellation'; case PortalCancellation = 'portal_cancellation';
case PortalCancellationReported = 'portal_cancel_reported'; case PortalCancellationReported = 'portal_cancel_reported';
case PortalChangeReported = 'portal_change_reported'; case PortalChangeReported = 'portal_change_reported';
case RefundCheck = 'refund_check';
case BookingWish = 'booking_wish';
case ArrivalDetails = 'arrival_details';
case Service = 'service';
case Issue = 'issue';
case FollowUp = 'follow_up';
case PayoutCheck = 'payout_check';
case OpenClaim = 'open_claim';
public function getLabel(): string public function getLabel(): string
{ {
@@ -31,12 +43,49 @@ public function getLabel(): string
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen', self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen', self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen', self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen',
self::RefundCheck => 'Erstattung an den Gast prüfen',
self::BookingWish => 'Buchungswunsch bestätigen?',
self::ArrivalDetails => 'Anreisedaten beim Gast erfragen',
self::Service => 'Leistung vorbereiten',
self::Issue => 'Abweichung oder Problem klären',
self::FollowUp => 'Folgeaufgabe',
self::PayoutCheck => 'Auszahlung des Portals prüfen',
self::OpenClaim => 'Offenen Betrag nach der Abreise klären',
}; };
} }
/**
* Whether this is a payment reminder task (created by the daily run, settled by a payment or a reminder mail).
*/
public function isPayment(): bool public function isPayment(): bool
{ {
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported], true); return in_array($this, [self::DepositReminder, self::BalanceRequest, self::BalanceReminder], true);
}
/**
* Whether an open task of this kind keeps the stay from being closed (it belongs to the stay itself).
*/
public function blocksStay(): bool
{
return in_array($this, [self::Service, self::Issue, self::PortalChangeReported], true);
}
/**
* Whether an open task of this kind keeps the case from being commercially settled.
*/
public function isCommercial(): bool
{
return $this->isPayment() || in_array($this, [self::CancellationFee, self::RefundCheck, self::PayoutCheck, self::OpenClaim], true);
}
/**
* Kinds the landlord adds by hand on a case (several per case, each with its own title).
*
* @return list<self>
*/
public static function manual(): array
{
return [self::Service, self::Issue, self::FollowUp];
} }
/** /**
@@ -50,7 +99,7 @@ public function reminder(): ?array
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'], self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'], self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'], self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported => null, default => null,
}; };
} }
} }
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How a change of a booking was agreed with the guest – the evidence the case keeps (package 5). Sending an updated
* confirmation is none of these: it informs the guest, it does not show the guest's consent.
*/
enum ChangeBasis: string implements HasLabel
{
case Phone = 'phone';
case Email = 'email';
case InPerson = 'in_person';
case Portal = 'portal';
case GuestLink = 'guest_link';
case NotNeeded = 'not_needed';
public function getLabel(): string
{
return match ($this) {
self::Phone => 'am Telefon vereinbart',
self::Email => 'per E-Mail / schriftlich vereinbart',
self::InPerson => 'persönlich vereinbart',
self::Portal => 'im Portal geändert',
self::GuestLink => 'vom Gast über den Link angenommen',
self::NotNeeded => 'keine Zustimmung nötig (eigener Vorgang)',
};
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChangeStatus: string implements HasColor, HasLabel
{
/** Sent to the guest, waiting for the guest's answer; nothing has changed yet. */
case Proposed = 'proposed';
/** In force. */
case Applied = 'applied';
case Declined = 'declined';
case Withdrawn = 'withdrawn';
case Expired = 'expired';
public function getLabel(): string
{
return match ($this) {
self::Proposed => 'dem Gast vorgeschlagen',
self::Applied => 'wirksam',
self::Declined => 'vom Gast abgelehnt',
self::Withdrawn => 'zurückgezogen',
self::Expired => 'nicht beantwortet',
};
}
public function getColor(): string
{
return match ($this) {
self::Proposed => 'warning',
self::Applied => 'success',
default => 'gray',
};
}
}
+6 -5
View File
@@ -9,8 +9,8 @@
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case * 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 * 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 * 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 * without an acceptance link (E-004), a request without a hold gets the information "unter Vorbehalt" with the link to
* (package 6) are prepared as working drafts but cannot be sent yet. * ask for the booking (package 7, E-026).
*/ */
enum DocumentKind: string implements HasLabel enum DocumentKind: string implements HasLabel
{ {
@@ -40,10 +40,10 @@ public function description(): string
{ {
return match ($this) { return match ($this) {
self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.', self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.',
self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit ohne Zusage; der Gast kann die Buchung anfragen. Folgt mit Paket 7.', self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit zum Zeitpunkt der Prüfung, ohne Reservierung und ohne Zusage. Der Gast kann daraus die Buchung anfragen; verbindlich wird sie erst mit Ihrer (oder der automatischen) Bestätigung nach erneuter Prüfung.',
self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.', self::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::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::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.', self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
}; };
} }
@@ -59,6 +59,7 @@ public static function forCase(Booking $booking): ?self
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal, $booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord, $booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation, $booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
! $profile->preReservation() => self::Information,
default => self::Offer, default => self::Offer,
}; };
} }
@@ -84,7 +85,7 @@ public function containsContract(): bool
*/ */
public function isAvailable(): bool public function isAvailable(): bool
{ {
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true); return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
} }
/** /**
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* The kinds of internal cases (A6): the landlord's own use, a private stay of family or friends, or a block without a
* guest (maintenance and the like). None of them has a rental contract, payment reminders, reviews or marketing.
*/
enum InternalKind: string implements HasLabel
{
case OwnUse = 'own_use';
case PrivateStay = 'private_stay';
case Block = 'block';
public function getLabel(): string
{
return match ($this) {
self::OwnUse => 'Eigene Nutzung',
self::PrivateStay => 'Private Überlassung (Familie, Freunde)',
self::Block => 'Sperre (z. B. Wartung)',
};
}
public function hasGuests(): bool
{
return $this === self::PrivateStay;
}
public static function fromPurpose(?BlockedPeriodPurpose $purpose): self
{
return $purpose === BlockedPeriodPurpose::OwnUse ? self::OwnUse : self::Block;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* What a payment is (package 8): only the guest's payments count towards what the guest owes; a portal's payout is
* money on our account but no payment of the guest, and "paid to the portal" is the portal's statement, not money we
* received. Nothing is counted twice.
*/
enum PaymentKind: string implements HasLabel
{
/** The guest paid us (transfer, cash). */
case Guest = 'guest';
/** The portal reports that the guest paid it (no money on our account). */
case GuestViaPortal = 'guest_via_portal';
/** The portal paid out to us. */
case PortalPayout = 'portal_payout';
/** We paid money back to the guest (entered as a positive amount, counted negative). */
case Refund = 'refund';
public function getLabel(): string
{
return match ($this) {
self::Guest => 'Gast hat an uns gezahlt',
self::GuestViaPortal => 'Gast hat laut Portal ans Portal gezahlt',
self::PortalPayout => 'Auszahlung vom Portal erhalten',
self::Refund => 'Erstattung an den Gast',
};
}
/**
* Whether it counts towards what the guest has paid of the agreed total.
*/
public function countsAsGuestPayment(): bool
{
return $this !== self::PortalPayout;
}
/**
* Whether the money moved through our account.
*/
public function isOnOurAccount(): bool
{
return $this !== self::GuestViaPortal;
}
}
+1 -1
View File
@@ -41,7 +41,7 @@ public function question(): string
return match ($this) { return match ($this) {
self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?', self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?',
self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?', self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?',
self::HoldHours => 'Wie lange gilt ein Angebot (und bleibt der Zeitraum reserviert)?', self::HoldHours => 'Wie lange gilt ein Angebot bzw. eine unverbindliche Auskunft (mit Reservierung: so lange bleibt der Zeitraum reserviert)?',
self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?', self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?',
self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?', self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?',
self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?', self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?',
+7 -1
View File
@@ -13,11 +13,17 @@ enum QuoteLineType: string
/** Manual price change by the landlord in an offer (negative = reduction). */ /** Manual price change by the landlord in an offer (negative = reduction). */
case Adjustment = 'adjustment'; case Adjustment = 'adjustment';
/** The agreed rent of an internal case (A6), e.g. 0 for family. */
case Rent = 'rent';
/** The tourist tax (Kurabgabe) as its own position: persons × nights × the landlord's rate. */
case TouristTax = 'tourist_tax';
/** /**
* Whether the line counts towards the rent on which the deposit is calculated. * Whether the line counts towards the rent on which the deposit is calculated.
*/ */
public function isRent(): bool public function isRent(): bool
{ {
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment], true); return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment, self::Rent], true);
} }
} }
+4
View File
@@ -12,11 +12,15 @@ enum Responsibility: string implements HasLabel
case Landlord = 'landlord'; case Landlord = 'landlord';
case Portal = 'portal'; case Portal = 'portal';
/** Nobody: internal cases (A6) have no rental documents, payment reminders or guest mails. */
case Nobody = 'none';
public function getLabel(): string public function getLabel(): string
{ {
return match ($this) { return match ($this) {
self::Landlord => 'Wir', self::Landlord => 'Wir',
self::Portal => 'Das Portal', self::Portal => 'Das Portal',
self::Nobody => 'Entfällt',
}; };
} }
} }
@@ -9,7 +9,9 @@
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Mail\BookingConfirmed; use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation; use App\Mail\BookingDocumentation;
use App\Mail\InformationSent;
use App\Mail\OfferMade; use App\Mail\OfferMade;
use App\Mail\StayConfirmed;
use App\Models\Booking; use App\Models\Booking;
use App\Models\User; use App\Models\User;
use Closure; use Closure;
@@ -85,7 +87,9 @@ private static function mailPreview(DocumentComposition $composition): string
try { try {
return match ($composition->kind) { return match ($composition->kind) {
DocumentKind::Offer => (new OfferMade($draft, '#'))->render(), DocumentKind::Offer => (new OfferMade($draft, '#'))->render(),
DocumentKind::Information => (new InformationSent($draft, '#'))->render(),
DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(), DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(),
DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(),
default => (new BookingConfirmed($draft))->render(), default => (new BookingConfirmed($draft))->render(),
}; };
} catch (Throwable $exception) { } catch (Throwable $exception) {
@@ -98,7 +102,7 @@ private static function mailPreview(DocumentComposition $composition): string
private static function documentPreview(DocumentComposition $composition): string private static function documentPreview(DocumentComposition $composition): string
{ {
try { try {
[$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer); [$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: in_array($composition->kind, [DocumentKind::Offer, DocumentKind::Information], true));
return view($view, $data)->render(); return view($view, $data)->render();
} catch (Throwable $exception) { } catch (Throwable $exception) {
+2 -2
View File
@@ -34,9 +34,9 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
return (match ($setting) { return (match ($setting) {
ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder) ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder)
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'), ->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – eine Anfrage reserviert nichts'])->placeholder($placeholder), ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – der Gast erhält eine unverbindliche Auskunft und kann daraus die Buchung anfragen (erneute Prüfung vor der Bestätigung)'])->placeholder($placeholder),
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder), ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options(Responsibility::class)->placeholder($placeholder), ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder),
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder), ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
ProcessSetting::ContractTemplate => Select::make($name) ProcessSetting::ContractTemplate => Select::make($name)
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
+152
View File
@@ -0,0 +1,152 @@
<?php
namespace App\Filament\Pages;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Support\Money;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* "Wirksame Einstellungen" (expert view, KONFIGURATION_UND_WIRKSAMKEIT): for every property, every way a case can come
* in (direct request, each portal for requests and for binding bookings, own use) the value of every process setting
* that applies right now and the level it comes from – and for one chosen case the profile that really was applied.
* Read only: settings are changed where they belong ("So arbeite ich", the property, the portal).
*/
class EffectiveSettings extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'Wirksame Einstellungen';
protected static ?string $title = 'Wirksame Einstellungen';
protected static ?string $slug = 'wirksame-einstellungen';
protected static ?int $navigationSort = 3;
protected string $view = 'filament.pages.effective-settings';
public ?int $bookingId = null;
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin);
}
public function mount(): void
{
$this->bookingId = is_numeric(request()->query('vorgang')) ? (int) request()->query('vorgang') : null;
}
/**
* Every way a case of a property can come in, with the profile that would apply now.
*
* @return list<array{property: Property, columns: list<array{label: string, profile: ProcessProfile}>}>
*/
public function matrix(): array
{
$settings = app(ProcessSettings::class);
return Property::query()->orderBy('name')->get()->map(function (Property $property) use ($settings): array {
$columns = [['label' => 'Direkte Anfrage (Webseite, Telefon)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)]];
foreach (Channel::query()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
$columns[] = ['label' => $channel->name.' – Anfrage', 'profile' => $settings->resolve($property, $channel, IntakeKind::Inquiry)];
$columns[] = ['label' => $channel->name.' – feste Buchung', 'profile' => $settings->resolve($property, $channel, IntakeKind::Booking)];
}
$columns[] = ['label' => 'Eigene Nutzung / Sperre (A6)', 'profile' => $settings->resolve($property, null, IntakeKind::Internal)];
return ['property' => $property, 'columns' => $columns];
})->all();
}
/**
* @return list<ProcessSetting>
*/
public function settings(): array
{
return ProcessSetting::cases();
}
public function describe(ProcessSetting $setting, ProcessProfile $profile): string
{
$value = $profile->value($setting);
if ($setting === ProcessSetting::ContractTemplate) {
return $value === null ? 'Texte der Webseite' : (ContractTemplate::query()->find($value)?->label() ?? 'Vorlage Nr. '.$value);
}
return $setting->describe($value);
}
/**
* Where a setting is changed in the application.
*/
public static function where(ProcessSetting $setting): string
{
return $setting === ProcessSetting::ContractTemplate
? 'Wohnung › Abweichende Abwicklung (Experte) bzw. Portal › Anfragen / Feste Buchungen'
: 'System › So arbeite ich; Abweichung: Wohnung (Experte), Portal je Anfrage/feste Buchung'.($setting->channelIntakes() === [] ? ' (kein Portal)' : '');
}
/**
* What a request on this way is answered with (package 7): a binding offer that reserves, or an information.
*/
public static function answer(ProcessProfile $profile): string
{
return match ($profile->intake) {
IntakeKind::Inquiry => $profile->preReservation() ? 'Angebot mit Annahmelink, Zeitraum reserviert' : 'Unverbindliche Auskunft, „Buchung anfragen“, erneute Prüfung',
IntakeKind::Booking => 'keine – beim Portal bereits verbindlich',
IntakeKind::Internal => 'keine – eigene Belegung',
};
}
/**
* The stay settings of a property in one line (package 9).
*/
public static function stay(Property $property): string
{
$tasks = array_map(fn (array $task): string => $task['title'].' ('.match ($task['when']) {
'after_departure' => 'am Abreisetag',
'on_arrival' => 'am Anreisetag',
default => $task['days'].' Tag(e) vor Anreise',
}.($task['responsible'] ? ', '.$task['responsible'] : '').')', $property->stayTaskDefinitions());
return implode(' · ', [
'Anreisezeit erfragen: '.($property->asks_arrival_time ? 'ja' : 'nein'),
'Aufgaben je Aufenthalt: '.($tasks === [] ? 'keine eingestellt' : implode(', ', $tasks)),
'gebuchte Leistungen werden zu Aufgaben',
'Kurabgabe (A6): '.($property->tourist_tax_rate ? Money::format((int) $property->tourist_tax_rate).' je Person und Nacht' : 'kein Satz – keine Berechnung'),
]);
}
/**
* Recent cases to check.
*
* @return array<int, string>
*/
public function cases(): array
{
return Booking::query()->with('guest')->latest('id')->limit(60)->get()
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->caseType()->value])->all();
}
public function booking(): ?Booking
{
return $this->bookingId ? Booking::query()->find($this->bookingId) : null;
}
}
@@ -4,8 +4,10 @@
use App\Filament\Concerns\ListsCurrentProperty; use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource; use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use Filament\Actions\CreateAction; use App\Filament\Resources\Bookings\BookingResource;
use Filament\Actions\Action;
use Filament\Resources\Pages\ManageRecords; use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Icons\Heroicon;
class ManageBlockedPeriods extends ManageRecords class ManageBlockedPeriods extends ManageRecords
{ {
@@ -16,7 +18,8 @@ class ManageBlockedPeriods extends ManageRecords
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
return [ return [
CreateAction::make()->label('Zeitraum sperren')->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']), // New blocks are cases (A6) with their own page, history and portal tasks; this list keeps the old ones.
Action::make('createCase')->label('Zeitraum sperren')->icon(Heroicon::OutlinedPlus)->url(BookingResource::getUrl('create', ['kind' => 'block'])),
]; ];
} }
} }
@@ -0,0 +1,272 @@
<?php
namespace App\Filament\Resources\Bookings\Pages\Concerns;
use App\Actions\CloseStay;
use App\Actions\DecideBookingWish;
use App\Actions\PrepareStays;
use App\Actions\SendInformation;
use App\Actions\SendOffer;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Filament\Forms\DocumentCompositionFields;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\StayRequest;
use App\Process\CaseClosure;
use App\Process\CaseLog;
use App\Support\Money;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Icons\Heroicon;
use Throwable;
/**
* Case page actions of packages 7 and 9: the information "unter Vorbehalt" and the decision on a booking wish; arrival
* details, tasks of the stay (done, handed over, newly noted), closing the stay and settling the case commercially.
*
* @property Booking $record
*/
trait HandlesWishAndStay
{
private function sendInformationAction(): Action
{
return Action::make('sendInformation')
->label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking
&& ! $this->record->process()->preReservation() && $this->record->offer_version === 0 && ! $this->record->isHoldActive())
->modalHeading('Unverbindliche Auskunft an den Gast')
->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.')
->modalSubmitActionLabel('Senden')
->modalWidth('4xl')
->fillForm(fn (): array => [
'expected_version' => $this->record->information_version,
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'promo_code' => $this->record->promo_code,
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
'price_adjustment_label' => $this->record->price_adjustment_label,
'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
])
->schema([
Hidden::make('expected_version'),
...DocumentCompositionFields::make($this->record, DocumentKind::Information, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message']))),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
Section::make('Anpassen')->description('Zeitraum, Preis und wie lange der Gast die Buchung anfragen kann.')->collapsed()->schema([
Section::make('Termin')->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
]),
Section::make('Preis')->columns(3)->schema([
TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true),
TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true),
]),
DateTimePicker::make('valid_until')->label('Buchung anfragen bis')->helperText('Der Zeitraum bleibt bis dahin trotzdem frei buchbar für andere.')->seconds(false)->after('now')->required()->live(onBlur: true),
]),
])
->action(fn (array $data, SendInformation $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Auskunft gesendet'));
}
private function decideWishAction(): Action
{
return Action::make('decideWish')
->label('Buchungswunsch bestätigen oder absagen …')
->icon(Heroicon::OutlinedCheckCircle)
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved && $this->record->wish_at !== null)
->modalHeading('Buchungswunsch des Gastes')
->modalDescription(fn (): string => 'Angefragt am '.$this->record->wish_at?->format('d.m.Y, H:i').' Uhr. Bei „Bestätigen“ wird die Verfügbarkeit noch einmal geprüft; der Gast erhält die Buchungsbestätigung mit dem Mietvertrag.')
->modalSubmitActionLabel('Ausführen')
->schema(fn (): array => [
Text::make($this->wishCheckText()),
Radio::make('decision')->label('Entscheidung')->required()->default('confirm')->live()->options(array_filter([
'confirm' => 'Bestätigen zum Preis der Auskunft ('.Money::format((int) $this->record->total).')',
'confirm_today' => $this->todaysTotal() !== null && $this->todaysTotal() < (int) $this->record->total ? 'Bestätigen zum heutigen, niedrigeren Preis ('.Money::format((int) $this->todaysTotal()).')' : null,
'decline' => 'Absagen – der Gast erhält eine freundliche Absage',
])),
Textarea::make('reason')->label('Grund (nur für den Verlauf)')->rows(2)->visible(fn (Get $get): bool => $get('decision') === 'decline'),
])
->action(function (array $data, DecideBookingWish $decide): void {
$this->runWorkflow(fn () => match ($data['decision']) {
'decline' => $decide->decline($this->record, $data['reason'] ?? null),
default => $decide->confirm($this->record, $data['decision'] === 'confirm_today'),
}, $data['decision'] === 'decline' ? 'Abgesagt' : 'Buchung bestätigt');
});
}
private function arrivalDetailsAction(): Action
{
return Action::make('arrivalDetails')
->label('Anreisedaten eintragen')
->icon(Heroicon::OutlinedClock)
->visible(fn (): bool => $this->record->isBinding() && ! $this->record->isInternal() && $this->record->departure->isFuture())
->modalHeading('Anreisedaten')
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Was fehlt, steht in der Aufgabe; nur Bekanntes eintragen.')
->fillForm(fn (): array => ['arrival_time' => $this->record->arrival_time, 'email' => $this->record->guest?->email, 'phone' => $this->record->guest?->phone])
->schema([
TextInput::make('arrival_time')->label('Anreisezeit')->placeholder('z. B. gegen 16 Uhr')->maxLength(40),
TextInput::make('phone')->label('Telefon des Gastes')->tel()->maxLength(50)->visible(fn (): bool => $this->record->guest !== null),
TextInput::make('email')->label('E-Mail des Gastes')->email()->maxLength(255)->visible(fn (): bool => $this->record->guest !== null),
])
->action(function (array $data): void {
$this->record->update(['arrival_time' => filled($data['arrival_time'] ?? null) ? trim((string) $data['arrival_time']) : null]);
if ($this->record->guest !== null) {
$this->record->guest->update(array_filter(['phone' => $data['phone'] ?? null, 'email' => isset($data['email']) ? mb_strtolower(trim((string) $data['email'])) : null], fn ($value): bool => filled($value)));
}
app(PrepareStays::class)->handle();
$this->record->refresh();
Notification::make()->title('Gespeichert')->success()->send();
});
}
private function completeTaskAction(): Action
{
return Action::make('completeTask')
->label('Aufgabe erledigen …')
->icon(Heroicon::OutlinedCheck)
->visible(fn (): bool => $this->openTasks() !== [])
->modalHeading('Aufgabe erledigen')
->modalDescription('Erledigt oder an jemanden übergeben (z. B. Reinigung, Portal, Steuerberater). Die Notiz steht im Verlauf.')
->fillForm(fn (): array => ['task' => array_key_first($this->openTasks()), 'outcome' => 'done'])
->schema([
Select::make('task')->label('Aufgabe')->options(fn (): array => $this->openTasks())->required(),
Radio::make('outcome')->label('Ergebnis')->required()->options([
'done' => 'Erledigt',
'handed_over' => 'Übergeben – jemand anderes kümmert sich',
'dismissed' => 'Entfällt',
])->live(),
TextInput::make('handed_to')->label('Übergeben an')->maxLength(120)->required(fn (Get $get): bool => $get('outcome') === 'handed_over')->visible(fn (Get $get): bool => $get('outcome') === 'handed_over'),
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
])
->action(function (array $data): void {
$task = BookingTask::query()->where('booking_id', $this->record->id)->whereKey($data['task'])->where('status', BookingTaskStatus::Open)->first();
if ($task === null) {
Notification::make()->title('Diese Aufgabe ist schon erledigt.')->warning()->send();
return;
}
$note = trim(implode(' · ', array_filter([$data['outcome'] === 'handed_over' ? 'Übergeben an '.$data['handed_to'] : null, $data['note'] ?? null])));
if ($data['outcome'] === 'dismissed') {
$task->update(['status' => BookingTaskStatus::Dismissed, 'note' => $note !== '' ? $note : $task->note, 'completed_by' => CaseLog::actor(), 'completed_at' => now()]);
} else {
if ($data['outcome'] === 'handed_over') {
$task->responsible = (string) $data['handed_to'];
}
$task->complete(CaseLog::actor(), $note !== '' ? $note : null);
}
$this->record->refresh();
Notification::make()->title('Aufgabe vermerkt')->success()->send();
});
}
private function addTaskAction(): Action
{
return Action::make('addTask')
->label('Abweichung oder Aufgabe festhalten …')
->icon(Heroicon::OutlinedPencilSquare)
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying(), BookingStatus::Cancelled], true))
->modalHeading('Abweichung oder Aufgabe festhalten')
->modalDescription('Zum Aufenthalt (z. B. späte Anreise, defekte Kaffeemaschine, Schaden) – als Aufgabe am Vorgang, keine eigene Verwaltung.')
->schema([
Radio::make('kind')->label('Art')->required()->default(BookingTaskKind::Issue->value)->options([
BookingTaskKind::Issue->value => 'Abweichung oder Problem beim Aufenthalt – muss vor dem Abschluss des Aufenthalts geklärt sein',
BookingTaskKind::Service->value => 'Leistung vorbereiten (z. B. Kinderbett, zusätzliche Reinigung)',
BookingTaskKind::FollowUp->value => 'Folgeaufgabe nach dem Aufenthalt (z. B. Schaden abrechnen, Reparatur) – hält den Abschluss nicht auf',
]),
TextInput::make('title')->label('Was?')->required()->maxLength(200),
TextInput::make('responsible')->label('Wer kümmert sich? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120),
DatePicker::make('due_on')->label('Bis wann? (optional)'),
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
])
->action(function (array $data): void {
BookingTask::openOnce($this->record, BookingTaskKind::from($data['kind']), 'manual:'.now()->format('YmdHisv'), [
'title' => trim((string) $data['title']),
'responsible' => filled($data['responsible'] ?? null) ? trim((string) $data['responsible']) : null,
'due_on' => $data['due_on'] ?? null,
'note' => $data['note'] ?? null,
]);
$this->record->refresh();
Notification::make()->title('Festgehalten')->success()->send();
});
}
private function closeStayAction(): Action
{
return Action::make('closeStay')
->label(fn (): string => $this->record->isInternal() ? 'Abschließen …' : 'Aufenthalt abschließen …')
->icon(Heroicon::OutlinedFlag)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true) && ! $this->record->departure->isFuture())
->modalHeading('Aufenthalt abschließen')
->modalDescription(fn (): string => ($blockers = CaseClosure::stayBlockers($this->record))->isEmpty()
? 'Für den Aufenthalt ist nichts mehr offen. Offene Zahlungen oder Auszahlungen bleiben als kaufmännische Punkte am Vorgang.'
: 'Noch offen für den Aufenthalt: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', ').'. Mit dem Abschluss werden sie als erledigt bzw. übergeben vermerkt.')
->schema([Textarea::make('note')->label('Notiz (z. B. „Reinigung erledigt, Schlüssel zurück“)')->rows(2)->maxLength(500)])
->action(fn (array $data, CloseStay $close) => $this->runWorkflow(fn () => $close->byHand($this->record, CaseLog::actor(), $data['note'] ?? null), 'Aufenthalt abgeschlossen'));
}
private function settleAction(): Action
{
return Action::make('settle')
->label('Kaufmännisch abschließen …')
->icon(Heroicon::OutlinedBanknotes)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null)
->modalHeading('Kaufmännisch abschließen')
->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).')
->schema([Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500)])
->action(function (array $data): void {
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor());
$this->record->refresh();
Notification::make()->title('Kaufmännisch abgeschlossen')->success()->send();
});
}
/**
* Open tasks the landlord can settle on the page (not the ones with an action of their own).
*
* @return array<int, string>
*/
private function openTasks(): array
{
return BookingTask::query()->where('booking_id', $this->record->id)->where('status', BookingTaskStatus::Open)
->whereNotIn('kind', [BookingTaskKind::BookingWish, BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get()
->mapWithKeys(fn (BookingTask $task): array => [$task->id => $task->label().($task->due_on ? ' (fällig '.$task->due_on->format('d.m.Y').')' : '')])->all();
}
private function wishCheckText(): string
{
$wish = (array) ($this->record->wish ?? []);
$findings = (array) ($wish['findings'] ?? []);
$available = app(AvailabilityChecker::class)->isAvailable($this->record->property, $this->record->arrival, $this->record->departure, ignore: $this->record);
return ($available ? 'Der Zeitraum ist im Moment frei. ' : 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. ')
.($findings === [] ? 'Bei der Prüfung des Wunsches war alles in Ordnung.' : 'Bei der Prüfung des Wunsches fiel auf: '.implode(' ', $findings));
}
private function todaysTotal(): ?int
{
try {
return app(SendOffer::class)->quoteFor($this->record, new StayRequest($this->record->arrival, $this->record->departure, $this->record->guests, $this->record->extras ?? [], $this->record->promo_code), (int) $this->record->price_adjustment, (string) ($this->record->price_adjustment_label ?: 'Zuschlag'))->total();
} catch (Throwable) {
return null;
}
}
}
@@ -3,11 +3,12 @@
namespace App\Filament\Resources\Bookings\Pages; namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\ConfirmBooking; use App\Actions\ConfirmBooking;
use App\Actions\CreateInternalCase;
use App\Actions\CreateReservation; use App\Actions\CreateReservation;
use App\Actions\SendBookingDocuments; use App\Actions\SendBookingDocuments;
use App\Actions\TakeOverExternalBooking; use App\Actions\TakeOverExternalBooking;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource; use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Bookings\Schemas\BookingForm; use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Models\Booking; use App\Models\Booking;
@@ -37,9 +38,8 @@ class CreateBooking extends CreateRecord
*/ */
protected function handleRecordCreation(array $data): Model protected function handleRecordCreation(array $data): Model
{ {
if (($data['kind'] ?? null) === BookingForm::OWN_USE) { if (in_array($data['kind'] ?? null, [BookingForm::OWN_USE, BookingForm::BLOCK], true)) {
$this->redirect(BlockedPeriodResource::getUrl()); return $this->createInternal($data);
$this->halt();
} }
try { try {
@@ -88,6 +88,58 @@ protected function handleRecordCreation(array $data): Model
return $booking; return $booking;
} }
/**
* Pre-filled from the calendar or the block list (?kind=block&von=…&bis=…&wohnung=…).
*/
protected function afterFill(): void
{
$kind = request()->query('kind');
if (in_array($kind, [BookingForm::INQUIRY, BookingForm::EXTERNAL, BookingForm::OWN_USE, BookingForm::BLOCK], true)) {
$this->data['kind'] = $kind;
}
foreach (['von' => 'arrival', 'bis' => 'departure'] as $parameter => $field) {
$value = request()->query($parameter);
if (is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1) {
$this->data[$field] = $value;
}
}
if (is_numeric(request()->query('wohnung')) && Property::query()->whereKey((int) request()->query('wohnung'))->exists()) {
$this->data['property_id'] = (int) request()->query('wohnung');
}
}
/**
* Own use, a private stay or a block as a case (A6).
*
* @param array<string, mixed> $data
*/
private function createInternal(array $data): Model
{
$kind = $data['kind'] === BookingForm::BLOCK ? InternalKind::Block : InternalKind::from((string) ($data['internal_kind'] ?? InternalKind::OwnUse->value));
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
if (filled($item['extra_id'] ?? null)) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) ($item['quantity'] ?? 1));
}
}
try {
return app(CreateInternalCase::class)->handle(Property::query()->findOrFail($data['property_id']), $kind, CarbonImmutable::parse($data['arrival']), CarbonImmutable::parse($data['departure']), [
'occasion' => $data['occasion'] ?? null,
'guest' => ['first_name' => $data['stay_first_name'] ?? null, 'last_name' => $data['stay_last_name'] ?? null, 'email' => $data['stay_email'] ?? null, 'phone' => $data['stay_phone'] ?? null],
'guests' => $data['guests'] ?? null,
'extras' => $extras,
'rent' => (int) ($data['rent'] ?? 0),
'tourist_tax_persons' => filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null,
'tourist_tax_note' => $data['tourist_tax_note'] ?? null,
'notes' => $data['internal_notes'] ?? null,
]);
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
$this->halt();
}
}
protected function getRedirectUrl(): string protected function getRedirectUrl(): string
{ {
/** @var Booking $record */ /** @var Booking $record */
@@ -3,18 +3,27 @@
namespace App\Filament\Resources\Bookings\Pages; namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\CancelBooking; use App\Actions\CancelBooking;
use App\Actions\ChangeBooking;
use App\Actions\ConfirmBooking; use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking; use App\Actions\DeclineBooking;
use App\Actions\EndInternalCase;
use App\Actions\ProvideGuestContact; use App\Actions\ProvideGuestContact;
use App\Actions\RecordPortalAmounts;
use App\Actions\SendBookingDocuments; use App\Actions\SendBookingDocuments;
use App\Actions\SendOffer; use App\Actions\SendOffer;
use App\Actions\SetBookingStatus; use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms; use App\Documents\OfferTerms;
use App\Documents\RentalContract; use App\Documents\RentalContract;
use App\Enums\AdminMode; use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\DocumentKind; use App\Enums\DocumentKind;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
use App\Enums\Responsibility; use App\Enums\Responsibility;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
@@ -22,19 +31,24 @@
use App\Filament\Forms\Components\EuroInput; use App\Filament\Forms\Components\EuroInput;
use App\Filament\Forms\DocumentCompositionFields; use App\Filament\Forms\DocumentCompositionFields;
use App\Filament\Resources\Bookings\BookingResource; use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Bookings\Pages\Concerns\HandlesWishAndStay;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingChange;
use App\Models\BookingTask;
use App\Models\ContractAnnex; use App\Models\ContractAnnex;
use App\Models\ContractTemplate; use App\Models\ContractTemplate;
use App\Models\Extra; use App\Models\Extra;
use App\Models\User; use App\Models\User;
use App\Pricing\PortalPrice; use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException; use App\Pricing\QuoteException;
use App\Process\CaseActivities; use App\Process\CaseActivities;
use App\Process\CaseAutomation; use App\Process\CaseAutomation;
use App\Process\CaseLog; use App\Process\CaseLog;
use App\Support\Money; use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Actions\ActionGroup; use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden; use Filament\Forms\Components\Hidden;
@@ -50,6 +64,7 @@
use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set; use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Components\View;
use Filament\Support\Icons\Heroicon; use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\Support\Htmlable; use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@@ -65,6 +80,8 @@
*/ */
class ViewBooking extends ViewRecord class ViewBooking extends ViewRecord
{ {
use HandlesWishAndStay;
protected static string $resource = BookingResource::class; protected static string $resource = BookingResource::class;
/** Actions for the expert view only. */ /** Actions for the expert view only. */
@@ -83,14 +100,24 @@ public function getSubheading(): string|Htmlable|null
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$actions = collect([ $actions = collect([
$this->sendInformationAction(),
$this->decideWishAction(),
$this->sendOfferAction(), $this->sendOfferAction(),
$this->provideContactAction(), $this->provideContactAction(),
$this->arrivalDetailsAction(),
$this->completeTaskAction(),
$this->addTaskAction(),
$this->closeStayAction(),
$this->settleAction(),
$this->requestContactAction(), $this->requestContactAction(),
AssignGuestAction::make(), AssignGuestAction::make(),
$this->confirmAction(), $this->confirmAction(),
$this->sendDocumentsAction(), $this->sendDocumentsAction(),
$this->resendConfirmationAction(), $this->resendConfirmationAction(),
$this->portalPriceAction(), $this->portalPriceAction(),
$this->changeAction(),
$this->confirmPortalCancellationAction(),
$this->withdrawChangeAction(),
$this->extendHoldAction(), $this->extendHoldAction(),
$this->servicesAction(), $this->servicesAction(),
$this->offerPdfAction(), $this->offerPdfAction(),
@@ -126,7 +153,11 @@ private function isExpert(): bool
private function sendOfferAction(): Action private function sendOfferAction(): Action
{ {
return Action::make('sendOffer') return Action::make('sendOffer')
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot prüfen und senden') ->label(fn (): string => match (true) {
$this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden',
! $this->record->process()->preReservation() => 'Stattdessen verbindliches Angebot mit Reservierung senden',
default => 'Angebot prüfen und senden',
})
->icon(Heroicon::OutlinedPaperAirplane) ->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking) ->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') ->modalHeading('Angebot an den Gast')
@@ -191,7 +222,8 @@ private function sendDocumentsAction(): Action
return Action::make('sendDocuments') return Action::make('sendDocuments')
->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden') ->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane) ->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) ->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null
&& ($this->record->process()->documents() === Responsibility::Landlord || ($this->record->isInternal() && $this->record->internal_kind !== InternalKind::Block && filled($this->record->guest?->email))))
->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel()) ->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel())
->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.') ->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.')
->modalSubmitActionLabel('Senden') ->modalSubmitActionLabel('Senden')
@@ -239,7 +271,7 @@ private function provideContactAction(): Action
return Action::make('provideContact') return Action::make('provideContact')
->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen') ->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen')
->icon(Heroicon::OutlinedUserPlus) ->icon(Heroicon::OutlinedUserPlus)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true)) ->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Kontaktdaten des Gastes') ->modalHeading('Kontaktdaten des Gastes')
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.') ->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.')
->modalWidth('3xl') ->modalWidth('3xl')
@@ -286,7 +318,7 @@ private function requestContactAction(): Action
return Action::make('requestContact') return Action::make('requestContact')
->label('Gast um Kontaktdaten bitten') ->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis) ->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->visible(fn (): bool => blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true)) ->visible(fn (): bool => ! $this->record->isInternal() && blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Gast um Kontaktdaten bitten') ->modalHeading('Gast um Kontaktdaten bitten')
->modalDescription('Den Text im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). „Als angefragt vermerken“ hält fest, dass die Daten erfragt sind.') ->modalDescription('Den Text im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). „Als angefragt vermerken“ hält fest, dass die Daten erfragt sind.')
->modalSubmitActionLabel('Als angefragt vermerken') ->modalSubmitActionLabel('Als angefragt vermerken')
@@ -361,28 +393,204 @@ private function resendConfirmationAction(): Action
}); });
} }
/**
* What the portal shows about the booking (package 8): the guest's total as the agreed price and – optional, folded
* away – its positions, commission, announced payouts, instalments and what the guest paid to the portal.
*/
private function portalPriceAction(): Action private function portalPriceAction(): Action
{ {
return Action::make('portalPrice') return Action::make('portalPrice')
->label('Gesamtpreis laut Portal eintragen') ->label('Preis laut Portal eintragen')
->icon(Heroicon::OutlinedCurrencyEuro) ->icon(Heroicon::OutlinedCurrencyEuro)
->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true)) ->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true))
->modalDescription('Der Betrag, den der Gast beim Portal gebucht hat (Gesamtpreis). Er wird so übernommen und nicht in eigene Positionen zerlegt.') ->modalHeading(fn (): string => 'Beträge laut '.($this->record->processChannel()?->name ?? 'Portal'))
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests]) ->modalDescription('Der Gesamtpreis, den der Gast beim Portal gebucht hat, wird so übernommen und nicht neu berechnet. Einzelheiten nur eintragen, wenn das Portal sie zeigt – nichts schätzen. Abweichende Angaben (z. B. zwei verschiedene Auszahlungsbeträge) einfach beide eintragen.')
->modalWidth('4xl')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests, 'stated_on' => today()->toDateString(), 'amounts' => [], 'paid' => []])
->schema([ ->schema([
EuroInput::make('portal_total')->label('Gesamtpreis laut Portal')->required(), Section::make()->columns(3)->schema([
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1), EuroInput::make('portal_total')->label('Gesamtpreis des Gastes laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
DatePicker::make('stated_on')->label('Stand der Angaben')->required(),
]),
Section::make('Einzelheiten laut Portal (optional)')->collapsed()->schema([
Repeater::make('amounts')->label('Positionen und Angaben')->addActionLabel('Angabe hinzufügen')->columns(4)->defaultItems(0)->schema([
Select::make('kind')->label('Art')->options(AmountKind::class)->required()->columnSpan(2),
TextInput::make('label')->label('Bezeichnung laut Portal')->placeholder('z. B. Gebühren und Steuern')->maxLength(150),
EuroInput::make('amount')->label('Betrag')->minValue(null)->required(),
DatePicker::make('due_on')->label('fällig am (bei Raten)'),
TextInput::make('note')->label('Notiz')->maxLength(500)->columnSpan(3),
]),
Repeater::make('paid')->label('Vom Gast laut Portal bereits bezahlt')->addActionLabel('Zahlung laut Portal hinzufügen')->columns(2)->defaultItems(0)->schema([
EuroInput::make('amount')->label('Betrag')->required(),
DatePicker::make('paid_on')->label('bezahlt am')->required(),
]),
]),
]) ])
->action(function (array $data, PortalPrice $price): void { ->action(function (array $data, RecordPortalAmounts $amounts): void {
$guests = filled($data['guests'] ?? null) ? (int) $data['guests'] : $this->record->guests; if (filled($data['guests'] ?? null)) {
$this->record->update(['guests' => $guests, ...$price->columns($this->record->property, $this->record->arrival, $this->record->departure, $guests, (int) $data['portal_total'], $this->record->processChannel()?->name)]); $this->record->update(['guests' => (int) $data['guests']]);
CaseLog::record($this->record, 'price', 'Gesamtpreis laut Portal eingetragen: '.Money::format((int) $data['portal_total'])); }
$blockers = app(CaseAutomation::class)->advance($this->record->fresh()); $amounts->handle(
$this->record->fresh(),
(int) $data['portal_total'],
array_map(fn (array $row): array => [...$row, 'amount' => (int) $row['amount']], array_values((array) ($data['amounts'] ?? []))),
array_map(fn (array $row): array => ['amount' => (int) $row['amount'], 'paid_on' => (string) $row['paid_on']], array_values((array) ($data['paid'] ?? []))),
$this->record->processChannel()?->name ?? 'Portal',
CarbonImmutable::parse($data['stated_on']),
auth()->user()?->name,
);
$this->record->refresh(); $this->record->refresh();
Notification::make()->title('Preis gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send(); $blockers = app(CaseAutomation::class)->documentBlockers($this->record);
Notification::make()->title('Beträge gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
}); });
} }
/**
* "Ändern" of a booking or internal case (package 5): dates, guests, services and price with the consequences shown
* before saving; either recorded as already agreed with the guest, or proposed to the guest for consent.
*/
private function changeAction(): Action
{
$own = fn (): bool => ! $this->record->isInternal() && ! $this->record->caseType()->isExternallyBinding();
return Action::make('change')
->label(fn (): string => $this->record->isInternal() ? 'Ändern oder verlängern …' : 'Buchung ändern …')
->icon(Heroicon::OutlinedPencil)
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->portal_cancellation_requested_at === null)
->modalHeading(fn (): string => $this->record->isInternal() ? 'Zeitraum oder Angaben ändern' : 'Buchung ändern')
->modalDescription('Tragen Sie ein, was sich ändert. Unten sehen Sie vor dem Speichern, was daraus folgt.')
->modalSubmitActionLabel('Speichern')
->modalWidth('4xl')
->fillForm(fn (): array => [
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all(),
'rent' => $this->record->isInternal() ? PrivateStayPrice::rentOf($this->record->quote) : null,
'tourist_tax_persons' => $this->record->tourist_tax_persons,
'way' => 'agreed',
'requested_by' => $this->record->caseType()->isExternallyBinding() ? 'portal' : 'guest',
'basis' => $this->record->caseType()->isExternallyBinding() ? ChangeBasis::Portal->value : ChangeBasis::Phone->value,
'agreed_at' => now()->format('Y-m-d H:i'),
'effective_on' => today()->toDateString(),
'send_confirmation' => false,
])
->schema(fn (): array => [
Section::make()->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise / Beginn')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise / Ende')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->live(onBlur: true)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block),
]),
Repeater::make('items')->label('Zusatzleistungen')->columns(2)->defaultItems(0)->addActionLabel('Leistung hinzufügen')->live()
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! $this->record->caseType()->isExternallyBinding())
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->where('property_id', $this->record->property_id)->orderBy('name')->pluck('name', 'id')->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
]),
Section::make('Preis')->columns(2)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block)->schema([
EuroInput::make('portal_total')->label('Neuer Gesamtpreis laut Portal')->helperText('Leer lassen, wenn das Portal den Preis nicht geändert hat.')->live(onBlur: true)
->visible(fn (): bool => $this->record->caseType()->isExternallyBinding()),
EuroInput::make('agreed_total')->label('Vereinbarter Gesamtpreis (optional)')->helperText('Leer lassen: Der Preis wird aus Ihren Preisen neu berechnet.')->live(onBlur: true)
->visible($own),
EuroInput::make('rent')->label('Vereinbarte Miete')->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
TextInput::make('tourist_tax_persons')->label('Kurabgabe: Personen')->integer()->minValue(0)->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
]),
View::make('filament.change-preview')->viewData(fn (Get $get): array => ['preview' => app(ChangeBooking::class)->preview($this->record, $this->changeData(self::formState($get, ['arrival', 'departure', 'guests', 'items', 'portal_total', 'agreed_total', 'rent', 'tourist_tax_persons'])))]),
Section::make('Grundlage')->columns(2)->visible(fn (): bool => ! $this->record->isInternal())->schema([
Radio::make('way')->label('Wie kommt die Änderung zustande?')->columnSpanFull()->live()->required()->options(fn (): array => array_filter([
'agreed' => 'Mit dem Gast bereits vereinbart – jetzt eintragen',
'propose' => $own() && filled($this->record->guest?->email) ? 'Dem Gast vorschlagen – wird erst mit seiner Zustimmung wirksam' : null,
])),
Select::make('requested_by')->label('Wer möchte die Änderung?')->options(BookingChange::REQUESTERS)->required(),
Select::make('basis')->label('Wie vereinbart?')->options(collect(ChangeBasis::cases())->reject(fn (ChangeBasis $basis): bool => in_array($basis, [ChangeBasis::GuestLink, ChangeBasis::NotNeeded], true))->mapWithKeys(fn (ChangeBasis $basis): array => [$basis->value => $basis->getLabel()])->all())
->visible(fn (Get $get): bool => $get('way') === 'agreed')->required(fn (Get $get): bool => $get('way') === 'agreed'),
DateTimePicker::make('agreed_at')->label('Vereinbart am')->seconds(false)->visible(fn (Get $get): bool => $get('way') === 'agreed'),
DatePicker::make('effective_on')->label('Wirksam ab'),
Toggle::make('send_confirmation')->label('Bestätigung der Änderung an den Gast senden')->visible(fn (Get $get): bool => $get('way') === 'agreed' && filled($this->record->guest?->email)),
]),
Textarea::make('reason')->label('Grund')->required()->rows(2),
])
->action(function (array $data, ChangeBooking $changes): void {
$meta = [
'requested_by' => $this->record->isInternal() ? 'landlord' : ($data['requested_by'] ?? 'landlord'),
'reason' => (string) $data['reason'],
'basis' => $this->record->isInternal() ? ChangeBasis::NotNeeded : ChangeBasis::from((string) ($data['basis'] ?? ChangeBasis::Phone->value)),
'agreed_at' => $data['agreed_at'] ?? null,
'effective_on' => $data['effective_on'] ?? null,
'send_confirmation' => (bool) ($data['send_confirmation'] ?? false),
];
$this->runWorkflow(fn () => ($data['way'] ?? 'agreed') === 'propose' && ! $this->record->isInternal()
? $changes->propose($this->record, $this->changeData($data), $meta, auth()->user()?->name)
: $changes->apply($this->record, $this->changeData($data), $meta, auth()->user()?->name), ($data['way'] ?? 'agreed') === 'propose' ? 'Vorschlag an den Gast gesendet' : 'Änderung gespeichert');
});
}
/**
* A booking binding on a portal is only cancelled here once the cancellation is effective on the portal.
*/
private function confirmPortalCancellationAction(): Action
{
$reported = fn (): bool => BookingTask::query()->where('booking_id', $this->record->id)->where('kind', BookingTaskKind::PortalCancellationReported)->where('status', BookingTaskStatus::Open)->exists();
return Action::make('confirmPortalCancellation')
->label(fn (): string => $reported() ? 'Stornierung übernehmen …' : 'Stornierung bestätigen …')
->icon(Heroicon::OutlinedCheckBadge)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->caseType()->isExternallyBinding()
&& ($this->record->portal_cancellation_requested_at !== null || $reported()))
->modalHeading('Ist die Stornierung im Portal wirksam?')
->modalDescription(fn (): string => 'Erst jetzt wird der Vorgang storniert und der Zeitraum frei. Bitte vorher im Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ nachsehen. Bleibt die Buchung im Portal bestehen, die Aufgabe einfach im Reiter „Aufgaben“ erledigen.')
->modalSubmitActionLabel('Storniert – übernehmen')
->fillForm(fn (): array => ['initiated_by' => $reported() ? 'portal' : 'landlord'])
->schema([
Radio::make('initiated_by')->label('Wer hat storniert?')->options(CancelBooking::INITIATORS)->required(),
Textarea::make('reason')->label('Grund / Hinweis')->rows(2),
Checkbox::make('effective')->label('Die Stornierung ist im Portal wirksam (geprüft).')->accepted(),
])
->action(fn (array $data, CancelBooking $cancel) => $this->runWorkflow(fn () => $cancel->confirmOnPortal($this->record, (string) auth()->user()?->name, $data['initiated_by'], $data['reason'] ?? null), 'Buchung storniert'));
}
private function withdrawChangeAction(): Action
{
return Action::make('withdrawChange')
->label('Änderungsvorschlag zurückziehen')
->icon(Heroicon::OutlinedArrowUturnLeft)
->visible(fn (): bool => $this->record->changes()->where('status', ChangeStatus::Proposed)->exists())
->requiresConfirmation()
->action(function (ChangeBooking $changes): void {
$changes->withdraw($this->record->changes()->where('status', ChangeStatus::Proposed)->firstOrFail(), auth()->user()?->name);
Notification::make()->title('Vorschlag zurückgezogen')->success()->send();
});
}
/**
* Form data of the change dialog as changes for {@see ChangeBooking}.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function changeData(array $data): array
{
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
if (filled($item['extra_id'] ?? null)) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) ($item['quantity'] ?? 1));
}
}
return array_filter([
'arrival' => $data['arrival'] ?? null,
'departure' => $data['departure'] ?? null,
'guests' => filled($data['guests'] ?? null) ? (int) $data['guests'] : null,
'extras' => $this->record->internal_kind === InternalKind::Block || $this->record->caseType()->isExternallyBinding() ? null : $extras,
'portal_total' => filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
'agreed_total' => filled($data['agreed_total'] ?? null) ? (int) $data['agreed_total'] : null,
'rent' => $this->record->isInternal() && filled($data['rent'] ?? null) ? (int) $data['rent'] : null,
'tourist_tax_persons' => $this->record->isInternal() && filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null,
], fn ($value): bool => $value !== null);
}
private function extendHoldAction(): Action private function extendHoldAction(): Action
{ {
return Action::make('extendHold') return Action::make('extendHold')
@@ -402,7 +610,7 @@ private function servicesAction(): Action
return Action::make('services') return Action::make('services')
->label('Zusatzleistungen erfassen') ->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle) ->icon(Heroicon::OutlinedPlusCircle)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) ->visible(fn (): bool => ! $this->record->isInternal() && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (z. B. aus einer Portalbuchung). Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis ändert sich dadurch nicht.') ->modalDescription('Gebuchte Zusatzleistungen (z. B. aus einer Portalbuchung). Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis ändert sich dadurch nicht.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()]) ->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([ ->schema([
@@ -525,7 +733,8 @@ private function setStatusAction(): Action
*/ */
private function automationAction(): ?Action private function automationAction(): ?Action
{ {
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) { // Own use, private stays and blocks have nothing that could run by itself.
if ($this->record->isInternal() || in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null; return null;
} }
@@ -554,11 +763,28 @@ private function automationAction(): ?Action
*/ */
private function endAction(): ?Action private function endAction(): ?Action
{ {
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) { if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)
|| $this->record->portal_cancellation_requested_at !== null) {
return null; return null;
} }
if ($this->record->isInternal()) {
$label = EndInternalCase::label($this->record);
return Action::make('end')
->label($this->record->internal_kind === InternalKind::Block ? 'Sperre aufheben …' : 'Aufenthalt absagen …')
->icon(Heroicon::OutlinedStopCircle)
->color('danger')
->outlined()
->modalHeading($label)
->modalDescription('Keine Stornierung: Es entstehen keine Kosten und keine Mails. Der Zeitraum wird frei, die Portale werden wieder freigegeben.')
->modalSubmitActionLabel($this->record->internal_kind === InternalKind::Block ? 'Aufheben' : 'Absagen')
->schema([Textarea::make('reason')->label('Grund')->required()->rows(2)])
->action(fn (array $data, EndInternalCase $end) => $this->runWorkflow(fn () => $end->handle($this->record, trim((string) $data['reason']), auth()->user()?->name), $label));
}
$binding = $this->record->isBinding(); $binding = $this->record->isBinding();
$external = $binding && $this->record->caseType()->isExternallyBinding();
$hasEmail = filled($this->record->guest?->email); $hasEmail = filled($this->record->guest?->email);
return Action::make('end') return Action::make('end')
@@ -567,22 +793,25 @@ private function endAction(): ?Action
->color('danger') ->color('danger')
->outlined() ->outlined()
->modalHeading($binding ? 'Gebuchten Vorgang stornieren' : 'Vorgang ohne Buchung beenden') ->modalHeading($binding ? 'Gebuchten Vorgang stornieren' : 'Vorgang ohne Buchung beenden')
->modalDescription($binding ->modalDescription(match (true) {
? 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel bleiben als Aufgabe offen.'.($this->record->caseType()->isExternallyBinding() ? ' Gebucht wurde beim Portal – dafür entsteht zusätzlich die Aufgabe, die Stornierung dort zu veranlassen bzw. zu prüfen.' : '') $external => 'Gebucht wurde beim Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ – storniert wird dort. Hier entsteht die Aufgabe, die Stornierung im Portal zu veranlassen; der Vorgang bleibt gebucht, bis Sie bestätigen, dass sie dort wirksam ist. Nichts wird still gelöscht.',
: 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.') $binding => 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel und eine mögliche Erstattung bleiben als Aufgaben offen.',
->modalSubmitActionLabel($binding ? 'Stornieren' : 'Beenden') default => 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.',
})
->modalSubmitActionLabel($external ? 'Stornierung veranlassen' : ($binding ? 'Stornieren' : 'Beenden'))
->schema(array_values(array_filter([ ->schema(array_values(array_filter([
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options(['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null, $binding ? Radio::make('initiated_by')->label('Wer storniert?')->options($external ? CancelBooking::INITIATORS : ['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
Textarea::make('reason')->label('Grund')->required()->rows(2), Textarea::make('reason')->label('Grund')->required()->rows(2),
Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail), $external ? null : Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null, $binding && ! $external ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
]))) ])))
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $hasEmail): void { ->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $external, $hasEmail): void {
$notify = $hasEmail && (bool) ($data['notify'] ?? false); $notify = ! $external && $hasEmail && (bool) ($data['notify'] ?? false);
$reason = trim((string) $data['reason']);
try { try {
$informed = CaseLog::context(fn () => $binding $informed = CaseLog::context(fn () => $binding
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by']) ? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'], $reason)
: $decline->handle($this->record, $notify), reason: trim((string) $data['reason'])); : $decline->handle($this->record, $notify), reason: $reason);
} catch (ReservationException $exception) { } catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
@@ -590,7 +819,11 @@ private function endAction(): ?Action
} }
$this->record->refresh(); $this->record->refresh();
$notification = Notification::make()->title($binding ? 'Buchung storniert' : 'Vorgang beendet'); $notification = Notification::make()->title(match (true) {
$external => 'Stornierung im Portal veranlassen',
$binding => 'Buchung storniert',
default => 'Vorgang beendet',
});
($informed === false ? $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte selbst informieren.') : $notification->success())->send(); ($informed === false ? $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte selbst informieren.') : $notification->success())->send();
}); });
} }
@@ -3,15 +3,19 @@
namespace App\Filament\Resources\Bookings\RelationManagers; namespace App\Filament\Resources\Bookings\RelationManagers;
use App\Actions\RecordPayment; use App\Actions\RecordPayment;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod; use App\Enums\PaymentMethod;
use App\Enums\Responsibility;
use App\Filament\Forms\Components\EuroInput; use App\Filament\Forms\Components\EuroInput;
use App\Models\Booking; use App\Models\Booking;
use App\Models\Payment; use App\Models\Payment;
use App\Pricing\CaseMoney;
use App\Support\Money; use App\Support\Money;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Actions\DeleteAction; use Filament\Actions\DeleteAction;
use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
@@ -38,11 +42,13 @@ public function table(Table $table): Table
{ {
return $table return $table
->recordTitleAttribute('amount') ->recordTitleAttribute('amount')
->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount())) ->description(fn (): string => 'Vom Gast bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' (davon an uns '.Money::format($this->ownerRecord->paidToUs()).', laut Portal ans Portal '.Money::format($this->ownerRecord->paidViaPortal()).') · Auszahlungen vom Portal: '.Money::format($this->ownerRecord->payoutsReceived()).' · offen bei uns: '.Money::format(CaseMoney::of($this->ownerRecord)->openForUs()))
->columns([ ->columns([
TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'), TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'),
TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'), TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'),
TextColumn::make('method')->label('Art'), TextColumn::make('kind')->label('Was')->badge()->state(fn (Payment $record): PaymentKind => $record->kind ?? PaymentKind::Guest),
TextColumn::make('method')->label('Zahlweg'),
TextColumn::make('source')->label('Quelle')->placeholder('–')->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('note')->label('Notiz')->placeholder('–'), TextColumn::make('note')->label('Notiz')->placeholder('–'),
TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'), TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'),
]) ])
@@ -54,9 +60,11 @@ public function table(Table $table): Table
'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''), 'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''),
'paid_on' => today(), 'paid_on' => today(),
'method' => PaymentMethod::Transfer, 'method' => PaymentMethod::Transfer,
'kind' => $this->ownerRecord->process()->payments() === Responsibility::Portal ? PaymentKind::PortalPayout->value : PaymentKind::Guest->value,
]) ])
->schema([ ->schema([
EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(), Radio::make('kind')->label('Was ist passiert?')->options(PaymentKind::class)->required(),
EuroInput::make('amount')->label('Betrag')->helperText('Immer den Betrag ohne Vorzeichen; eine Erstattung wird automatisch abgezogen.')->required(),
DatePicker::make('paid_on')->label('Zahlungseingang')->required(), DatePicker::make('paid_on')->label('Zahlungseingang')->required(),
Select::make('method')->label('Art')->options(PaymentMethod::class)->required(), Select::make('method')->label('Art')->options(PaymentMethod::class)->required(),
TextInput::make('note')->label('Notiz')->maxLength(255), TextInput::make('note')->label('Notiz')->maxLength(255),
@@ -69,6 +77,8 @@ public function table(Table $table): Table
$data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']), $data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']),
$data['note'] ?: null, $data['note'] ?: null,
auth()->user()?->name, auth()->user()?->name,
$data['kind'] instanceof PaymentKind ? $data['kind'] : PaymentKind::from($data['kind']),
in_array($data['kind'] instanceof PaymentKind ? $data['kind']->value : $data['kind'], [PaymentKind::GuestViaPortal->value, PaymentKind::PortalPayout->value], true) ? ($this->ownerRecord->processChannel()?->name ?? 'Portal') : null,
); );
Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send(); Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send();
@@ -2,22 +2,23 @@
namespace App\Filament\Resources\Bookings\Schemas; namespace App\Filament\Resources\Bookings\Schemas;
use App\Enums\InternalKind;
use App\Filament\Forms\Components\EuroInput; use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Models\Channel; use App\Models\Channel;
use App\Models\Extra;
use App\Models\Property; use App\Models\Property;
use App\Support\CurrentProperty; use App\Support\CurrentProperty;
use App\Support\Money;
use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Radio; use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea; use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema; use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/** /**
* "Neu": one entry for everything that arrives outside the website. The first question is what it is – a request, * "Neu": one entry for everything that arrives outside the website. The first question is what it is – a request,
@@ -32,10 +33,14 @@ class BookingForm
public const OWN_USE = 'own_use'; public const OWN_USE = 'own_use';
public const BLOCK = 'block';
public static function configure(Schema $schema): Schema public static function configure(Schema $schema): Schema
{ {
$is = fn (string $kind): \Closure => fn (Get $get): bool => $get('kind') === $kind; $is = fn (string $kind): \Closure => fn (Get $get): bool => $get('kind') === $kind;
$isCase = fn (Get $get): bool => in_array($get('kind'), [self::INQUIRY, self::EXTERNAL], true); $isCase = fn (Get $get): bool => in_array($get('kind'), [self::INQUIRY, self::EXTERNAL], true);
$isInternal = fn (Get $get): bool => in_array($get('kind'), [self::OWN_USE, self::BLOCK], true);
$hasGuests = fn (Get $get): bool => $get('kind') === self::OWN_USE && $get('internal_kind') === InternalKind::PrivateStay->value;
return $schema return $schema
->components([ ->components([
@@ -46,17 +51,25 @@ public static function configure(Schema $schema): Schema
->options([ ->options([
self::INQUIRY => 'Eine Anfrage – per Telefon, E-Mail oder Nachricht über ein Portal', self::INQUIRY => 'Eine Anfrage – per Telefon, E-Mail oder Nachricht über ein Portal',
self::EXTERNAL => 'Eine Buchung, die bei einem Portal schon fest gebucht ist', self::EXTERNAL => 'Eine Buchung, die bei einem Portal schon fest gebucht ist',
self::OWN_USE => 'Eigene Nutzung oder eine Sperre (z. B. Wartung)', self::OWN_USE => 'Eigene Nutzung oder Besuch von Familie und Freunden',
self::BLOCK => 'Eine Sperre ohne Gäste (z. B. Wartung, Renovierung)',
]) ])
->default(self::INQUIRY) ->default(self::INQUIRY)
->required() ->required()
->live(), ->live(),
Text::make(new HtmlString('Eigene Nutzung und Sperren tragen Sie bis auf Weiteres unter <a class="underline" href="'.e(BlockedPeriodResource::getUrl()).'">Sperrzeiten</a> ein.')) Radio::make('internal_kind')
->visible($is(self::OWN_USE)), ->label('Wer wohnt in der Wohnung?')
->options([InternalKind::OwnUse->value => 'Wir selbst (eigene Nutzung)', InternalKind::PrivateStay->value => 'Familie oder Freunde (private Überlassung, ohne Mietvertrag)'])
->default(InternalKind::OwnUse->value)
->visible($is(self::OWN_USE))
->live(),
TextInput::make('occasion')->label(fn (Get $get): string => $get('kind') === self::BLOCK ? 'Grund der Sperre' : 'Anlass')
->placeholder(fn (Get $get): string => $get('kind') === self::BLOCK ? 'z. B. Malerarbeiten im Bad' : 'z. B. Besuch von Tochter Anna')
->maxLength(255)->required($is(self::BLOCK))->visible($isInternal),
]), ]),
Section::make('Zeitraum') Section::make('Zeitraum')
->columns(2) ->columns(2)
->visible($isCase) ->visible(fn (Get $get): bool => $isCase($get) || $isInternal($get))
->schema([ ->schema([
Select::make('property_id') Select::make('property_id')
->label('Wohnung') ->label('Wohnung')
@@ -69,9 +82,36 @@ public static function configure(Schema $schema): Schema
->integer() ->integer()
->minValue(1) ->minValue(1)
->helperText(fn (Get $get): ?string => $get('kind') === self::EXTERNAL ? 'Leer lassen, wenn nicht bekannt.' : null) ->helperText(fn (Get $get): ?string => $get('kind') === self::EXTERNAL ? 'Leer lassen, wenn nicht bekannt.' : null)
->visible(fn (Get $get): bool => $get('kind') !== self::BLOCK)
->live(onBlur: true)
->required($is(self::INQUIRY)), ->required($is(self::INQUIRY)),
DatePicker::make('arrival')->label('Anreise')->required(), DatePicker::make('arrival')->label(fn (Get $get): string => $isInternal($get) ? 'Beginn' : 'Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required(), DatePicker::make('departure')->label(fn (Get $get): string => $isInternal($get) ? 'Ende (erster freier Tag)' : 'Abreise')->after('arrival')->required(),
]),
Section::make('Gäste')
->description('Nur eintragen, was Sie brauchen – z. B. für eine Aufenthaltsbestätigung.')
->columns(2)
->visible($hasGuests)
->schema([
TextInput::make('stay_first_name')->label('Vorname')->maxLength(255),
TextInput::make('stay_last_name')->label('Nachname')->maxLength(255),
TextInput::make('stay_email')->label('E-Mail (für eine Bestätigung)')->email()->maxLength(255),
TextInput::make('stay_phone')->label('Telefon')->tel()->maxLength(50),
]),
Section::make('Leistungen und Kosten (optional)')
->description('Miete ist bei Familie meist 0 €. Zahlungen lassen sich später erfassen; es gibt keine Zahlungserinnerungen.')
->columns(2)
->visible($is(self::OWN_USE))
->collapsed(fn (Get $get): bool => $get('internal_kind') !== InternalKind::PrivateStay->value)
->schema([
EuroInput::make('rent')->label('Vereinbarte Miete')->default(0),
TextInput::make('tourist_tax_persons')->label('Kurabgabe: Personen')->integer()->minValue(0)
->helperText(fn (Get $get): string => ($rate = Property::query()->find($get('property_id'))?->tourist_tax_rate) ? 'Satz je Person und Nacht: '.Money::format((int) $rate).' (Wohnung › Kurabgabe)' : 'Kein Satz hinterlegt (Wohnung › Kurabgabe) – es wird nichts berechnet.'),
TextInput::make('tourist_tax_note')->label('Befreiungen / Hinweis zur Kurabgabe')->maxLength(255)->columnSpanFull(),
Repeater::make('items')->label('Zusatzleistungen')->columns(2)->defaultItems(0)->addActionLabel('Leistung hinzufügen')->columnSpanFull()->schema([
Select::make('extra_id')->label('Leistung')->options(fn (Get $get): array => Extra::query()->where('property_id', $get('../../property_id'))->orderBy('name')->pluck('name', 'id')->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
]),
]), ]),
Section::make('Portal') Section::make('Portal')
->columns(2) ->columns(2)
@@ -113,7 +153,7 @@ public static function configure(Schema $schema): Schema
TextInput::make('promo_code')->label('Aktionscode')->maxLength(50), TextInput::make('promo_code')->label('Aktionscode')->maxLength(50),
]), ]),
Section::make('Notiz') Section::make('Notiz')
->visible($isCase) ->visible(fn (Get $get): bool => $isCase($get) || $isInternal($get))
->collapsed() ->collapsed()
->schema([ ->schema([
Textarea::make('internal_notes')->hiddenLabel()->placeholder('Interne Notiz (nur für Sie sichtbar)'), Textarea::make('internal_notes')->hiddenLabel()->placeholder('Interne Notiz (nur für Sie sichtbar)'),
@@ -13,6 +13,7 @@
use App\Models\Booking; use App\Models\Booking;
use App\Models\IntakeObservation; use App\Models\IntakeObservation;
use App\Models\User; use App\Models\User;
use App\Pricing\CaseMoney;
use App\Process\CaseActivities; use App\Process\CaseActivities;
use App\Process\CaseAutomation; use App\Process\CaseAutomation;
use App\Process\ProcessProfile; use App\Process\ProcessProfile;
@@ -66,14 +67,10 @@ public static function configure(Schema $schema): Schema
TextEntry::make('label'), TextEntry::make('label'),
TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(), TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(),
]), ]),
Grid::make(4)->visible(fn (Booking $record): bool => $record->total !== null)->schema([ TextEntry::make('money')->hiddenLabel()->html()
TextEntry::make('total')->label('Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->weight('bold'), ->state(fn (Booking $record): HtmlString => new HtmlString(view('filament.case-money', ['money' => CaseMoney::of($record), 'booking' => $record])->render())),
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())), TextEntry::make('balance_due_on')->label('Restzahlung fällig am')->date('d.m.Y')
TextEntry::make('open')->label('Offen') ->visible(fn (Booking $record): bool => $record->wantsPaymentTasks() && $record->balance_due_on !== null),
->state(fn (Booking $record): string => $record->process()->payments() === Responsibility::Portal ? 'über das Portal' : Money::format($record->openAmount()))
->color(fn (Booking $record): string => $record->process()->payments() === Responsibility::Landlord && $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y')->placeholder('–'),
]),
]), ]),
Section::make('Verlauf') Section::make('Verlauf')
->collapsible() ->collapsible()
@@ -107,7 +104,7 @@ public static function configure(Schema $schema): Schema
->schema([ ->schema([
TextEntry::make('documents')->hiddenLabel()->html()->state(fn (Booking $record): HtmlString => self::documents($record)), 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('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) TextEntry::make('template')->label('Vorlage')->visible(fn (Booking $record): bool => ! $record->isInternal())->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)' ? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].', festgeschrieben)'
: (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'), : (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'),
]), ]),
@@ -154,7 +151,7 @@ private static function nextStep(Booking $booking): HtmlString
default => 'Nichts zu tun.', default => 'Nichts zu tun.',
}; };
$color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d'); $color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d');
$detail = $next?->detail ?? $waiting?->detail; $detail = $next !== null ? $next->detail : $waiting?->detail;
$mode = $automatic $mode = $automatic
? 'Dieser Vorgang läuft automatisch weiter, sobald alle Angaben da sind.'.(($blockers = self::blockers($booking)) !== [] ? ' Es fehlt: '.e(implode(' ', $blockers)) : '') ? 'Dieser Vorgang läuft automatisch weiter, sobald alle Angaben da sind.'.(($blockers = self::blockers($booking)) !== [] ? ' Es fehlt: '.e(implode(' ', $blockers)) : '')
: 'Sie geben jeden Schritt selbst frei. Der Knopf oben rechts führt zum nächsten Schritt.'; : 'Sie geben jeden Schritt selbst frei. Der Knopf oben rechts führt zum nächsten Schritt.';
@@ -13,7 +13,9 @@
use App\Models\Site; use App\Models\Site;
use App\Models\User; use App\Models\User;
use App\Support\Settings; use App\Support\Settings;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\KeyValue; use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker; use Filament\Forms\Components\TimePicker;
@@ -95,6 +97,9 @@ public static function configure(Schema $schema): Schema
->label('Endreinigung & Service (einmalig)') ->label('Endreinigung & Service (einmalig)')
->required() ->required()
->default(0), ->default(0),
EuroInput::make('tourist_tax_rate')
->label('Kurabgabe je Person und Nacht')
->helperText('Ihr Satz laut Gemeinde. Wird bei eigener Nutzung und privaten Aufenthalten als eigene Position berechnet; Befreiungen tragen Sie im Vorgang ein. Leer lassen: keine Berechnung.'),
]), ]),
Section::make('Zahlungsbedingungen') Section::make('Zahlungsbedingungen')
->columns(2) ->columns(2)
@@ -141,6 +146,36 @@ public static function configure(Schema $schema): Schema
->placeholder('Texte der Webseite') ->placeholder('Texte der Webseite')
->helperText('Wird bei neuen Angeboten verwendet, sofern das Portal keine eigene Vorlage hat.'), ->helperText('Wird bei neuen Angeboten verwendet, sofern das Portal keine eigene Vorlage hat.'),
]), ]),
Section::make('Aufenthalt vorbereiten und abschließen')
->description('Was bei jedem Aufenthalt in dieser Wohnung zu tun ist. Jede Zeile wird rechtzeitig zur Aufgabe am Vorgang – keine Personalplanung. Gebuchte Leistungen (z. B. Wäschepaket) kommen automatisch dazu.')
->collapsed()
->columnSpanFull()
->schema([
Toggle::make('asks_arrival_time')
->label('Anreisezeit erfragen')
->helperText('Fehlt sie wenige Tage vor der Anreise, erscheint die Aufgabe „Anreisedaten beim Gast erfragen“. Kontaktdaten werden immer geprüft.'),
Repeater::make('stay_tasks')
->label('Aufgaben je Aufenthalt')
->addActionLabel('Aufgabe hinzufügen')
->defaultItems(0)
->columns(4)
->schema([
TextInput::make('title')->label('Was?')->placeholder('z. B. Endreinigung')->required()->maxLength(120),
Select::make('when')->label('Wann?')->required()->default('before_arrival')->live()->options([
'before_arrival' => 'vor der Anreise',
'on_arrival' => 'am Anreisetag',
'after_departure' => 'am Abreisetag',
]),
TextInput::make('days')->label('Tage vorher')->integer()->minValue(0)->maxValue(14)->default(1)->visible(fn (Get $get): bool => $get('when') === 'before_arrival'),
TextInput::make('responsible')->label('Wer? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120),
CheckboxList::make('applies_to')->label('Bei')->required()->default(['rental'])->columns(4)->columnSpanFull()->options([
'rental' => 'Gästebuchungen',
'private' => 'Familie/Freunde',
'own' => 'eigener Nutzung',
'block' => 'Sperren',
]),
]),
]),
Section::make('Abweichende Abwicklung dieser Wohnung') Section::make('Abweichende Abwicklung dieser Wohnung')
->description('Nur nötig, wenn diese Wohnung anders bearbeitet wird als in „So arbeite ich“ eingestellt. Leere Felder folgen Ihren Standardeinstellungen.') ->description('Nur nötig, wenn diese Wohnung anders bearbeitet wird als in „So arbeite ich“ eingestellt. Leere Felder folgen Ihren Standardeinstellungen.')
->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert) ->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert)
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers;
use App\Actions\ChangeBooking;
use App\Enums\ChangeStatus;
use App\Exceptions\ReservationException;
use App\Mail\ChangeAnswered;
use App\Models\BookingChange;
use App\Support\Settings;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
/**
* The guest's page for a proposed change of a booking (signed link): see it, accept it or decline it. Only the acceptance
* here makes the change binding; it is recorded with time and (hashed) address.
*/
class ChangeController extends Controller
{
public function show(BookingChange $change): View
{
return view('change', ['change' => $change, 'booking' => $change->booking]);
}
public function accept(Request $request, BookingChange $change, ChangeBooking $changes): RedirectResponse
{
$request->validate(['agree' => ['accepted']], ['agree.accepted' => 'Bitte bestätigen Sie, dass Sie mit der Änderung einverstanden sind.']);
try {
$changes->accept($change, $request->ip());
} catch (ReservationException $exception) {
return back()->with('change.error', $exception->getMessage());
}
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChangeAnswered($change->fresh(), accepted: true)));
return back()->with('change.success', 'Vielen Dank – die Änderung ist jetzt verbindlich.');
}
public function decline(BookingChange $change, ChangeBooking $changes): RedirectResponse
{
if ($change->status === ChangeStatus::Proposed) {
$changes->decline($change, request()->ip());
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChangeAnswered($change->fresh(), accepted: false)));
}
return back()->with('change.success', 'Sie haben die Änderung abgelehnt. Ihre Buchung bleibt unverändert.');
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Http\Controllers;
use App\Actions\SubmitBookingWish;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
/**
* The guest's page of an information "unter Vorbehalt" (package 7, signed link from the mail): shows price and conditions
* as checked when it was sent, says plainly that nothing is reserved or binding, and lets the guest ask for the booking.
*/
class InformationController extends Controller
{
public function show(Request $request, Booking $booking, SubmitBookingWish $wish): View
{
$booking->loadMissing(['guest', 'property']);
$version = (int) $request->query('v');
$problem = null;
try {
$wish->ensureCurrent($booking, $version);
} catch (ReservationException $exception) {
$problem = $exception->getMessage();
}
return view('information', [
'booking' => $booking,
'problem' => $problem,
'canAsk' => $problem === null,
'wishUrl' => $this->signed($booking, 'information.wish', $booking->information_valid_until?->isFuture() ? $booking->information_valid_until : now()->addHour(), $version),
]);
}
public function wish(Request $request, Booking $booking, SubmitBookingWish $wish): RedirectResponse
{
$request->validate(['terms' => ['accepted']], ['terms.accepted' => 'Bitte bestätigen Sie, dass Sie die Angaben und Bedingungen gelesen haben.']);
$version = (int) $request->query('v');
$back = $this->signed($booking, 'information.show', now()->addDays(30), $version);
try {
$outcome = $wish->handle($booking, $version, $request->ip());
} catch (ReservationException $exception) {
return redirect()->to($back)->with('information.error', $exception->getMessage());
}
$booking->refresh();
return redirect()->to($back)->with('information.success', match ($outcome) {
SubmitBookingWish::CONFIRMED => $booking->confirmation_sent_at !== null
? 'Vielen Dank! Wir haben Verfügbarkeit und Preis geprüft – Ihre Buchung ist verbindlich bestätigt. Die Bestätigung mit dem Mietvertrag haben wir Ihnen per E-Mail gesendet.'
: 'Vielen Dank! Ihre Buchung ist verbindlich bestätigt. Die Bestätigung mit dem Mietvertrag erhalten Sie in Kürze per E-Mail.',
SubmitBookingWish::PENDING => 'Vielen Dank – Ihr Buchungswunsch ist eingegangen. Wir prüfen ihn und melden uns in Kürze. Die Buchung ist noch nicht verbindlich; sie wird es erst mit unserer Buchungsbestätigung.',
SubmitBookingWish::UNAVAILABLE => 'Leider ist der Zeitraum inzwischen vergeben. Es ist keine Buchung zustande gekommen. Vielleicht passt ein anderer Termin?',
default => 'Ihr Buchungswunsch liegt uns bereits vor – Sie müssen nichts weiter tun.',
});
}
private function signed(Booking $booking, string $name, DateTimeInterface $expiration, int $version): string
{
$parameters = ['booking' => $booking, 'v' => $version];
return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters)
?? URL::temporarySignedRoute($name, $expiration, $parameters);
}
}
+3 -1
View File
@@ -25,7 +25,9 @@ public function handle(MessageSent $event): void
$recipients = collect($event->message->getTo())->map(fn ($address): string => mb_strtolower($address->getAddress())); $recipients = collect($event->message->getTo())->map(fn ($address): string => mb_strtolower($address->getAddress()));
$guest = mb_strtolower((string) $booking->guest?->email); $guest = mb_strtolower((string) $booking->guest?->email);
$audience = ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord'); // A redirected mail carries the original recipients (EnforceMailTestMode); it never reached them.
$redirected = $event->message->getHeaders()->has(EnforceMailTestMode::ORIGINAL_RECIPIENTS_HEADER);
$audience = $redirected || ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord');
BookingMessage::query()->create([ BookingMessage::query()->create([
'booking_id' => $booking->id, 'booking_id' => $booking->id,
+11
View File
@@ -6,6 +6,7 @@
use App\Actions\RequestMarketingConsent; use App\Actions\RequestMarketingConsent;
use App\Availability\AvailabilityChecker; use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ReferralSource; use App\Enums\ReferralSource;
use App\Exceptions\ReservationException; use App\Exceptions\ReservationException;
use App\Models\Booking; use App\Models\Booking;
@@ -15,6 +16,7 @@
use App\Pricing\PriceQuote; use App\Pricing\PriceQuote;
use App\Pricing\QuoteException; use App\Pricing\QuoteException;
use App\Pricing\StayRequest; use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Tenancy\TenantContext; use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
@@ -104,6 +106,15 @@ public function property(): Property
return Property::findOrFail($this->propertyId); return Property::findOrFail($this->propertyId);
} }
/**
* Whether a request on the website reserves the dates (else it is answered with an information, package 7).
*/
#[Computed]
public function reservesDates(): bool
{
return app(ProcessSettings::class)->resolve($this->property, null, IntakeKind::Inquiry)->preReservation();
}
/** /**
* @return Collection<int, Extra> * @return Collection<int, Extra>
*/ */
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Confirms a change that was already agreed with the guest – information about what now applies, not a request for
* consent (package 5).
*/
class BookingChanged extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public BookingChange $change) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Änderung Ihrer Buchung '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-changed');
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Answer to the guest's booking wish while nothing is binding (package 7): received and being checked (`pending`),
* dates given away meanwhile (`unavailable`) or not confirmed by the landlord (`declined`). The confirmation itself is
* the usual booking confirmation with the contract.
*/
class BookingWishAnswered extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public string $outcome) {}
public function envelope(): Envelope
{
return new Envelope(
subject: ($this->outcome === 'pending' ? 'Ihr Buchungswunsch ist eingegangen' : 'Ihr Buchungswunsch').' – '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-wish-answered');
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Tells the landlord about a booking wish (package 7): confirmed automatically, waiting for the confirmation, or
* arrived after the dates were given away.
*/
class BookingWishNotice extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public string $outcome) {}
public function envelope(): Envelope
{
return new Envelope(subject: match ($this->outcome) {
'confirmed' => 'Buchungswunsch automatisch bestätigt',
'unavailable' => 'Buchungswunsch – Zeitraum inzwischen vergeben',
default => 'Buchungswunsch bitte bestätigen',
}.' '.$this->booking->reference.': '.$this->booking->guestName().', '.$this->booking->arrival->format('d.m.').'–'.$this->booking->departure->format('d.m.Y'));
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-wish-notice', with: ['caseUrl' => BookingResource::getUrl('view', ['record' => $this->booking])]);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Mail;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Tells the landlord how the guest answered a proposed change.
*/
class ChangeAnswered extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public BookingChange $change, public bool $accepted) {}
public function envelope(): Envelope
{
return new Envelope(subject: ($this->accepted ? 'Änderung angenommen: ' : 'Änderung abgelehnt: ').$this->change->booking->reference);
}
public function content(): Content
{
return new Content(markdown: 'mail.change-answered');
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Proposes a change to the guest: nothing has changed yet; the guest accepts or declines through the signed link
* (package 5). Only the guest's acceptance makes it binding.
*/
class ChangeProposed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public BookingChange $change, public string $url) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Vorschlag zur Änderung Ihrer Buchung '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.change-proposed');
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* The information "unter Vorbehalt" (package 7): price and availability as checked now, no reservation, no acceptance
* link – only the link to ask for the booking, which is checked again before anything becomes binding.
*/
class InformationSent extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public string $url) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Unverbindliche Auskunft zu Ihrer Anfrage '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.information-sent');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?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 confirmation of a private stay (A6, on request): the stay, no rental contract (package 6).
*/
class StayConfirmed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Bestätigung Ihres Aufenthalts '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.stay-confirmed');
}
/**
* @return list<Attachment>
*/
public function attachments(): array
{
$path = app(RentalContract::class)->absolutePath($this->booking);
return $path ? [Attachment::fromPath($path)->as("Aufenthaltsbestaetigung-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
}
}
+98 -3
View File
@@ -7,6 +7,8 @@
use App\Enums\BookingTaskKind; use App\Enums\BookingTaskKind;
use App\Enums\CaseType; use App\Enums\CaseType;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
use App\Enums\ReferralSource; use App\Enums\ReferralSource;
use App\Enums\Responsibility; use App\Enums\Responsibility;
@@ -91,13 +93,30 @@
'balance_requested_at', 'balance_requested_at',
'balance_reminded_at', 'balance_reminded_at',
'arrival_info_sent_at', 'arrival_info_sent_at',
'internal_kind',
'occasion',
'tourist_tax_persons',
'tourist_tax_note',
'portal_cancellation_requested_at',
'export_uid',
'information_version',
'information_sent_at',
'information_valid_until',
'information',
'wish_at',
'wish',
'arrival_time',
'completed_at',
'settled_at',
'settled_note',
'settled_by',
])] ])]
class Booking extends Model class Booking extends Model
{ {
/** @use HasFactory<BookingFactory> */ /** @use HasFactory<BookingFactory> */
use BelongsToTenant, HasChannelProvenance, HasFactory; use BelongsToTenant, HasChannelProvenance, HasFactory;
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email']; public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email', 'internal'];
public function isDirect(): bool public function isDirect(): bool
{ {
@@ -177,6 +196,15 @@ protected function casts(): array
'contact_requested_at' => 'immutable_datetime', 'contact_requested_at' => 'immutable_datetime',
'guest_confirmed_at' => 'immutable_datetime', 'guest_confirmed_at' => 'immutable_datetime',
'archived_at' => 'immutable_datetime', 'archived_at' => 'immutable_datetime',
'internal_kind' => InternalKind::class,
'portal_cancellation_requested_at' => 'immutable_datetime',
'information_sent_at' => 'immutable_datetime',
'information_valid_until' => 'immutable_datetime',
'information' => 'array',
'wish_at' => 'immutable_datetime',
'wish' => 'array',
'completed_at' => 'immutable_datetime',
'settled_at' => 'immutable_datetime',
]; ];
} }
@@ -267,6 +295,7 @@ public function bookingChannelLabel(): string
'phone' => 'Telefon', 'phone' => 'Telefon',
'email' => 'E-Mail', 'email' => 'E-Mail',
'direct' => 'Direkt', 'direct' => 'Direkt',
'internal' => 'Eigene Belegung',
default => $this->source, default => $this->source,
}; };
} }
@@ -336,7 +365,73 @@ public function payments(): HasMany
*/ */
public function paidAmount(): int public function paidAmount(): int
{ {
return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount')); return $this->sumOfPayments([PaymentKind::Guest, PaymentKind::GuestViaPortal, PaymentKind::Refund]);
}
/**
* What the guest paid us directly, less refunds (money on our account from the guest).
*/
public function paidToUs(): int
{
return $this->sumOfPayments([PaymentKind::Guest, PaymentKind::Refund]);
}
/**
* What the guest paid to the portal according to the portal (no money on our account).
*/
public function paidViaPortal(): int
{
return $this->sumOfPayments([PaymentKind::GuestViaPortal]);
}
/**
* What the portal paid out to us.
*/
public function payoutsReceived(): int
{
return $this->sumOfPayments([PaymentKind::PortalPayout]);
}
/**
* @param list<PaymentKind> $kinds
*/
private function sumOfPayments(array $kinds): int
{
$payments = $this->relationLoaded('payments') ? $this->payments : $this->payments()->get();
return (int) $payments->filter(fn (Payment $payment): bool => in_array($payment->kind ?? PaymentKind::Guest, $kinds, true))->sum('amount');
}
/**
* @return HasOne<Cancellation, $this>
*/
public function cancellation(): HasOne
{
return $this->hasOne(Cancellation::class);
}
/**
* @return HasMany<CaseAmount, $this>
*/
public function amounts(): HasMany
{
return $this->hasMany(CaseAmount::class)->orderBy('id');
}
/**
* @return HasMany<BookingChange, $this>
*/
public function changes(): HasMany
{
return $this->hasMany(BookingChange::class)->orderBy('id');
}
/**
* Own use, private stay or block (A6).
*/
public function isInternal(): bool
{
return $this->intake === IntakeKind::Internal;
} }
/** /**
@@ -366,7 +461,7 @@ public function requiresFullPayment(): bool
*/ */
public function wantsPaymentTasks(): bool public function wantsPaymentTasks(): bool
{ {
return $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0; return ! $this->isInternal() && $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0;
} }
/** /**
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Models;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One change of a booking (package 5): what it was before and after, who asked and why, from when, and on which basis
* the guest agreed – or, as long as it is only proposed, that the guest still has to agree.
*/
#[Fillable(['booking_id', 'status', 'requested_by', 'basis', 'reason', 'effective_on', 'agreed_at', 'agreed_by', 'before', 'after', 'consequences', 'expires_at', 'decided_at', 'decision_ip_hash', 'applied_at', 'confirmation_sent_at', 'recorded_by'])]
class BookingChange extends Model
{
use BelongsToTenant;
public const REQUESTERS = ['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)', 'portal' => 'Das Portal'];
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'status' => ChangeStatus::class,
'basis' => ChangeBasis::class,
'effective_on' => 'immutable_date',
'agreed_at' => 'immutable_datetime',
'before' => 'array',
'after' => 'array',
'consequences' => 'array',
'expires_at' => 'immutable_datetime',
'decided_at' => 'immutable_datetime',
'applied_at' => 'immutable_datetime',
'confirmation_sent_at' => 'immutable_datetime',
];
}
/** @return BelongsTo<Booking, $this> */
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
/**
* The change in one line, e.g. "07.11.–10.11.2026 → 07.11.–12.11.2026 · 2 → 3 Personen · 368,00 € → 450,00 €".
*/
public function summary(): string
{
return implode(' · ', (array) ($this->consequences['summary'] ?? []));
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ protected static function booted(): void
CaseLog::record($message->booking, 'mail', 'E-Mail '.match ($message->audience) { CaseLog::record($message->booking, 'mail', 'E-Mail '.match ($message->audience) {
'guest' => 'an den Gast', 'guest' => 'an den Gast',
'landlord' => 'an uns', 'landlord' => 'an uns',
default => '(Testbetrieb)', default => 'im Testbetrieb an die Testadresse (nicht an den Gast)',
}.': '.$message->subject, actor: CaseLog::SYSTEM, at: $message->sent_at); }.': '.$message->subject, actor: CaseLog::SYSTEM, at: $message->sent_at);
} }
}); });
+36 -5
View File
@@ -5,6 +5,7 @@
use App\Enums\BookingTaskKind; use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Models\Concerns\BelongsToTenant; use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseClosure;
use App\Process\CaseLog; use App\Process\CaseLog;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -16,7 +17,7 @@
* Something the landlord has to do about a booking. One task per booking and kind; a finished or * Something the landlord has to do about a booking. One task per booking and kind; a finished or
* dismissed task is never created again. * dismissed task is never created again.
*/ */
#[Fillable(['booking_id', 'kind', 'status', 'due_on', 'note', 'completed_by', 'completed_at'])] #[Fillable(['booking_id', 'kind', 'subject', 'title', 'responsible', 'status', 'due_on', 'note', 'completed_by', 'completed_at'])]
class BookingTask extends Model class BookingTask extends Model
{ {
use BelongsToTenant; use BelongsToTenant;
@@ -25,12 +26,19 @@ protected static function booted(): void
{ {
static::created(function (BookingTask $task): void { static::created(function (BookingTask $task): void {
if ($task->booking !== null) { if ($task->booking !== null) {
CaseLog::record($task->booking, 'task', 'Aufgabe: '.$task->kind->getLabel()); CaseLog::record($task->booking, 'task', 'Aufgabe: '.$task->label().($task->responsible ? ' (zuständig: '.$task->responsible.')' : ''));
if ($task->kind->isCommercial() && $task->status === BookingTaskStatus::Open) {
CaseClosure::refresh($task->booking);
}
} }
}); });
static::updated(function (BookingTask $task): void { static::updated(function (BookingTask $task): void {
if ($task->wasChanged('status') && $task->status !== BookingTaskStatus::Open && $task->booking !== null) { if ($task->wasChanged('status') && $task->status !== BookingTaskStatus::Open && $task->booking !== null) {
CaseLog::record($task->booking, 'task', 'Aufgabe '.($task->status === BookingTaskStatus::Done ? 'erledigt' : 'verworfen').': '.$task->kind->getLabel(), actor: $task->completed_by); CaseLog::record($task->booking, 'task', 'Aufgabe '.($task->status === BookingTaskStatus::Done ? 'erledigt' : 'verworfen').': '.$task->label().($task->wasChanged('note') && filled($task->note) ? ' – '.$task->note : ''), actor: $task->completed_by);
}
// Money tasks decide the commercial closing of the case (package 9).
if ($task->wasChanged('status') && $task->booking !== null && $task->kind->isCommercial()) {
CaseClosure::refresh($task->booking);
} }
}); });
} }
@@ -68,8 +76,31 @@ protected function open(Builder $query): Builder
return $query->where('status', BookingTaskStatus::Open); return $query->where('status', BookingTaskStatus::Open);
} }
public function complete(string $by): void public function complete(string $by, ?string $note = null): void
{ {
$this->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]); $this->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now(), ...($note !== null && $note !== '' ? ['note' => mb_substr($note, 0, 1000)] : [])]);
}
/**
* What the task is about in plain words: its own title (services, issues, follow-ups) or the label of its kind.
*/
public function label(): string
{
return filled($this->title) ? (string) $this->title : $this->kind->getLabel();
}
/**
* Opens the task of this kind and subject for the case once; a task that was done or dismissed is not opened again.
*
* @param array<string, mixed> $attributes
*/
public static function openOnce(Booking $booking, BookingTaskKind $kind, string $subject = '', array $attributes = []): self
{
$task = static::withoutGlobalScope('tenant')->firstOrNew(['booking_id' => $booking->id, 'kind' => $kind, 'subject' => $subject]);
if (! $task->exists) {
$task->forceFill(['tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, ...$attributes])->save();
}
return $task;
} }
} }
+1 -1
View File
@@ -11,7 +11,7 @@
* The record of a cancelled booking: when, how many days before arrival, the cost proposed by the cancellation rule * The record of a cancelled booking: when, how many days before arrival, the cost proposed by the cancellation rule
* and the amount the landlord finally charges. Cancelled bookings stay in the system for this history. * and the amount the landlord finally charges. Cancelled bookings stay in the system for this history.
*/ */
#[Fillable(['booking_id', 'cancelled_on', 'initiated_by', 'has_policy', 'policy_name', 'days_before', 'percent', 'base_amount', 'calculated_fee', 'final_fee', 'paid_amount', 'status', 'note', 'settled_at'])] #[Fillable(['booking_id', 'cancelled_on', 'initiated_by', 'has_policy', 'policy_name', 'days_before', 'percent', 'base_amount', 'calculated_fee', 'final_fee', 'paid_amount', 'status', 'note', 'settled_at', 'reason', 'recorded_by'])]
class Cancellation extends Model class Cancellation extends Model
{ {
use BelongsToTenant; use BelongsToTenant;
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use App\Enums\AmountKind;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
use App\Support\Money;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* An amount of a case as a source states it (package 8): the portal's price positions, what it keeps as commission,
* what it announces to pay out, instalments of the guest. Stored as stated – contradicting statements stand side by
* side, and nothing is derived from them.
*/
#[Fillable(['booking_id', 'kind', 'label', 'amount', 'source', 'stated_on', 'due_on', 'note', 'recorded_by'])]
class CaseAmount extends Model
{
use BelongsToTenant;
protected static function booted(): void
{
static::created(function (CaseAmount $amount): void {
if ($amount->booking !== null) {
CaseLog::record($amount->booking, 'amount', ($amount->label ?: $amount->kind->getLabel()).': '.Money::format($amount->amount).($amount->source ? ' laut '.$amount->source : ''), data: ['case_amount_id' => $amount->id]);
}
});
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return ['kind' => AmountKind::class, 'amount' => 'integer', 'stated_on' => 'immutable_date', 'due_on' => 'immutable_date'];
}
/** @return BelongsTo<Booking, $this> */
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
public function title(): string
{
return $this->label ?: $this->kind->getLabel();
}
}
+7 -4
View File
@@ -2,10 +2,11 @@
namespace App\Models; namespace App\Models;
use App\Actions\RecordPayment;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod; use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToTenant; use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog; use App\Process\CaseLog;
use App\Support\Money;
use Database\Factories\PaymentFactory; use Database\Factories\PaymentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -13,9 +14,10 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
/** /**
* A received payment (negative amount = refund), in euro cents. * A payment in euro cents (negative amount = refund) and its kind: the guest paid us, the portal reports the guest paid
* it, the portal paid out to us, or we refunded the guest ({@see PaymentKind}).
*/ */
#[Fillable(['booking_id', 'amount', 'paid_on', 'method', 'note', 'recorded_by'])] #[Fillable(['booking_id', 'amount', 'paid_on', 'method', 'note', 'recorded_by', 'kind', 'source'])]
class Payment extends Model class Payment extends Model
{ {
/** @use HasFactory<PaymentFactory> */ /** @use HasFactory<PaymentFactory> */
@@ -25,7 +27,7 @@ protected static function booted(): void
{ {
static::created(function (Payment $payment): void { static::created(function (Payment $payment): void {
if ($payment->booking !== null) { if ($payment->booking !== null) {
CaseLog::record($payment->booking, 'payment', ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').Money::format(abs($payment->amount)).' erfasst', data: ['payment_id' => $payment->id]); CaseLog::record($payment->booking, 'payment', RecordPayment::summary($payment->booking, $payment->kind ?? PaymentKind::Guest, (int) $payment->amount, $payment->paid_on, $payment->source), data: ['payment_id' => $payment->id, 'kind' => ($payment->kind ?? PaymentKind::Guest)->value]);
} }
}); });
} }
@@ -40,6 +42,7 @@ protected function casts(): array
return [ return [
'paid_on' => 'immutable_date', 'paid_on' => 'immutable_date',
'method' => PaymentMethod::class, 'method' => PaymentMethod::class,
'kind' => PaymentKind::class,
]; ];
} }
+33
View File
@@ -13,6 +13,7 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Str;
/** /**
* A rentable holiday apartment. All money amounts are stored in euro cents. * A rentable holiday apartment. All money amounts are stored in euro cents.
@@ -28,6 +29,7 @@
'included_guests', 'included_guests',
'extra_guest_fee_per_night', 'extra_guest_fee_per_night',
'cleaning_fee', 'cleaning_fee',
'tourist_tax_rate',
'deposit_percent', 'deposit_percent',
'balance_due_days_before_arrival', 'balance_due_days_before_arrival',
'hold_hours', 'hold_hours',
@@ -46,6 +48,8 @@
'min_stay_absolute', 'min_stay_absolute',
'is_active', 'is_active',
'process_overrides', 'process_overrides',
'stay_tasks',
'asks_arrival_time',
])] ])]
class Property extends Model class Property extends Model
{ {
@@ -84,6 +88,8 @@ protected function casts(): array
'free_cancellation_days' => 'integer', 'free_cancellation_days' => 'integer',
'contract_data' => 'array', 'contract_data' => 'array',
'process_overrides' => 'array', 'process_overrides' => 'array',
'stay_tasks' => 'array',
'asks_arrival_time' => 'boolean',
'min_stay_fill_gaps' => 'boolean', 'min_stay_fill_gaps' => 'boolean',
'min_stay_until_changeover' => 'boolean', 'min_stay_until_changeover' => 'boolean',
'changeover_weekday' => 'integer', 'changeover_weekday' => 'integer',
@@ -187,4 +193,31 @@ public function extras(): HasMany
{ {
return $this->hasMany(Extra::class)->orderBy('sort_order'); return $this->hasMany(Extra::class)->orderBy('sort_order');
} }
/**
* The stay tasks of this property (package 9): local services and provider jobs such as cleaning, linen or the key
* handover, each with when it is due and for which kinds of stays it applies. No staff planning – a task per case.
*
* @return list<array{key: string, title: string, when: string, days: int, responsible: ?string, applies_to: list<string>}>
*/
public function stayTaskDefinitions(): array
{
$definitions = [];
foreach ((array) ($this->stay_tasks ?? []) as $task) {
$title = trim((string) ($task['title'] ?? ''));
if ($title === '') {
continue;
}
$definitions[] = [
'key' => 'stay:'.mb_substr(Str::slug($title), 0, 70),
'title' => $title,
'when' => in_array($task['when'] ?? null, ['before_arrival', 'on_arrival', 'after_departure'], true) ? $task['when'] : 'before_arrival',
'days' => max(0, (int) ($task['days'] ?? 1)),
'responsible' => filled($task['responsible'] ?? null) ? trim((string) $task['responsible']) : null,
'applies_to' => array_values(array_filter((array) ($task['applies_to'] ?? ['rental']))) ?: ['rental'],
];
}
return $definitions;
}
} }
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Pricing;
use App\Enums\AmountKind;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\CaseAmount;
use Illuminate\Support\Collection;
/**
* The money of a case as four separate questions (package 8, K01): what the guest owes and to whom, what the guest has
* paid (to us or – according to the portal – to the portal), what the portal still has to pay out to us, and what has
* really arrived on our account. Every figure comes from a stated amount or a recorded payment; nothing is split up,
* estimated or counted twice, and contradicting statements are shown side by side with their difference.
*/
final class CaseMoney
{
private function __construct(private Booking $booking) {}
public static function of(Booking $booking): self
{
$booking->loadMissing(['payments', 'amounts']);
return new self($booking);
}
/**
* Who collects the guest's money (us, the portal, nobody for internal cases).
*/
public function collector(): Responsibility
{
return $this->booking->process()->payments();
}
public function total(): ?int
{
return $this->booking->total;
}
public function totalSource(): string
{
return match (true) {
$this->booking->total === null => 'noch nicht bekannt',
($this->booking->quote['source'] ?? null) === 'portal' => 'laut '.($this->booking->processChannel()?->name ?? 'Portal'),
$this->booking->isInternal() => 'vereinbart',
default => 'aus Ihren Preisen berechnet',
};
}
/**
* What the guest still owes us – only when we collect the money.
*/
public function openForUs(): int
{
return $this->collector() === Responsibility::Landlord ? $this->booking->openAmount() : 0;
}
/**
* What the guest still owes the portal according to the portal's statements (informational; the portal collects it).
*/
public function openAtPortal(): ?int
{
if ($this->collector() !== Responsibility::Portal || $this->booking->total === null) {
return null;
}
return max(0, $this->booking->total - $this->booking->paidViaPortal());
}
/**
* Instalments of the guest that the portal still shows as due.
*
* @return Collection<int, CaseAmount>
*/
public function installmentsDue(): Collection
{
return $this->amounts(AmountKind::InstallmentDue);
}
/**
* The price positions as stated, with their sum and whether they add up to the agreed total.
*
* @return array{positions: Collection<int, CaseAmount>, sum: int, difference: ?int}
*/
public function positions(): array
{
$positions = $this->booking->amounts->filter(fn (CaseAmount $amount): bool => $amount->kind->isPricePosition())->values();
$sum = (int) $positions->sum('amount');
return ['positions' => $positions, 'sum' => $sum, 'difference' => $positions->isEmpty() || $this->booking->total === null ? null : $this->booking->total - $sum];
}
/**
* @return Collection<int, CaseAmount>
*/
public function commissions(): Collection
{
return $this->amounts(AmountKind::Commission);
}
/**
* Payout announcements of the portal. Several different values are kept as they are; the difference is shown.
*
* @return array{announcements: Collection<int, CaseAmount>, values: list<int>, difference: int, received: int, outstanding: ?int}
*/
public function payout(): array
{
$announcements = $this->amounts(AmountKind::PayoutAnnounced);
$values = array_values(array_unique($announcements->pluck('amount')->map(fn ($value): int => (int) $value)->all()));
$received = $this->booking->payoutsReceived();
return [
'announcements' => $announcements,
'values' => $values,
'difference' => $values === [] ? 0 : max($values) - min($values),
'received' => $received,
// Only a single, consistent announcement gives an outstanding amount; contradicting ones are left to the person.
'outstanding' => count($values) === 1 ? max(0, $values[0] - $received) : null,
];
}
/**
* Money that really arrived on our account for this case: the guest's own payments (less refunds) and payouts.
*/
public function receivedOnAccount(): int
{
return $this->booking->paidToUs() + $this->booking->payoutsReceived();
}
/**
* @return Collection<int, CaseAmount>
*/
private function amounts(AmountKind $kind): Collection
{
return $this->booking->amounts->filter(fn (CaseAmount $amount): bool => $amount->kind === $kind)->values();
}
}
+1 -1
View File
@@ -209,7 +209,7 @@ private function bestOffers(Collection $offers, array $nightSeasons): array
* @param array<int, int> $extraQuantities * @param array<int, int> $extraQuantities
* @return list<QuoteLine> * @return list<QuoteLine>
*/ */
private function extraLines(Property $property, array $extraQuantities, int $nights): array public function extraLines(Property $property, array $extraQuantities, int $nights): array
{ {
$extraQuantities = array_filter($extraQuantities, fn (int $quantity): bool => $quantity > 0); $extraQuantities = array_filter($extraQuantities, fn (int $quantity): bool => $quantity > 0);
if ($extraQuantities === []) { if ($extraQuantities === []) {
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Pricing;
use App\Enums\QuoteLineType;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* The price of an internal case (A6, package 6): the rent agreed for this stay (often 0 for family), the services
* booked with their usual prices, and the tourist tax (Kurabgabe) as a position of its own – the persons liable ×
* nights × the rate the landlord keeps on the property. Exemptions are noted by hand; there is no municipal rule logic.
*/
class PrivateStayPrice
{
public function __construct(private PriceCalculator $calculator) {}
/**
* @param array<int, int> $extras extra id => quantity
*
* @throws QuoteException
*/
public function quote(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras, int $rent, ?int $taxPersons): PriceQuote
{
$nights = (int) $arrival->diffInDays($departure);
$lines = [new QuoteLine(QuoteLineType::Rent, 'Miete (vereinbart)', 1, $rent, $rent)];
array_push($lines, ...$this->calculator->extraLines($property, $extras, $nights));
$tax = self::touristTax($property, $nights, $taxPersons);
if ($tax !== null) {
$lines[] = $tax;
}
return new PriceQuote($arrival, $departure, (int) $guests, $lines, 0, $arrival);
}
/**
* The tourist tax line, or null when no rate is kept or nobody is liable.
*/
public static function touristTax(Property $property, int $nights, ?int $persons): ?QuoteLine
{
$rate = (int) ($property->tourist_tax_rate ?? 0);
if ($rate <= 0 || (int) $persons <= 0 || $nights <= 0) {
return null;
}
$units = (int) $persons * $nights;
return new QuoteLine(QuoteLineType::TouristTax, 'Kurabgabe ('.$persons.' '.((int) $persons === 1 ? 'Person' : 'Personen').' × '.$nights.' Nächte)', $units, $rate, $units * $rate);
}
/**
* The agreed rent of an existing internal case (its rent line), 0 when none.
*
* @param array<string, mixed>|null $quote
*/
public static function rentOf(?array $quote): int
{
foreach ((array) ($quote['lines'] ?? []) as $line) {
if (($line['type'] ?? null) === QuoteLineType::Rent->value) {
return (int) $line['amount'];
}
}
return 0;
}
}
+208 -9
View File
@@ -2,18 +2,25 @@
namespace App\Process; namespace App\Process;
use App\Actions\EndInternalCase;
use App\Actions\PrepareStays;
use App\Actions\SendBookingDocuments; use App\Actions\SendBookingDocuments;
use App\Availability\AvailabilityChecker;
use App\Enums\ActivityState; use App\Enums\ActivityState;
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus; use App\Enums\BookingTaskStatus;
use App\Enums\ChangeStatus;
use App\Enums\ChannelTaskStatus; use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeKind; use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\ProcessingMode; use App\Enums\ProcessingMode;
use App\Enums\Responsibility; use App\Enums\Responsibility;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource; use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Models\Booking; use App\Models\Booking;
use App\Models\BookingTask; use App\Models\BookingTask;
use App\Models\ChannelTask; use App\Models\ChannelTask;
use App\Pricing\CaseMoney;
use App\Support\Money; use App\Support\Money;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
@@ -28,7 +35,7 @@ class CaseActivities
private const LISTED_SEPARATELY = ['channel_block']; private const LISTED_SEPARATELY = ['channel_block'];
/** Activities that are the next step whatever else is open. */ /** Activities that are the next step whatever else is open. */
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported']; private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation'];
/** /**
* @return list<Activity> * @return list<Activity>
@@ -41,9 +48,17 @@ public static function for(Booking $booking): array
$binding = $booking->isBinding(); $binding = $booking->isBinding();
$inquiry = $booking->intake !== IntakeKind::Booking; $inquiry = $booking->intake !== IntakeKind::Booking;
$today = CarbonImmutable::today(); $today = CarbonImmutable::today();
$later = fn (ActivityState $state): ActivityState => $closed && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state; // After the end of a case (or of its stay) what was not done before is no longer to do; open money and other
// follow-ups are tasks and the commercial closing of their own (package 9).
// A stay whose departure has passed counts as over for the steps before it, too.
$over = $closed || $booking->status === BookingStatus::Completed || ($binding && $booking->departure->isBefore($today));
$later = fn (ActivityState $state): ActivityState => $over && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
$activities = []; $activities = [];
if ($booking->isInternal()) {
return self::internal($booking, $closed, $later);
}
$activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel()); $activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel());
$needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord; $needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
@@ -59,7 +74,37 @@ public static function for(Booking $booking): array
$hasEmail ? null : 'provideContact'); $hasEmail ? null : 'provideContact');
} }
if ($inquiry) { if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) {
// Package 7: a request without a hold is answered with an information "unter Vorbehalt"; the guest asks for the booking.
$informed = $booking->information_version > 0 || $binding;
$activities[] = new Activity('information', $booking->processingMode() === ProcessingMode::Automatic ? 'Unverbindliche Auskunft senden (automatisch)' : 'Unverbindliche Auskunft prüfen und senden', $later(match (true) {
$booking->information_version > 0 => ActivityState::Done,
$binding => ActivityState::NotApplicable,
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
default => ActivityState::Later,
}), $booking->information_version > 0 ? 'Version '.$booking->information_version.' vom '.$booking->information_sent_at?->format('d.m.Y').' · ohne Reservierung' : 'der Zeitraum wird nicht reserviert', $informed ? null : 'sendInformation');
$activities[] = new Activity('wish', 'Gast fragt die Buchung an', $later(match (true) {
$booking->wish_at !== null => ActivityState::Done,
$binding => ActivityState::NotApplicable,
$booking->information_version > 0 && $booking->information_valid_until?->isFuture() => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->wish_at !== null => 'angefragt am '.$booking->wish_at->format('d.m.Y, H:i').' Uhr',
$booking->information_version > 0 => 'möglich bis '.$booking->information_valid_until?->format('d.m.Y, H:i').' Uhr',
default => null,
});
$activities[] = new Activity('wish_check', 'Erneut prüfen und verbindlich bestätigen', $later(match (true) {
$binding => ActivityState::Done,
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->accepted_at !== null && ($booking->acceptance['via'] ?? null) === 'booking_wish' => 'bestätigt am '.$booking->confirmed_at?->format('d.m.Y').' ('.($booking->acceptance['confirmed_by'] ?? '').')',
$booking->wish_at !== null && $booking->status === BookingStatus::Reserved => 'siehe Aufgabe „Buchungswunsch bestätigen?“',
$binding => 'direkt verbindlich bestätigt (ohne Buchungswunsch)',
default => $booking->processingMode() === ProcessingMode::Automatic ? 'automatisch, wenn alles passt' : 'durch Sie',
});
} elseif ($inquiry) {
$offerDone = $booking->offer_version > 0 || $binding; $offerDone = $booking->offer_version > 0 || $binding;
$activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) { $activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) {
$offerDone => ActivityState::Done, $offerDone => ActivityState::Done,
@@ -117,7 +162,19 @@ public static function for(Booking $booking): array
} }
if ($profile->payments() === Responsibility::Portal) { if ($profile->payments() === Responsibility::Portal) {
$activities[] = new Activity('payment', 'Zahlung des Gastes', ActivityState::External, 'läuft über das Portal'); $portal = $booking->processChannel()?->name ?? 'das Portal';
$viaPortal = $booking->paidViaPortal();
$activities[] = new Activity('payment', 'Zahlung des Gastes an '.$portal, ActivityState::External, match (true) {
$booking->total === null => 'zieht das Portal ein',
$viaPortal > 0 => 'laut Portal bezahlt: '.Money::format($viaPortal).' von '.Money::format($booking->total).' (Angabe des Portals, kein Geld bei uns)',
default => 'zieht das Portal ein; noch keine Zahlungsangabe',
});
$payout = CaseMoney::of($booking)->payout();
$activities[] = new Activity('payout', 'Auszahlung von '.$portal.' auf unser Konto', $later(match (true) {
! $binding => ActivityState::Later,
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) === 0 && $payout['difference'] === 0 => ActivityState::Done,
default => ActivityState::Waiting,
}), trim(($payout['values'] !== [] ? 'angekündigt '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).' · ' : '').'eingegangen '.Money::format($payout['received']).($payout['difference'] > 0 ? ' · Angaben weichen um '.Money::format($payout['difference']).' ab' : '')));
} elseif ($booking->total === null) { } elseif ($booking->total === null) {
$activities[] = new Activity('payment', 'Zahlungen überwachen', $later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist'); $activities[] = new Activity('payment', 'Zahlungen überwachen', $later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist');
} else { } else {
@@ -134,14 +191,27 @@ public static function for(Booking $booking): array
}), Money::format(max(0, $booking->total - (int) $booking->deposit)).($booking->balance_due_on ? ', fällig '.$booking->balance_due_on->format('d.m.Y') : '')); }), Money::format(max(0, $booking->total - (int) $booking->deposit)).($booking->balance_due_on ? ', fällig '.$booking->balance_due_on->format('d.m.Y') : ''));
} }
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) { foreach (self::tasks($booking) as $task) {
$activities[] = new Activity('task_'.$task->kind->value, $task->kind->getLabel(), ActivityState::Open, $task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : null, $task->kind->isPayment() ? null : 'end'); $activities[] = self::task($task);
}
foreach ($booking->changes()->where('status', ChangeStatus::Proposed)->get() as $change) {
$activities[] = new Activity('change_proposed', 'Änderungsvorschlag liegt beim Gast', ActivityState::Waiting, $change->summary().($change->expires_at ? ' · bis '.$change->expires_at->format('d.m.Y') : ''));
} }
$arrived = $binding && $booking->arrival <= $today; $arrived = $binding && $booking->arrival <= $today;
$left = $binding && $booking->departure <= $today; $left = $binding && $booking->departure <= $today;
$missing = PrepareStays::missingArrivalDetails($booking);
$detailsTask = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->exists();
if ($binding && ! $detailsTask) {
$activities[] = new Activity('arrival_details', 'Anreisedaten', $later(match (true) {
$missing === [] => ActivityState::Done,
$left => ActivityState::NotApplicable,
default => ActivityState::Later,
}), $missing === [] ? implode(' · ', array_filter([$booking->guest?->phone ?: $booking->guest?->email, $booking->arrival_time ? 'Anreise '.$booking->arrival_time : null])) : 'es fehlt: '.implode(', ', $missing).' – wird rechtzeitig als Aufgabe gemeldet');
}
$activities[] = $profile->guestMessages() === Responsibility::Portal $activities[] = $profile->guestMessages() === Responsibility::Portal
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External) ? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen')
: new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise'); : new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise');
$activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) { $activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) {
$left => ActivityState::Done, $left => ActivityState::Done,
@@ -152,9 +222,123 @@ public static function for(Booking $booking): array
$activities[] = new Activity('review', 'Bitte um eine Bewertung (automatisch)', $later($booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later)); $activities[] = new Activity('review', 'Bitte um eine Bewertung (automatisch)', $later($booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later));
} }
return [...$activities, ...self::closing($booking, $closed)];
}
/**
* The two closings of a case (package 9): the stay, and the money.
*
* @return list<Activity>
*/
private static function closing(Booking $booking, bool $closed): array
{
$today = CarbonImmutable::today();
$completed = $booking->status === BookingStatus::Completed;
$activities = [];
if (! $closed && ($booking->isBinding() || $completed)) {
$blockers = $booking->isBinding() && ! $completed ? CaseClosure::stayBlockers($booking) : collect();
$activities[] = new Activity('closure', $booking->isInternal() && $booking->internal_kind === InternalKind::Block ? 'Sperrzeit abschließen' : 'Aufenthalt abschließen', match (true) {
$completed => ActivityState::Done,
! $booking->isBinding() || $booking->departure > $today => ActivityState::Later,
default => ActivityState::Waiting,
}, match (true) {
$completed => 'abgeschlossen am '.($booking->completed_at ?? $booking->updated_at)?->format('d.m.Y'),
$blockers->isNotEmpty() => 'wartet auf: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', '),
$booking->isBinding() && $booking->departure <= $today => 'geschieht automatisch über Nacht – oder jetzt von Hand',
default => 'nach der Abreise, sobald nichts mehr für den Aufenthalt offen ist',
}, $booking->isBinding() && ! $completed && $booking->departure <= $today ? 'closeStay' : null);
}
$settlementApplies = $completed || $booking->status === BookingStatus::Cancelled;
if ($settlementApplies || ($booking->isBinding() && ! $booking->isInternal()) || ($booking->isInternal() && (int) $booking->total > 0)) {
$points = $settlementApplies && $booking->settled_at === null ? CaseClosure::commercialPoints($booking) : [];
$activities[] = new Activity('settlement', 'Kaufmännisch abschließen', match (true) {
$booking->settled_at !== null => ActivityState::Done,
! $settlementApplies => ActivityState::Later,
default => ActivityState::Waiting,
}, match (true) {
$booking->settled_at !== null => 'abgeschlossen am '.$booking->settled_at->format('d.m.Y').($booking->settled_by && $booking->settled_by !== CaseClosure::AUTOMATIC ? ' von '.$booking->settled_by : '').($booking->settled_note ? ' · '.$booking->settled_note : ''),
! $settlementApplies => 'nach dem Aufenthalt, wenn Zahlungen, Erstattungen und Auszahlungen geklärt sind',
default => 'offen: '.implode(' ', $points),
}, $settlementApplies && $booking->settled_at === null && $points !== [] ? 'settle' : null);
}
return $activities; return $activities;
} }
/**
* The tasks shown on the case: every open one, and the done ones of the stay (services, issues, follow-ups) as its record.
*
* @return iterable<BookingTask>
*/
private static function tasks(Booking $booking): iterable
{
return BookingTask::query()->where('booking_id', $booking->id)
->where(fn ($query) => $query->where('status', BookingTaskStatus::Open)
->orWhere(fn ($done) => $done->where('status', BookingTaskStatus::Done)->whereIn('kind', [BookingTaskKind::Service, BookingTaskKind::Issue, BookingTaskKind::FollowUp, BookingTaskKind::PayoutCheck, BookingTaskKind::OpenClaim])))
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get();
}
/**
* Own use, private stay or block (A6): only what such a case has – no contract, no reminders, no reviews.
*
* @param callable(ActivityState): ActivityState $later
* @return list<Activity>
*/
private static function internal(Booking $booking, bool $closed, callable $later): array
{
$kind = $booking->internal_kind;
$activities = [new Activity('intake', ($kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
foreach (self::channelTasks($booking) as $task) {
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
}
if ($kind !== InternalKind::Block && filled($booking->guest?->email)) {
$activities[] = new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $later($booking->confirmation_sent_at !== null ? ActivityState::Done : ActivityState::Later),
$booking->confirmation_sent_at ? 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : 'nur bei Bedarf', $booking->confirmation_sent_at === null && ! $closed ? 'sendDocuments' : null);
}
if ($booking->total !== null && $booking->total > 0) {
$paid = $booking->paidAmount();
$activities[] = new Activity('payment', 'Zahlung (ohne Erinnerungen)', $later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt');
}
foreach (self::tasks($booking) as $task) {
$activities[] = self::task($task);
}
$activities[] = new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $closed ? ActivityState::NotApplicable : ($booking->departure <= CarbonImmutable::today() ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
return [...$activities, ...self::closing($booking, $closed)];
}
/**
* An open task of the case and the action that settles it.
*/
private static function task(BookingTask $task): Activity
{
$action = match ($task->kind) {
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
BookingTaskKind::PortalChangeReported => 'change',
BookingTaskKind::BookingWish => 'decideWish',
BookingTaskKind::ArrivalDetails => 'arrivalDetails',
BookingTaskKind::CancellationRequest => 'end',
default => $task->kind->isPayment() ? null : 'completeTask',
};
$today = CarbonImmutable::today();
$state = match (true) {
$task->status === BookingTaskStatus::Done => ActivityState::Done,
$task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting,
$task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later,
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem,
default => ActivityState::Open,
};
$detail = $task->status === BookingTaskStatus::Done
? 'erledigt am '.$task->completed_at?->format('d.m.Y').($task->completed_by ? ' von '.$task->completed_by : '').($task->note ? ' · '.$task->note : '')
: trim(($state === ActivityState::Problem ? 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. · ' : '').($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->responsible ? ' · zuständig: '.$task->responsible : '').($task->note ? ' · '.$task->note : ''), ' ·');
return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action);
}
/** /**
* What the landlord should do next on this case, or null when nothing is up to him. * What the landlord should do next on this case, or null when nothing is up to him.
*/ */
@@ -179,16 +363,31 @@ public static function next(Booking $booking): ?Activity
public static function situation(Booking $booking): string public static function situation(Booking $booking): string
{ {
$today = CarbonImmutable::today(); $today = CarbonImmutable::today();
if ($booking->isInternal()) {
return implode(' · ', array_filter([
$booking->internal_kind?->getLabel() ?? 'Eigene Belegung',
$booking->occasion,
$booking->status === BookingStatus::Cancelled ? EndInternalCase::label($booking) : ($booking->departure <= $today ? 'beendet am '.$booking->departure->format('d.m.Y') : $booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')),
]));
}
if ($booking->portal_cancellation_requested_at !== null && $booking->isBinding()) {
return 'Gebucht über '.($booking->processChannel()?->name ?? 'ein Portal').' · Stornierung beim Portal veranlasst – bleibt gebucht, bis sie bestätigt ist';
}
$channel = $booking->processChannel()?->name; $channel = $booking->processChannel()?->name;
$kind = $booking->intake === IntakeKind::Booking ? 'Gebucht über '.($channel ?? 'ein Portal') : ($channel ? 'Anfrage über '.$channel : ($booking->source === 'website' ? 'Anfrage über die Webseite' : 'Anfrage')); $kind = $booking->intake === IntakeKind::Booking ? 'Gebucht über '.($channel ?? 'ein Portal') : ($channel ? 'Anfrage über '.$channel : ($booking->source === 'website' ? 'Anfrage über die Webseite' : 'Anfrage'));
$state = match ($booking->status) { $state = match ($booking->status) {
BookingStatus::Reserved => $booking->isHoldActive() ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr' : 'Zeitraum nicht reserviert', BookingStatus::Reserved => match (true) {
$booking->isHoldActive() => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr',
$booking->wish_at !== null => 'Buchungswunsch liegt vor – noch nicht verbindlich, Zeitraum nicht reserviert',
$booking->information_version > 0 => 'unverbindliche Auskunft gesendet, Zeitraum nicht reserviert',
default => 'Zeitraum nicht reserviert',
},
BookingStatus::OfferSent => $booking->isHoldActive() ? 'Angebot liegt beim Gast bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr' : 'Angebot abgelaufen', BookingStatus::OfferSent => $booking->isHoldActive() ? 'Angebot liegt beim Gast bis '.$booking->hold_expires_at->format('d.m., H:i').' Uhr' : 'Angebot abgelaufen',
BookingStatus::Confirmed => 'fest gebucht', BookingStatus::Confirmed => 'fest gebucht',
BookingStatus::DepositPaid => 'fest gebucht, Anzahlung erhalten', BookingStatus::DepositPaid => 'fest gebucht, Anzahlung erhalten',
BookingStatus::Paid => 'fest gebucht, bezahlt', BookingStatus::Paid => 'fest gebucht, bezahlt',
BookingStatus::Completed => 'abgeschlossen', BookingStatus::Completed => $booking->settled_at !== null ? 'Aufenthalt und Kaufmännisches abgeschlossen' : 'Aufenthalt abgeschlossen, kaufmännisch noch offen',
BookingStatus::Declined => 'ohne Buchung beendet', BookingStatus::Declined => 'ohne Buchung beendet',
BookingStatus::Expired => 'Frist abgelaufen, ohne Buchung beendet', BookingStatus::Expired => 'Frist abgelaufen, ohne Buchung beendet',
BookingStatus::Cancelled => 'storniert', BookingStatus::Cancelled => 'storniert',
+1 -1
View File
@@ -48,7 +48,7 @@ public function advance(Booking $booking): array
*/ */
private function step(Booking $booking): array private function step(Booking $booking): array
{ {
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->intake !== IntakeKind::Booking) { if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->information_version === 0 && $booking->intake !== IntakeKind::Booking) {
return $this->autoOffer->handle($booking); return $this->autoOffer->handle($booking);
} }
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Process;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Illuminate\Support\Collection;
/**
* The two closings of a case (package 9, operator decision): **stay closed** – the activities the stay needs are done or
* handed over (status "Abgeschlossen") – and **commercially settled** – claims, payments, refunds and portal payouts are
* clear (`settled_at`). They are separate statements: a stay can be closed while the payout of the portal is still
* outstanding, and open money never disappears because the stay is closed.
*
* Nothing here is a status of its own: what keeps a case open is derived from its tasks and its money.
*/
final class CaseClosure
{
public const AUTOMATIC = 'automatisch';
/**
* Open tasks of the stay itself (services, issues, a portal change to check) that keep the stay from being closed.
*
* @return Collection<int, BookingTask>
*/
public static function stayBlockers(Booking $booking): Collection
{
return BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->filter(fn (BookingTask $task): bool => $task->kind->blocksStay())->values();
}
/**
* What is still open commercially, in plain words (empty: nothing open). Only cases whose stay is closed or that were
* cancelled have a commercial closing; for all others the money is simply still running.
*
* @return list<string>
*/
public static function commercialPoints(Booking $booking): array
{
$points = [];
$tasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->filter(fn (BookingTask $task): bool => $task->kind->isCommercial());
if ($booking->status !== BookingStatus::Cancelled) {
$money = CaseMoney::of($booking);
$points = match ($money->collector()) {
Responsibility::Landlord => self::ourMoney($booking, $money),
Responsibility::Portal => self::portalMoney($booking, $money),
default => $booking->total !== null && $booking->total > 0 && $booking->paidAmount() < $booking->total
? ['Vereinbarte Zahlung noch offen: '.Money::format($booking->total - $booking->paidAmount()).' (ohne Erinnerungen).']
: [],
};
}
foreach ($tasks as $task) {
$points[] = 'Aufgabe offen: '.$task->label().'.';
}
return array_values(array_unique($points));
}
/**
* Closes or reopens the commercial side after anything that may have changed it (payment, task, stay closed).
* A settlement the landlord made by hand stays unless a commercial task is opened again.
*/
public static function refresh(Booking $booking): void
{
if (! in_array($booking->status, [BookingStatus::Completed, BookingStatus::Cancelled], true)) {
return;
}
$booking->unsetRelation('payments');
$points = self::commercialPoints($booking);
$openTasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->contains(fn (BookingTask $task): bool => $task->kind->isCommercial());
if ($booking->settled_at === null && $points === []) {
$booking->forceFill(['settled_at' => now(), 'settled_by' => self::AUTOMATIC, 'settled_note' => null])->save();
CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen – nichts mehr offen');
} elseif ($booking->settled_at !== null && ($openTasks || ($booking->settled_by === self::AUTOMATIC && $points !== []))) {
$booking->forceFill(['settled_at' => null, 'settled_by' => null, 'settled_note' => null])->save();
CaseLog::record($booking, 'settled', 'Kaufmännischer Abschluss wieder geöffnet: '.implode(' ', $points));
}
}
/**
* The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial
* tasks are closed with the same note. The reason is required and kept.
*/
public static function settle(Booking $booking, string $note, string $by): void
{
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
if ($task->kind->isCommercial()) {
$task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note);
}
}
$points = self::commercialPoints($booking);
$booking->forceFill(['settled_at' => now(), 'settled_by' => $by, 'settled_note' => mb_substr($note, 0, 500)])->save();
CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen (von Hand)', reason: $note, data: ['open_points' => $points], actor: $by);
}
/**
* @return list<string>
*/
private static function ourMoney(Booking $booking, CaseMoney $money): array
{
if ($booking->total === null) {
return ['Der Preis ist nicht bekannt.'];
}
$paid = $booking->paidAmount();
return array_values(array_filter([
$money->openForUs() > 0 ? 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.' : null,
$paid > $booking->total ? 'Überzahlung von '.Money::format($paid - $booking->total).' – Erstattung klären.' : null,
]));
}
/**
* @return list<string>
*/
private static function portalMoney(Booking $booking, CaseMoney $money): array
{
$portal = $booking->processChannel()?->name ?? 'dem Portal';
if ($booking->total === null) {
return ['Der Gesamtpreis laut '.$portal.' fehlt.'];
}
$payout = $money->payout();
return array_values(array_filter([
$payout['received'] === 0 ? 'Die Auszahlung von '.$portal.' ist noch nicht eingegangen.' : null,
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) > 0 ? 'Von der angekündigten Auszahlung fehlen noch '.Money::format((int) $payout['outstanding']).'.' : null,
$payout['difference'] > 0 ? 'Die Auszahlungsangaben weichen um '.Money::format($payout['difference']).' voneinander ab – ungeklärt.' : null,
]));
}
}
+23 -4
View File
@@ -5,6 +5,8 @@
use App\Enums\BookingStatus; use App\Enums\BookingStatus;
use App\Models\Booking; use App\Models\Booking;
use App\Models\Guest; use App\Models\Guest;
use App\Models\Tenant;
use App\Support\Settings;
/** /**
* Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake * Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake
@@ -53,6 +55,10 @@ public static function updated(Booking $booking): void
CaseLog::record($booking, 'guest', 'Gast zugeordnet: '.(Guest::query()->find($booking->guest_id)?->full_name ?? '–')); CaseLog::record($booking, 'guest', 'Gast zugeordnet: '.(Guest::query()->find($booking->guest_id)?->full_name ?? '–'));
} }
if (array_key_exists('information_version', $changes) && $booking->information_version > 0) {
CaseLog::record($booking, 'information', 'Unverbindliche Auskunft Version '.$booking->information_version.' gesendet'.($booking->information_valid_until ? ', Buchung anfragen bis '.$booking->information_valid_until->format('d.m.Y, H:i').' Uhr' : '').' – ohne Reservierung');
}
if (array_key_exists('offer_version', $changes) && $booking->offer_version > 0) { if (array_key_exists('offer_version', $changes) && $booking->offer_version > 0) {
CaseLog::record($booking, 'offer', 'Angebot Version '.$booking->offer_version.' gesendet'.($booking->hold_expires_at ? ', gültig bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : '')); CaseLog::record($booking, 'offer', 'Angebot Version '.$booking->offer_version.' gesendet'.($booking->hold_expires_at ? ', gültig bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : ''));
} elseif (array_key_exists('hold_expires_at', $changes) && $booking->hold_expires_at !== null && in_array($booking->status, BookingStatus::holding(), true) && ! array_key_exists('status', $changes)) { } elseif (array_key_exists('hold_expires_at', $changes) && $booking->hold_expires_at !== null && in_array($booking->status, BookingStatus::holding(), true) && ! array_key_exists('status', $changes)) {
@@ -78,9 +84,10 @@ public static function updated(Booking $booking): void
'arrival_info_sent_at' => 'Anreise-Informationen gesendet', 'arrival_info_sent_at' => 'Anreise-Informationen gesendet',
'review_requested_at' => 'Gast um eine Bewertung gebeten', 'review_requested_at' => 'Gast um eine Bewertung gebeten',
]; ];
$mailed = ['contact_requested_at', 'confirmation_sent_at', 'arrival_info_sent_at', 'review_requested_at'];
foreach ($facts as $column => $summary) { foreach ($facts as $column => $summary) {
if (array_key_exists($column, $changes) && $booking->{$column} !== null) { if (array_key_exists($column, $changes) && $booking->{$column} !== null) {
CaseLog::record($booking, 'fact', $summary); CaseLog::record($booking, 'fact', in_array($column, $mailed, true) ? self::mailFact($booking, $summary) : $summary);
} }
} }
@@ -93,17 +100,29 @@ public static function updated(Booking $booking): void
} }
} }
/**
* A fact that says a mail went to the guest – in test operation it went to the test address only, and the history says so.
*/
private static function mailFact(Booking $booking, string $summary): string
{
$redirect = Settings::mailRedirectFor(Tenant::query()->find($booking->tenant_id));
return $redirect === null ? $summary : $summary.' – Testbetrieb: nur an die Testadresse, nicht an den Gast';
}
private static function statusSummary(Booking $booking, mixed $from): string private static function statusSummary(Booking $booking, mixed $from): string
{ {
$from = $from instanceof BookingStatus ? $from : BookingStatus::tryFrom((string) $from); $from = $from instanceof BookingStatus ? $from : BookingStatus::tryFrom((string) $from);
return match ($booking->status) { return match ($booking->status) {
BookingStatus::Confirmed => $booking->wasChanged('accepted_at') && $booking->accepted_at !== null BookingStatus::Confirmed => ($booking->acceptance['via'] ?? null) === 'booking_wish' && $booking->wasChanged('acceptance')
? 'Buchungswunsch bestätigt – Buchung verbindlich'
: ($booking->wasChanged('accepted_at') && $booking->accepted_at !== null
? 'Angebot vom Gast angenommen – Buchung verbindlich' ? 'Angebot vom Gast angenommen – Buchung verbindlich'
: ($booking->caseType()->isExternallyBinding() ? 'Beim Portal verbindlich gebucht – übernommen' : 'Buchung verbindlich bestätigt'), : ($booking->caseType()->isExternallyBinding() ? 'Beim Portal verbindlich gebucht – übernommen' : 'Buchung verbindlich bestätigt')),
BookingStatus::DepositPaid => 'Anzahlung eingegangen', BookingStatus::DepositPaid => 'Anzahlung eingegangen',
BookingStatus::Paid => 'Vollständig bezahlt', BookingStatus::Paid => 'Vollständig bezahlt',
BookingStatus::Completed => 'Aufenthalt abgeschlossen', BookingStatus::Completed => 'Aufenthalt abgeschlossen'.($booking->settled_at === null ? ' – kaufmännische Punkte laufen weiter' : ''),
BookingStatus::Declined => 'Ohne Buchung beendet (abgelehnt'.($booking->declined_by ? ' durch '.($booking->declined_by === 'guest' ? 'den Gast' : 'uns') : '').')', BookingStatus::Declined => 'Ohne Buchung beendet (abgelehnt'.($booking->declined_by ? ' durch '.($booking->declined_by === 'guest' ? 'den Gast' : 'uns') : '').')',
BookingStatus::Expired => 'Ohne Buchung beendet (Frist abgelaufen)', BookingStatus::Expired => 'Ohne Buchung beendet (Frist abgelaufen)',
BookingStatus::Cancelled => 'Storniert', BookingStatus::Cancelled => 'Storniert',
+4
View File
@@ -23,6 +23,9 @@ final class ProcessProfile
public const CHANNEL = 'channel'; public const CHANNEL = 'channel';
/** Fixed by the case type (A6), not settable. */
public const CASE_TYPE = 'case_type';
/** Settings resolved when they are used instead of being frozen (documents capture their own template). */ /** Settings resolved when they are used instead of being frozen (documents capture their own template). */
public const LIVE = [ProcessSetting::ContractTemplate]; public const LIVE = [ProcessSetting::ContractTemplate];
@@ -117,6 +120,7 @@ public static function sourceLabel(string $source): string
self::TENANT => 'Ihre Standardeinstellung', self::TENANT => 'Ihre Standardeinstellung',
self::PROPERTY => 'Abweichung der Wohnung', self::PROPERTY => 'Abweichung der Wohnung',
self::CHANNEL => 'Abweichung des Portals', self::CHANNEL => 'Abweichung des Portals',
self::CASE_TYPE => 'fest für diese Vorgangsart',
'migration' => 'aus dem bisherigen Stand übernommen', 'migration' => 'aus dem bisherigen Stand übernommen',
default => 'Grundeinstellung', default => 'Grundeinstellung',
}; };
+8 -1
View File
@@ -49,7 +49,14 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
} }
} }
if ($intake !== IntakeKind::Booking) { if ($intake === IntakeKind::Internal) {
// Own use, private stays and blocks (A6): no rental documents, no payment reminders, no guest mails – fixed by
// the case type, not by a setting.
foreach ([ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages] as $setting) {
$values[$setting->value] = Responsibility::Nobody->value;
$sources[$setting->value] = ProcessProfile::CASE_TYPE;
}
} elseif ($intake !== IntakeKind::Booking) {
// A request is answered with our own offer and an internal case is ours anyway: the documents are ours. // A request is answered with our own offer and an internal case is ours anyway: the documents are ours.
$values[ProcessSetting::Documents->value] = Responsibility::Landlord->value; $values[ProcessSetting::Documents->value] = Responsibility::Landlord->value;
$sources[ProcessSetting::Documents->value] = ProcessProfile::SYSTEM; $sources[ProcessSetting::Documents->value] = ProcessProfile::SYSTEM;
+3 -2
View File
@@ -31,8 +31,9 @@ public static function items(): array
$cases = Booking::query() $cases = Booking::query()
->with(['guest', 'property', 'payments', 'importChannel', 'originChannel']) ->with(['guest', 'property', 'payments', 'importChannel', 'originChannel'])
->whereNull('archived_at') ->whereNull('archived_at')
->whereNotIn('status', [BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed]) ->whereNotIn('status', [BookingStatus::Declined, BookingStatus::Expired])
->where(fn ($query) => $query->whereNot('status', BookingStatus::Cancelled)->orWhereHas('tasks', fn ($tasks) => $tasks->where('status', 'open'))) // Closed stays and cancellations only with open tasks: follow-ups (money, damage) stay visible (package 9).
->where(fn ($query) => $query->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Completed])->orWhereHas('tasks', fn ($tasks) => $tasks->where('status', 'open')))
->get(); ->get();
foreach ($cases as $case) { foreach ($cases as $case) {
$next = CaseActivities::next($case); $next = CaseActivities::next($case);
@@ -0,0 +1,94 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Packages 8, 5 and 6 of UMSETZUNGSPLAN_v0.10:
* - external amounts of a case with kind, source and date (case_amounts) and the kind of every payment – a payment of
* the guest to us, one the portal reports as paid to it, a payout of the portal, a refund (package 8);
* - changes of a booking with who asked, why, from when and on which basis, agreed or proposed to the guest (package 5);
* a cancellation records its reason and who entered it; a portal cancellation can wait for the portal's confirmation;
* - own use, private stays and blocks as cases (package 6): their kind, occasion, tourist tax and – for blocks taken over
* from the old block list – the calendar identity the portals already know.
* Purely additive; existing payments count as payments of the guest to us.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('payments', function (Blueprint $table): void {
$table->string('kind', 20)->default('guest');
$table->string('source', 120)->nullable();
});
Schema::create('case_amounts', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('kind', 20);
$table->string('label', 150)->nullable();
$table->integer('amount');
$table->string('source', 120)->nullable();
$table->date('stated_on')->nullable();
$table->date('due_on')->nullable();
$table->string('note', 500)->nullable();
$table->string('recorded_by', 120)->nullable();
$table->timestamps();
$table->index(['booking_id', 'kind']);
});
Schema::create('booking_changes', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('status', 12);
$table->string('requested_by', 12);
$table->string('basis', 20)->nullable();
$table->text('reason')->nullable();
$table->date('effective_on')->nullable();
$table->timestamp('agreed_at')->nullable();
$table->string('agreed_by', 120)->nullable();
$table->json('before');
$table->json('after');
$table->json('consequences')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamp('decided_at')->nullable();
$table->string('decision_ip_hash', 64)->nullable();
$table->timestamp('applied_at')->nullable();
$table->timestamp('confirmation_sent_at')->nullable();
$table->string('recorded_by', 120)->nullable();
$table->timestamps();
$table->index(['booking_id', 'status']);
});
Schema::table('cancellations', function (Blueprint $table): void {
$table->text('reason')->nullable();
$table->string('recorded_by', 120)->nullable();
});
Schema::table('bookings', function (Blueprint $table): void {
$table->string('internal_kind', 16)->nullable();
$table->string('occasion', 255)->nullable();
$table->string('export_uid', 120)->nullable();
$table->unsignedTinyInteger('tourist_tax_persons')->nullable();
$table->string('tourist_tax_note', 255)->nullable();
$table->timestamp('portal_cancellation_requested_at')->nullable();
});
Schema::table('properties', function (Blueprint $table): void {
$table->unsignedInteger('tourist_tax_rate')->nullable();
});
}
public function down(): void
{
Schema::table('properties', fn (Blueprint $table) => $table->dropColumn('tourist_tax_rate'));
Schema::table('bookings', fn (Blueprint $table) => $table->dropColumn(['internal_kind', 'occasion', 'export_uid', 'tourist_tax_persons', 'tourist_tax_note', 'portal_cancellation_requested_at']));
Schema::table('cancellations', fn (Blueprint $table) => $table->dropColumn(['reason', 'recorded_by']));
Schema::dropIfExists('booking_changes');
Schema::dropIfExists('case_amounts');
Schema::table('payments', fn (Blueprint $table) => $table->dropColumn(['kind', 'source']));
}
};
@@ -0,0 +1,68 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Packages 7 and 9 (Prozessarchitektur v0.10): information "unter Vorbehalt" and the guest's booking wish for requests
* without a hold; preparation, stay and the two closings of a case (stay closed / commercially settled); stay tasks of a
* property and tasks that are not unique per kind (services, issues, follow-ups).
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('bookings', function (Blueprint $table) {
$table->unsignedSmallInteger('information_version')->default(0)->after('offer_version');
$table->dateTime('information_sent_at')->nullable()->after('information_version');
$table->dateTime('information_valid_until')->nullable()->after('information_sent_at');
$table->json('information')->nullable()->after('information_valid_until');
$table->dateTime('wish_at')->nullable()->after('information');
$table->json('wish')->nullable()->after('wish_at');
$table->string('arrival_time', 40)->nullable()->after('departure');
$table->dateTime('completed_at')->nullable();
$table->dateTime('settled_at')->nullable();
$table->string('settled_note', 500)->nullable();
$table->string('settled_by')->nullable();
});
Schema::table('properties', function (Blueprint $table) {
$table->json('stay_tasks')->nullable();
$table->boolean('asks_arrival_time')->default(false);
});
Schema::table('booking_tasks', function (Blueprint $table) {
$table->string('subject', 80)->default('')->after('kind');
$table->string('title')->nullable()->after('subject');
$table->string('responsible')->nullable()->after('title');
});
// The new unique key is added before the old one is dropped: MariaDB needs an index on booking_id for its foreign key.
Schema::table('booking_tasks', function (Blueprint $table) {
$table->unique(['booking_id', 'kind', 'subject']);
});
Schema::table('booking_tasks', function (Blueprint $table) {
$table->dropUnique(['booking_id', 'kind']);
});
}
public function down(): void
{
Schema::table('booking_tasks', function (Blueprint $table) {
$table->unique(['booking_id', 'kind']);
});
Schema::table('booking_tasks', function (Blueprint $table) {
$table->dropUnique(['booking_id', 'kind', 'subject']);
$table->dropColumn(['subject', 'title', 'responsible']);
});
Schema::table('properties', function (Blueprint $table) {
$table->dropColumn(['stay_tasks', 'asks_arrival_time']);
});
Schema::table('bookings', function (Blueprint $table) {
$table->dropColumn(['information_version', 'information_sent_at', 'information_valid_until', 'information', 'wish_at', 'wish', 'arrival_time', 'completed_at', 'settled_at', 'settled_note', 'settled_by']);
});
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 313 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 291 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 KiB

@@ -0,0 +1,89 @@
# Fachliche End-to-End-Abnahme
Wiederverwendbarer Katalog repräsentativer Geschäftsfälle der Prozessarchitektur v0.10. Jeder Fall ist aus Sicht der Vermieterin und des Gastes beschrieben. Durchgespielt wird er über die echten Dialoge, Gast-Links und den täglichen Lauf:
- `tests/Feature/EndToEndAcceptanceTest.php` (T01–T15)
- `tests/Feature/EndToEndStayAcceptanceTest.php` (T16–T25 ohne T23, dazu die Sonderfälle)
- `tests/Feature/TestOperationSmtpAcceptanceTest.php` (T23)
Screenshots liegen unter `Abnahme/<Datum>/`.
## Abnahmestand 02.11.2026
| Prüfart | Stand |
|---|---|
| **Automatisiert geprüft** | Alle 25 Fälle und 5 Sonderfall-Tests bestanden, Teil der Suite mit 700 grünen Tests. Branch `feature/aufenthalt`. |
| **Im Browser geprüft** | T07–T12, T14 (01.11.) sowie T16, T19, T22, T24 und die Konfiguration (02.11.). Chromium am Desktop, lokale Datenbankkopie, Testbetrieb, Mails nur ins Log. Keine Konsolenfehler. |
| **Auf dem Testsystem geprüft** | Nein: Für Pakete 7 und 9 gibt es keine Deployment-Freigabe. Die Migration der Pakete 5, 6 und 8 hat der Betreiber als erfolgreich gemeldet. |
| **Vom Betreiber fachlich abgenommen** | Nein. Die Bedienprobe mit der Vermieterin hat **nicht** stattgefunden; das Drehbuch steht in [GESAMTABNAHME_v0.10](GESAMTABNAHME_v0.10.md) §8. |
Nicht geprüft: Tablet und Smartphone, Darstellung der Mails in echten Mailprogrammen, MariaDB, echte Portal-Mails und -Feeds (nur synthetische Muster).
**Legende:** ✅ bestanden · – nicht durchgeführt · Spalten A = automatisiert, B = Browser, T = Testsystem, F = fachlich abgenommen
---
## Testfälle
| ID | Fall | Ausgangslage, Konfiguration | Handlungen | Soll | Ist | A | B | T | F | Nachweis |
|---|---|---|---|---|---|---|---|---|---|---|
| T01 | Eigene Anfrage, automatisch | Standard automatisch, Texte freigegeben | Anfrage über die Webseite | Angebot ohne Klick, nichts zu tun | wie Soll | ✅ | – | – | – | `test_t01_…` |
| T02 | Eigene Anfrage, manuell | Standard „Sie geben frei“, Portal mit Handsperre | Neu → Anfrage; Angebot senden; Gast nimmt an | gebucht, Vertrag, Sperraufgabe | wie Soll | ✅ | – | – | – | `test_t02_…` |
| T03 | Fehlende Gastdaten | automatisch, keine E-Mail | E-Mail eintragen, „automatisch weitermachen“ | Aufgabe, dann Angebot | wie Soll | ✅ | – | – | – | `test_t03_…` |
| T04 | FeWo-direkt-Direktbuchung | Kanal „Anlegen“, Portal kassiert | Buchungsmail; Preis laut Portal | ein A4-Vorgang, keine Mahnungen | wie Soll | ✅ | – | – | – | `test_t04_…` |
| T05 | Destination Solutions | wir kassieren | Neu → Portalbuchung | A3, Unterlagen und Zahlungsplan durch uns | wie Soll | ✅ | – | – | – | `test_t05_…` |
| T06 | Doppelte Portalmeldungen | Mail und Kalender | Mail, zweimal Abgleich | genau ein Vorgang | wie Soll | ✅ | – | – | – | `test_t06_…` |
| T07 | Buchungsänderung | gebuchte eigene Buchung | „Buchung ändern …“ | Folgenvorschau, Preis, Plan, Portalaufgabe, Verlauf | wie Soll | ✅ | ✅ | – | – | `test_t07_…`, `2026-11-01/T07-…` |
| T08 | Stornierung | eigene, Portal-, Anfrage | „Stornieren …“, Portalbestätigung | richtiger Weg je Lage | wie Soll | ✅ | ✅ | – | – | `test_t08_…`, `2026-11-01/T08-…` |
| T09 | Familienbesuch | Kurabgabe, Wäschepaket | Neu → Besuch | A6 79 €, kein Vertrag, keine Mahnung | wie Soll | ✅ | ✅ | – | – | `test_t09_…`, `2026-11-01/T09-…` |
| T10 | Wartungssperre | – | eintragen, verlängern, aufheben | keine Stornierung, Portale folgen | wie Soll | ✅ | ✅ | – | – | `test_t10_…`, `2026-11-01/T10-…` |
| T11 | Externe Zahlungen R09 | FeWo-direkt | Beträge laut Portal, Auszahlung | exakt, Differenz 5,51 € sichtbar | wie Soll | ✅ | ✅ | – | – | `test_t11_…`, `2026-11-01/T11-…` |
| T12 | Einstellungshierarchie | Standard, Wohnung, Portal | Vorgang umstellen | jede Ebene mit Herkunft | wie Soll | ✅ | ✅ | – | – | `test_t12_…`, `2026-11-01/T12-…` |
| T13 | Testbetrieb (Ablauf) | Testadresse, echter Mailer | Anfrage bis Storno | nur Testadresse | wie Soll | ✅ | – | – | – | `test_t13_…` |
| T14 | Änderung mit Zustimmung | gebuchte Buchung | Vorschlag, Gast nimmt an; vereinbarte Änderung | Bestätigung ≠ Zustimmung | wie Soll | ✅ | ✅ | – | – | `test_t14_…`, `2026-11-01/T14-…` |
| T15 | Bestandsübernahme Sperren | zwei manuelle Sperren | `cases:adopt-blocks` | A6, Export identisch | wie Soll | ✅ | – | – | – | `test_existing_manual_blocks_…` |
| **T16** | **Haltefrist 0: Auskunft und Buchungswunsch** | „Reservieren? nein“, manuell; Auskunftstext Arbeitsfassung | Anfrage; „Unverbindliche Auskunft prüfen und senden“ (Hinweis bestätigt); Gast öffnet Seite, „Buchung anfragen“ (zweimal); „Buchungswunsch bestätigen“ | Kalender frei, kein Annahmelink, Wunsch ist keine Buchung, eine Aufgabe; nach Bestätigung verbindlich, Vertrag, Portalaufgabe | wie Soll. Ein alter Link zeigt „nicht mehr aktuell“; eine unbeantwortete Auskunft endet nach Ablauf. | ✅ | ✅ | – | – | `test_t16_…` (2), `2026-11-02/T16-gast-auskunft.png`, `T16-buchungswunsch-*.png` |
| **T17** | **Verfügbarkeit hat sich geändert** | zwei Auskünfte für dieselben Tage; Portalimport; Preisänderung; veralteter Kalender | erster Gast wird bestätigt, zweiter fragt an; Import meldet Belegung; automatische Prüfung | keine Doppelbuchung, freundliche Absage, Mail und Postfach; Preis- und Kalenderbefund führt zur Aufgabe statt Automatik | wie Soll; bestätigt wird zum Preis der Auskunft | ✅ | – | – | – | `test_t17_…` (2) |
| **T18** | **Automatische und manuelle Bearbeitung** | automatisch, Texte freigegeben | zwei Anfragen, beide Gäste fragen an | Auskünfte automatisch, erster Wunsch sofort verbindlich, zweiter abgesagt; manuell: siehe T16 | wie Soll | ✅ | – | – | – | `test_t18_…` |
| **T19** | **Vollständiger A1-Ablauf bis zum Aufenthaltsabschluss** | Aufgaben je Wohnung (Schlüssel am Anreisetag, Endreinigung am Abreisetag), Anreisezeit erfragen | Anfrage, Angebot, Annahme, Anzahlung, Rest; täglicher Lauf (zweimal); Anreisedaten eintragen; Schlüssel erledigt; Reinigung „übergeben“; Lauf; Bewertungsbitte | Aufgaben einmalig und rechtzeitig, Anreise-Info, Aufenthalt wartet auf Reinigung, danach abgeschlossen und kaufmännisch abgeschlossen, Bewertungsbitte | wie Soll | ✅ | ✅ | – | – | `test_t19_…`, `2026-11-02/T19-*.png` |
| **T20** | **A4 mit Portalzahlung, Aufenthalt, späterer Auszahlung** | FeWo-direkt kassiert und schickt Anreise-Info | Preis laut Portal, „laut Portal bezahlt“; Läufe vor und nach dem Aufenthalt; Auszahlung erfassen | Status bleibt „Bestätigt“, Verlauf „noch kein Geld bei uns“; keine eigene Anreisemail, keine Mahnung; Aufenthalt abgeschlossen trotz offener Auszahlung; Prüfaufgabe wartet bis zur Fälligkeit; mit Auszahlung kaufmännisch abgeschlossen | wie Soll | ✅ | – | – | – | `test_t20_…` |
| **T21** | **A6-Familienaufenthalt** | Endreinigung auch bei Familie; Wäschepaket | Neu → Besuch; Läufe; Aufgaben erledigt; Zahlung 79 € | Bereitstellen und Reinigung als Aufgaben, keine Anreisedaten, keine Mails; Abschluss erst nach den Aufgaben; „Zahlung offen (ohne Erinnerungen)“ bis zur Zahlung | wie Soll | ✅ | – | – | – | `test_t21_…` |
| **T22** | **Aufenthalt abgeschlossen, Kaufmännisches offen** | nur Anzahlung bezahlt; Portalfall mit zwei Auszahlungsangaben | Läufe nach Abreise; Restzahlung; „Kaufmännisch abschließen“ mit Begründung | abgeschlossen, genau ein Nachläufer, bleibt in „Zu erledigen“; Zahlung schließt kaufmännisch; Differenz nur von Hand mit Begründung | wie Soll | ✅ | ✅ | – | – | `test_t22_…`, `2026-11-02/T22-kaufmaennisch-offen.png` |
| **T23** | **Testmail-Umleitung über SMTP-Empfänger** | Testbetrieb, Testadresse, isolierter SMTP-Empfänger | Ablauf automatisch, manuell, geplant; Cc/Bcc; im Livebetrieb eingereiht, im Testbetrieb versendet | jede Nachricht nur an die Testadresse, keine Originaladresse im SMTP-Umschlag, Verlauf „Testbetrieb“ | wie Soll (≥ 8 Nachrichten) | ✅ | – | – | – | `TestOperationSmtpAcceptanceTest` |
| **T24** | **Einstellungen aller Ebenen im ganzen Ablauf** | Standard automatisch mit Reservierung; Portal Ostseeklar (Anfragen) ohne Reservierung, manuell; Wohnung Anreise-Info 5 Tage, Anreisezeit erfragen | direkte Anfrage; Anfrage über Ostseeklar; Vorgang auf automatisch; Wunsch; Läufe | Angebot mit Reservierung bzw. Auskunft ohne; nach Umstellung automatische Auskunft und Bestätigung; Anreisedaten 7 Tage, Anreise-Info 5 Tage vorher; Übersicht nennt Herkunft | wie Soll | ✅ | ✅ | – | – | `test_t24_…`, `2026-11-02/T24-wirksame-einstellungen.png` |
| **T25** | **Änderung einer verbindlichen Portalbuchung** | A4 mit Portalpreis, Ostseeklar von Hand gesperrt | „Buchung ändern …“ bis 16.12., neuer Preis laut Portal 1.199 € | Portalpreis gilt ohne Neuberechnung, A4 bleibt, offen bei uns 0, Portalaufgabe neue Tage, Grundlage „Portal“ | wie Soll | ✅ | – | – | – | `test_t25_…` |
## Sonderfälle
| Fall | Erwartung | Ist | A | Nachweis |
|---|---|---|---|---|
| Portalgast ohne Kontaktdaten | Aufgabe „Anreisedaten“ mit „ggf. im Portal nachsehen“; nach Abreise „entfällt“ | wie Soll | ✅ | `test_special_cases_…` |
| Unbekannter Portalpreis | kaufmännischer Punkt „Gesamtpreis fehlt“, nie 0 | wie Soll | ✅ | `test_special_cases_…` |
| Stornierung kurz vor Anreise | Vorbereitungsaufgaben entfallen; Stornokosten halten den kaufmännischen Abschluss offen, bis sie erledigt sind | wie Soll | ✅ | `test_special_cases_…` |
| Abweichung und Folgeaufgabe | Abweichung hält den Abschluss auf (Abschluss von Hand mit Notiz); Folgeaufgabe bleibt am abgeschlossenen Vorgang | wie Soll | ✅ | `test_issues_hold_the_stay_up_…` |
| Alte Zahlungsstatus | Vorschau ändert nichts, `--apply` korrigiert mit Begründung | wie Soll | ✅ | `test_existing_payment_statuses_…` |
| Wiederholte Scheduler-Läufe | keine doppelten Aufgaben, Nachläufer oder Mails | wie Soll | ✅ | T19, T20, T22 (Läufe doppelt) |
| Fehlende oder verspätete Kalenderinformation | Wunsch nicht automatisch bestätigt, Befund „Kalenderstand … nicht aktuell“ | wie Soll | ✅ | T17 |
| Änderung nach versendeten Dokumenten | Bestätigung als Information, keine Zustimmung | wie Soll | ✅ | T13, T14 |
| Unterschiedliche Dokumentenverantwortung | Portal: „übernimmt das Portal“, keine eigenen Unterlagen | wie Soll | ✅ | T04, T20, `DocumentCompositionTest` |
| Unvollständige Zahlungen | Nachläufer und offener Punkt | wie Soll | ✅ | T22 |
| Offene Dienstleisteraufgaben | Aufenthalt wartet, Übergabe mit Notiz | wie Soll | ✅ | T19, T21 |
---
## Erkannte Bedienungsprobleme
| Problem | Stand |
|---|---|
| Direkt bestätigte Vorgänge zeigten „Auskunft“ und „Gast fragt an“ als erledigt | behoben (02.11.) |
| Nach der Abreise blieb „Bestätigung senden“ der nächste Schritt | behoben: Schritte vor dem Aufenthalt entfallen danach |
| „Als Nächstes“ zeigte den Detailtext eines anderen Schritts | behoben |
| Wohnungsformular „Aufgaben je Aufenthalt“ zu schmal | behoben |
| Bei einer noch unverbindlichen Anfrage steht in der Geldübersicht „Noch offen – zahlt der Gast an uns“ in Rot | offen, kosmetisch (aus Paket 8) |
| Portalaufgaben vergangener Zeiträume bleiben „zu tun“, bis jemand sie erledigt | offen; Vorschlag: nach der Abreise automatisch „entfällt“ |
| Der Dialog „Buchung ändern“ ist lang | offen (aus Paket 5) |
## Offene Arbeiten
1. Auslieferung auf das Testsystem nach Freigabe, MariaDB-Migration prüfen, dann diesen Katalog dort wiederholen (Spalte T).
2. Bedienprobe mit der Vermieterin nach Drehbuch (Spalte F).
3. Texte freigeben und rechtlich prüfen lassen ([GESAMTABNAHME](GESAMTABNAHME_v0.10.md) §4).
@@ -0,0 +1,127 @@
# Gesamtstand der Prozessarchitektur v0.10
Stand 02.11.2026 · Branch `feature/aufenthalt` · Pakete 1–9 umgesetzt, noch nicht ausgeliefert. Dieses Dokument dient dem Betreiber zur Bewertung ohne Codekenntnisse. Einzelheiten: [UMSETZUNGSERGEBNIS_P7_P9](UMSETZUNGSERGEBNIS_P7_P9.md) (und die früheren Ergebnisdokumente), [END_TO_END_ABNAHME](END_TO_END_ABNAHME.md), [KONFIGURATION_UND_WIRKSAMKEIT](KONFIGURATION_UND_WIRKSAMKEIT.md).
**Prüfstand:**
- 700 automatische Tests grün, darunter 25 durchgespielte Geschäftsfälle (T01–T25).
- Wichtige Oberflächen im Browser angesehen.
- **Nicht** auf dem Testsystem geprüft.
- **Keine** Bedienprobe mit der Vermieterin.
---
## 1. Vollständig unterstützte Geschäftsvorfälle
Jeder Vorfall ist **ein Vorgang** mit Ablauf, Aufgaben, Verlauf und einem Knopf für den nächsten Schritt.
| Vorfall | Von … bis |
|---|---|
| **Anfrage über die Webseite, Telefon oder Mail (A1)** | Anfrage → Angebot mit Reservierung → Annahme durch den Gast → Vertrag und Zahlungsplan → Zahlungen und Mahnaufgaben → Vorbereitung und Aufenthalt → Abschluss → Bewertungsbitte |
| **Anfrage ohne Reservierung (Haltefrist 0)** | Anfrage → unverbindliche Auskunft → Gast fragt die Buchung an → erneute Prüfung → automatisch oder von Ihnen bestätigt bzw. freundlich abgesagt |
| **Anfrage über ein Portal (A2)** | wie oben, mit den Einstellungen dieses Portals |
| **Beim Portal fest gebucht (A3–A5)** | Buchungsmail oder Kalender → ein Vorgang ohne zweites Angebot → Preis und Beträge laut Portal → eigene Unterlagen und Zahlungen nur, wo Sie zuständig sind → Aufenthalt → Abschluss, Auszahlung des Portals als Nachläufer |
| **Eigene Nutzung, Familie, Freunde, Sperre (A6)** | eintragen → Portale sperren → optional Aufenthaltsbestätigung, Leistungen, Kurabgabe → Abschluss; ohne Vertrag, Mahnung oder Bewertung |
| **Ändern** | mit dem Gast vereinbart (Grundlage festgehalten) oder als Vorschlag, dem der Gast zustimmt; Folgen werden vorher gezeigt |
| **Stornieren, Beenden** | ein Weg mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portalbuchungen erst nach Bestätigung im Portal |
| **Aufenthalt durchführen** | Anreisedaten, Schlüssel, Reinigung, Wäsche und gebuchte Leistungen als Aufgaben; Abweichungen festhalten; erledigt oder übergeben mit Notiz |
| **Abschluss** | „Aufenthalt abgeschlossen“ und „kaufmännisch abgeschlossen“ getrennt; offenes Geld bleibt als Aufgabe am Vorgang |
## 2. Sonderfälle, die funktionieren
- Gast ohne E-Mail oder ganz unbekannt: Die Aufgabe nennt, was fehlt. Bei Portalbuchungen kommt der Hinweis „im Portal nachsehen“.
- Portalpreis unbekannt oder nur als Gesamtbetrag: Nichts wird erfunden, der Abschluss nennt „Preis fehlt“.
- Widersprüchliche Auszahlungsangaben (5,51 € Differenz): Sie bleiben sichtbar und werden nur mit Begründung abgeschlossen.
- „Laut Portal bezahlt“ zeigt nicht mehr „Anzahlung erhalten“.
- Zwei Gäste wollen dieselben Tage: Nie entstehen zwei Buchungen, der zweite Gast bekommt eine Absage.
- Zeitraum zwischen Auskunft und Wunsch anderweitig gebucht, auch über einen Portalkalender: Es entsteht keine Buchung, der Gast bekommt eine Absage, Sie einen Hinweis.
- Preis geändert oder Kalender nicht aktuell: Es gibt keine automatische Bestätigung; Sie entscheiden und bestätigen zum Preis der Auskunft.
- Doppelter Klick oder alter Link: Es entsteht nichts doppelt, der Gast sieht einen verständlichen Hinweis.
- Stornierung kurz vor der Anreise: Die Vorbereitung entfällt, Kosten und Erstattung bleiben als Aufgaben.
- Schaden nach der Abreise: eine Folgeaufgabe, die den Abschluss nicht aufhält.
- Nächtlicher Lauf mehrfach: Es entstehen keine doppelten Aufgaben oder Mails.
- Testbetrieb: Jede Mail geht nur an die Testadresse, auch mit Kopie, Blindkopie und aus der Warteschlange. Der Verlauf sagt das.
## 3. Bestehende Einschränkungen
- Keine Melde- und Abgabefelder und keine Kurabgabe für Mietgäste (rechtlich offen); die Kurabgabe wird nur bei A6 berechnet.
- Keine Personal- oder Dienstleisterplanung. Dienstleister bekommen nichts automatisch; die Aufgabe nennt nur, wer zuständig ist.
- Einige Fristen sind fest: Vorbereitung 14 Tage voraus, Auszahlungsprüfung 14 Tage nach der Abreise.
- Ein Änderungsvorschlag und ein Buchungswunsch reservieren nichts, bis sie angenommen bzw. bestätigt sind.
- Portalbeträge werden von Hand eingetragen, ein Import aus Portalabrechnungen fehlt.
- Portalaufgaben vergangener Zeiträume müssen von Hand erledigt werden.
- Geprüft nur am Desktop. Smartphone und Tablet, echte Mailprogramme und MariaDB sind ungeprüft.
## 4. Noch freizugebende Texte und Bedingungen
| Was | Wo | Stand |
|---|---|---|
| **Mietbedingungen** (derzeit „[MUSTER …]“) und **Stornobedingungen** | Webseite › Texte bzw. Vorlagen | Mustertext. Gäste sehen ihn auf Angebot und Auskunft. |
| Bankverbindung | System › Betrieb | prüfen |
| Auskunft unter Vorbehalt | So arbeite ich › Dokumente | Arbeitsfassung; ohne Freigabe keine automatische Auskunft |
| Buchungsunterlagen für Portalbuchungen | So arbeite ich › Dokumente | Arbeitsfassung |
| Aufenthaltsbestätigung (Familie, Freunde) | So arbeite ich › Dokumente | Arbeitsfassung |
| Mails Änderungsbestätigung, Änderungsvorschlag, Buchungswunsch eingegangen/abgesagt | im System hinterlegt | Entwurf, bitte gegenlesen |
| FeWo-direkt-Vorlage (FW-01) und „gibt nur Portalbedingungen wieder“ | Vorlagen › Freigabe | offen seit Paket 3 |
| **Rechtliche Prüfung:** Annahme eines Angebots, Buchungswunsch, Zustimmung zu Änderungen, Einbeziehung der Bedingungen | – | offen |
## 5. Erforderliche Konfiguration für den Betrieb
1. **So arbeite ich:** Bearbeitung (zu Beginn „Sie geben frei“ empfohlen), Reservierung ja/nein, Gültigkeit, Zuständigkeiten.
2. **Je Portal** (Anfragen und feste Buchungen):
- FeWo-direkt: Zahlungen „Portal“; Anreise-Info je nach Absprache.
- Destination Solutions: Zahlungen „Wir“.
- „Erkannte Buchungen übernehmen“ zunächst auf **Beobachten** stellen.
3. **Je Wohnung:**
- Aufgaben je Aufenthalt (Endreinigung, Schlüssel …) mit Zuständigen.
- „Anreisezeit erfragen“.
- Kurabgabe-Satz.
- Zusatzleistungen.
4. **Texte und Bank** wie in Abschnitt 4.
5. **Testbetrieb:** Testadresse und Benachrichtigungsadressen prüfen. Erst nach Abnahme auf „Live“.
6. **Nach der Auslieferung** einmal als Vorschau, dann bewusst anwenden:
- `cases:adopt-blocks` (Altsperren)
- `cases:recheck-payment-status` (alte Zahlungsstatus)
- `channels:adopt-occupations` (Portalbelegungen)
## 6. Was den Produktivbetrieb tatsächlich blockiert
| # | Punkt | Warum |
|---|---|---|
| 1 | Freigabe und Auslieferung auf das Testsystem, Migrationen der Pakete 7/9 auf MariaDB, Wiederholung des Abnahmekatalogs dort | bisher nur lokal (SQLite) geprüft |
| 2 | Echte Mietbedingungen, Stornobedingungen, Bankverbindung | Gäste sähen sonst Mustertexte; im Livebetrieb sendet die Automatik ohne sie ohnehin nicht |
| 3 | Rechtliche Prüfung der Gastschritte (Abschnitt 4) | Vertragsschluss über Link bzw. Bestätigung |
| 4 | Bedienprobe mit der Vermieterin (Drehbuch §8) | fachliche Abnahme steht aus |
| 5 | Durchsicht der Vorschau-Befehle auf echten Daten (§5, Punkt 6) | Bestandsdaten nicht ungeprüft umstellen |
| 6 | Umschalten Testbetrieb → Live durch den Betreiber | bewusst manuell |
## 7. Spätere Verbesserungen (nicht blockierend)
- Fristen je Portal einstellbar machen (Auszahlung, Vorbereitung).
- Portalbeträge aus Mails oder Abrechnungen übernehmen.
- Melde- und Abgabefelder nach rechtlicher Klärung.
- Dienstleister per Mail benachrichtigen (über die Testbetriebs-Schranke).
- Portalaufgaben vergangener Zeiträume automatisch „entfällt“.
- Kosmetik:
- „Noch offen“ bei unverbindlichen Anfragen nicht rot zeigen.
- Dialog „Buchung ändern“ kürzen.
- Hinweis bei Widerspruch Portal-Buchungsmodell und Profil.
- Alte Spalten nach erfolgreicher Migration entfernen.
## 8. Drehbuch für die persönliche Abnahme (etwa 60 Minuten, Testsystem, Testbetrieb an)
| # | Handlung | Darauf achten |
|---|---|---|
| 1 | Startseite „Zu erledigen“ öffnen | Ist jede Zeile verständlich, führt der Knopf an die richtige Stelle? |
| 2 | Auf der Webseite eine Anfrage stellen (eigene Testadresse) | Mail im Testpostfach; Vorgang zeigt „Angebot prüfen und senden“ |
| 3 | Angebot senden, im Testpostfach annehmen | Bestätigung mit Vertrag, Portalaufgabe zum Sperren |
| 4 | So arbeite ich: „Reservieren? nein“, zweite Anfrage | Auskunft statt Angebot, Kalender bleibt frei; „Buchung anfragen“, dann „Buchungswunsch bestätigen?“; danach Einstellung zurücksetzen |
| 5 | Wohnung: Endreinigung (am Abreisetag, Reinigung …) und „Anreisezeit erfragen“ eintragen | Aufgaben erscheinen am gebuchten Vorgang |
| 6 | „Anreisedaten eintragen“, „Aufgabe erledigen …“ (Übergabe) | Notiz im Verlauf |
| 7 | „Abweichung oder Aufgabe festhalten …“: „Kaffeemaschine defekt“ | hält den Abschluss auf; „Aufenthalt abschließen …“ mit Notiz |
| 8 | FeWo-direkt-Buchung (Testmail) mit „Preis laut Portal“ und „laut Portal bezahlt“ | Status bleibt „Bestätigt“; Verlauf „noch kein Geld bei uns“ |
| 9 | Nach der Abreise: Auszahlung erfassen bzw. „Kaufmännisch abschließen …“ | Aufenthalt und Kaufmännisches getrennt verständlich? |
| 10 | Neu → Familie: Besuch mit Wäschepaket | keine Mails, Aufgaben „Bereitstellen“ |
| 11 | Buchung ändern und stornieren | Folgenvorschau verständlich? Kosten und Erstattung als Aufgabe |
| 12 | System › Wirksame Einstellungen | Herkunft der Werte nachvollziehbar? |
Ergebnis je Schritt (passt / unklar / falsch) bitte in [END_TO_END_ABNAHME](END_TO_END_ABNAHME.md) Spalte F festhalten.
@@ -0,0 +1,120 @@
# Konfiguration und Wirksamkeit
Dieses Dokument beschreibt, welche fachlichen Einstellungen es gibt, wo man sie vornimmt und wie sie sich vererben. Es zeigt auch, wie man nachprüft, dass sie in einem Vorgang wirklich angewandt wurden. Stand 02.11.2026, Pakete 1–9.
---
## 1. Wo man die Wirksamkeit sieht
| Werkzeug | Zeigt |
|---|---|
| **System › Wirksame Einstellungen** (Expertenansicht) | Für jede Wohnung und jeden Eingangsweg den Wert jeder Prozesseinstellung, der für einen **neuen** Vorgang gilt, mit Herkunft und Ort der Änderung. Eingangswege: direkte Anfrage, je Portal Anfrage und feste Buchung, A6. Neu ist die Zeile „Antwort auf eine Anfrage“: Angebot mit Reservierung, Auskunft unter Vorbehalt oder keine. Je Wohnung steht die Zeile „Aufenthalt“: Anreisezeit, Aufgaben je Aufenthalt, Kurabgabe. „Einen Vorgang prüfen“ zeigt dessen festgehaltenes Profil, eine Umstellung im Vorgang, das Dokument, das er jetzt braucht, und beide Abschlüsse mit den offenen Punkten. |
| **Vorgang › Ablauf** | Jede Aktivität mit Zustand: erledigt, übernimmt das Portal, zu tun, wartet, später oder entfällt. Dazu kommen Aufgaben mit Zuständigkeit und Erledigungsnotiz sowie beide Abschlüsse. |
| **Vorgang › Technische Angaben** (Experte) | eingefrorenes Abwicklungsprofil mit Herkunft je Wert |
| `php artisan process:settings-report` | alle Standards und Abweichungen als Text |
| `php artisan cases:recheck-payment-status` | Vorgänge, deren gespeicherter Zahlungsstatus der neuen Regel widerspricht (Vorschau) |
Nachweise: `test_t12_…`, `test_t24_…`; Screenshots `Abnahme/2026-11-01/T12-wirksame-einstellungen.png` und `Abnahme/2026-11-02/T24-wirksame-einstellungen.png`.
---
## 2. Vererbung
```
Grundeinstellung (im Code)
→ Ihr Standard System › So arbeite ich
→ Wohnung Wohnung bearbeiten › „Abweichende Abwicklung dieser Wohnung“ (Experte)
→ Portal je Eingangsart Portal bearbeiten › „Anfragen über dieses Portal“ / „Feste Buchungen über dieses Portal“
→ Vorgang Schalter „Läuft automatisch / Sie geben frei“, Wahl Angebot statt Auskunft, Aufgaben
```
- **Leer heißt „erbt“.** Ein bewusst gesetztes „nein“, „0“ oder „manuell“ ist ein eigener Wert.
- **Eingefroren beim Eingang.** Ein Vorgang behält die Werte von seinem Eingang. Ausnahme ist die Vertragsvorlage: Sie wird erst festgehalten, wenn das Dokument erstellt wird.
- **A6 fest:** Unterlagen, Zahlungen und Gastmails „Entfällt“.
- **Anfragen:** Unterlagen schicken immer wir.
- **Vorgangsart aus den wirksamen Werten:** A1/A2 Anfrage (direkt bzw. über Portal); A3 wir kassieren und schicken Unterlagen, A4 Portal kassiert, A5 Portal schickt Unterlagen; A6 intern.
---
## 3. Einstellbare Prozessparameter
| Einstellung | Standard | Übersteuerbar auf | Wirkung |
|---|---|---|---|
| Bearbeitung (automatisch / Sie geben frei) | Sie geben frei | Vermieter, Wohnung, Portal (Anfrage und Buchung), Vorgang | Angebote, Auskünfte und Unterlagen gehen ohne Klick hinaus, sobald nichts fehlt. Ein Buchungswunsch wird automatisch nur bestätigt, wenn die erneute Prüfung ohne jeden Befund ist (Paket 7). |
| Reserviert eine Anfrage den Zeitraum? | ja | Vermieter, Wohnung, Portal (Anfrage) | **ja:** Angebot mit Annahmelink, Zeitraum reserviert bis zum Ablauf. **nein:** unverbindliche Auskunft mit „Buchung anfragen“, kein Eintrag im Kalender, erneute Prüfung vor der Bestätigung (Paket 7). |
| Gültigkeit Angebot bzw. Auskunft | 48 Stunden | Vermieter, Wohnung, Portal (Anfrage) | Frist des Angebots und der Reservierung bzw. bis wann der Gast aus der Auskunft anfragen kann; danach endet die Anfrage ohne Buchung |
| Wer schickt Vertrag bzw. Unterlagen? | Wir | Vermieter, Wohnung, Portal (Buchung) | Portal → A5, keine eigenen Unterlagen |
| Wer kümmert sich um die Zahlungen? | Wir | Vermieter, Wohnung, Portal (Anfrage und Buchung) | Portal → A4: keine Mahnungen. „Laut Portal bezahlt“ ändert den Status nicht. Nach dem Aufenthalt entsteht die Aufgabe „Auszahlung des Portals prüfen“. |
| Wer schickt Anreise-Info und Bewertungsbitte? | Wir | Vermieter, Wohnung, Portal (Anfrage und Buchung) | Portal → „durch Portal (angekündigt)“, keine eigenen Mails |
| Anreise-Info Tage vorher | 3 | Vermieter, Wohnung | Zeitpunkt der Anreisemail. Die Anreisedaten werden 2 Tage davor geprüft. |
| Vertragsvorlage | Texte der Webseite | Wohnung, Portal, Vorgang (Zusammenstellung) | Inhalt von Angebot, Auskunft, Bestätigung und Unterlagen |
## 4. Weitere Einstellungen
| Einstellung | Wo | Ebene | Wirkung |
|---|---|---|---|
| **Anreisezeit erfragen** (neu) | Wohnung › Aufenthalt vorbereiten und abschließen | Wohnung | Fehlt die Anreisezeit, entsteht die Aufgabe „Anreisedaten beim Gast erfragen“. Kontaktdaten werden immer geprüft (nicht bei A6). |
| **Aufgaben je Aufenthalt** (neu) | Wohnung › Aufenthalt vorbereiten und abschließen | Wohnung | Je Zeile: Was, Wann (Tage vor Anreise / am Anreisetag / am Abreisetag), Wer, für welche Art von Aufenthalt (Gästebuchungen, Familie/Freunde, eigene Nutzung, Sperren). Daraus wird je Aufenthalt eine Aufgabe, die den Aufenthaltsabschluss aufhält, bis sie erledigt oder übergeben ist. |
| Gebuchte Leistungen | Wohnung › Zusatzleistungen | Wohnung | werden automatisch zu „Bereitstellen: …“ (nur bei eigenem Preis bzw. A6) |
| Kurabgabe je Person und Nacht | Wohnung › Preise | Wohnung | Position bei A6 |
| Erkannte Buchungen übernehmen | Portal | Kanal | Aus / Beobachten / Anlegen / Anlegen und weiter (Paket 4) |
| Was kommt über dieses Portal? | Portal | Kanal | Sofortbuchungsschutz (`CalendarClearance`) |
| Zusätzlich von Hand sperren | Portal | Kanal | Portalaufgaben mit Nachweisstufe |
| Freigabe der Dokumentarten | So arbeite ich › Dokumente | Vermieter | Arbeitsfassungen gehen nie automatisch hinaus. Neu ist die Dokumentart „Auskunft unter Vorbehalt“; solange sie nicht freigegeben ist, wird nicht automatisch geantwortet. |
| Freigabe einer Vorlage | Vorlagen › Freigabe | Vorlagenversion | Schutz vor unvereinbarten Bedingungen |
| Testbetrieb / Testadresse | System › Betrieb | Vermieter (Server-Vorgabe `FEWO_MAIL_REDIRECT_TO` gewinnt) | Jede ausgehende Mail nur an die Testadresse; der Verlauf vermerkt es. iCal-Abgleich bleibt aktiv. |
| Anzahlungsfrist, Bewertung nach Tagen | System › Betrieb | Vermieter | Zahlungsplan, Bewertungsbitte |
**Im einzelnen Vorgang übersteuerbar:**
- Bearbeitungsart
- Vorlage (im Dokument)
- bei Haltefrist 0 „Stattdessen verbindliches Angebot mit Reservierung senden“
- Preis bei der Bestätigung eines Wunsches (Preis der Auskunft oder ein niedrigerer heutiger Preis)
- eigene Aufgaben, Abweichungen und Folgeaufgaben; Aufgaben als erledigt, übergeben oder entfällt markieren
- Aufenthalt von Hand abschließen
- kaufmännischer Abschluss mit Begründung
**Fest im Code:**
- Vorbereitung 14 Tage im Voraus
- Anreisedaten-Prüfung 2 Tage vor der Anreise-Info
- Auszahlungsprüfung am Tag der Abreise + 14
- Abschluss in der Nacht nach der Abreise
---
## 5. Sonderfälle nur über Konfiguration
| Sonderfall | Konfiguration |
|---|---|
| Ein Portal leitet nur Anfragen weiter, die nichts blockieren sollen | Portal › Anfragen: „Reservieren? nein“ → Auskunft statt Angebot (T24) |
| Diese Wohnung wird von Hand bearbeitet, die andere automatisch | Wohnung › Abweichende Abwicklung: Bearbeitung |
| Schlüsselübergabe nur bei Gästen, Endreinigung auch bei Familie | Aufgaben je Aufenthalt mit „Bei“ (T19, T21) |
| Ein Gast soll trotz Haltefrist 0 ein bindendes Angebot erhalten | im Vorgang „Stattdessen verbindliches Angebot …“ |
| Portal schickt Anreise-Info selbst | Portal › Feste Buchungen: „Anreise-Info und Bewertung: Portal“ (T20) |
| Kleine Auszahlungsdifferenz akzeptieren | im Vorgang „Kaufmännisch abschließen …“ mit Begründung (T22) |
---
## 6. Nachweis an konkreten Vorgängen
| Konstellation | Erwartung | Beobachtet |
|---|---|---|
| Standard automatisch, Wohnung 24 h, direkte Anfrage | automatisch (Standard), 24 h (Wohnung) | identisch (T12) |
| FeWo-direkt feste Buchung, Zahlung Portal | A4, keine Mahnung, Status bleibt „Bestätigt“ trotz „laut Portal bezahlt“ | identisch (T04, T20) |
| Standard mit Reservierung, Ostseeklar-Anfragen ohne Reservierung und manuell | direkte Anfrage: Angebot und Reservierung. Ostseeklar: keine Reservierung, Aufgabe „Auskunft senden“ | identisch (T24) |
| Ostseeklar-Anfrage im Vorgang auf automatisch | Auskunft sofort, Wunsch automatisch bestätigt | identisch (T24) |
| Wohnung Anreise-Info 5 Tage, Anreisezeit erfragen | Anreisedaten-Aufgabe 7 Tage, Anreisemail 5 Tage vorher | identisch (T24) |
| Automatisch, aber Preis geändert bzw. Kalender veraltet | keine Automatik, Aufgabe mit Befunden | identisch (T17) |
| Familienbesuch | Unterlagen, Zahlungen, Mails „Entfällt“; Aufgaben je Aufenthalt „Familie“ wirken | identisch (T09, T21) |
---
## 7. Lücken und widersprüchliche Stellen
| Stelle | Beschreibung | Empfehlung |
|---|---|---|
| Buchungsmodell am Portal und Profil | „Was kommt über dieses Portal?“ und das Profil je Eingangsart können sich widersprechen. | Modell aus den Eingangsarten ableiten oder einen Hinweis im Portalformular zeigen. |
| Alte Spalten | `properties.hold_hours`, `pre_reservation_enabled`, `arrival_info_days_before` u. a. werden nicht mehr gelesen. | Nach erfolgreicher Migration auf Produktion entfernen. |
| Aufgaben je Aufenthalt | nur je Wohnung, nicht je Portal | ausreichend für 1–3 Wohnungen |
| Feste Fristen | Vorbereitung, Anreisedaten-Prüfung, Auszahlungsprüfung | einstellbar machen, wenn Erfahrungswerte vorliegen |
| Gültigkeit der Auskunft | dieselbe Einstellung wie das Angebot | bewusst so (E-026) |
@@ -0,0 +1,190 @@
# Umsetzungsergebnis Pakete 8, 5 und 6
Stand: 01.11.2026 · Branch `feature/abwicklung` (aufbauend auf `develop` = Pakete 1–4) · Grundlage: [UMSETZUNGSPLAN_v0.10](UMSETZUNGSPLAN_v0.10.md) §4.6, §5.6, §5.7, §5.9 und die Abnahmekriterien 5.x, 6.x, 8.x. Die normative Prozessarchitektur v0.10 wurde nicht verändert.
Begleitdokumente: [END_TO_END_ABNAHME.md](END_TO_END_ABNAHME.md) (fachliche Abnahme T01–T14) und [KONFIGURATION_UND_WIRKSAMKEIT.md](KONFIGURATION_UND_WIRKSAMKEIT.md).
---
## 1. Implementierungsstand je Paket
| Paket | Stand | Einschränkungen |
|---|---|---|
| **8 – Externe Beträge und Zahlungsstände** | umgesetzt | Kein Import von Portalbeträgen aus Mails oder Abrechnungen; erfasst wird von Hand. |
| **5 – Änderung, Storno, kontrollierter Abbruch** | umgesetzt | Kein Änderungsvorschlag an Portalgäste (geändert wird im Portal); keine PDF-Nachtragsurkunde, die Änderungsbestätigung ist eine Mail. |
| **6 – A6 im Vorgang** | umgesetzt | Der Kalender-Schnellweg ist ein Link je freiem Tag, keine Bereichsauswahl per Maus. |
Tests: **685 grün** (vorher 670; neu sind 15 fachliche Durchgangstests in `EndToEndAcceptanceTest`), Pint sauber. Die Abnahme über die Oberfläche lief im Browser auf einer Datenbankkopie. Ein Testsystem stand ohne Deployment-Freigabe nicht zur Verfügung.
---
## 2. Verfügbare Geschäftsfunktionen
### Paket 8 – Preise und Zahlungen
**Preis laut Portal eintragen.** Ein Dialog übernimmt den Gesamtpreis des Gastes als vereinbarten Preis. Aufklappbar folgen Einzelangaben mit Art, Bezeichnung, Betrag und bei Raten dem Fälligkeitsdatum:
- Übernachtung, Leistung, Rabatt, Gebühr/Steuer
- Sammelposten, nicht aufgeschlüsselt
- Provision / an das Portal gezahlt
- angekündigte Auszahlung, Rate laut Portal fällig
Zahlungen, die das Portal als bezahlt zeigt, lassen sich mit eintragen. Quelle und Stand werden gespeichert. Dieselbe Angabe ein zweites Mal wird nicht doppelt angelegt.
**Zahlungen mit Art.** Es gibt vier Arten:
- Gast hat an uns gezahlt
- Gast hat laut Portal ans Portal gezahlt
- Auszahlung vom Portal erhalten
- Erstattung an den Gast (wird automatisch abgezogen)
**Übersicht „Preis und Zahlungen“** im Vorgang:
- vereinbarter Gesamtpreis mit Herkunft
- je nach Zuständigkeit: „Noch offen – zahlt der Gast an uns“ oder „laut Portal bezahlt / noch beim Gast offen / Raten“
- angekündigte und erhaltene Auszahlungen; widersprüchliche Angaben stehen nebeneinander mit dem Hinweis „weichen um 5,51 € ab – ungeklärt“
- „Auf unserem Konto eingegangen“
- aufklappbar die Einzelangaben mit Summenprüfung („979,51 € = Gesamtpreis“)
**Zuständigkeit.** Zahlungserinnerungen entstehen nur, wenn wir die Zahlung einziehen. Bei Portalzahlung und bei A6 entstehen keine.
### Paket 5 – Ändern, Stornieren, Beenden
**„Buchung ändern …“** (bei A6 „Ändern oder verlängern …“) ändert Zeitraum, Personen, Leistungen und Preis. Vor dem Speichern zeigt der Dialog „Das ändert sich“ und „Folgen“:
- neu belegte bzw. wieder freie Nächte
- Aufgaben für Portale, die von Hand gesperrt werden
- alter und neuer Preis mit Differenz und Herkunft: neu berechnet (eigene Buchung, angepasste Positionen bleiben), neuer Betrag laut Portal (A3–A5) oder vereinbarte Miete mit Leistungen und Kurabgabe (A6)
- bisher bezahlt und danach offen; die Anzahlung bleibt, wenn sie bezahlt ist; neue Fälligkeit; Erstattungshinweis
**Zwei Wege:**
- *Mit dem Gast bereits vereinbart:* Die Änderung wirkt sofort und hält fest, wer sie wollte, warum, ab wann und auf welcher Grundlage (Telefon, E-Mail, persönlich, Portal). Auf Wunsch geht eine Bestätigung an den Gast. Sie informiert nur und gilt **nicht** als Zustimmung.
- *Dem Gast vorschlagen:* Bis zur Zustimmung ändert sich nichts. Der Gast bekommt einen signierten Link, nimmt an (mit Häkchen; Zeit und gehashte Adresse werden gespeichert) oder lehnt ab. Die Vermieterin wird informiert, der Vorschlag lässt sich zurückziehen.
**Folgen nach dem Speichern:**
- Kalender und Portalexport sind aktualisiert; Sperr- und Freigabeaufgaben entstehen.
- Der Zahlungsstatus wird neu berechnet.
- Bei Überzahlung entsteht die Aufgabe „Erstattung an den Gast prüfen“.
- Jede Änderung steht im Verlauf (`booking_changes`).
**„Stornieren …“ / „Beenden …“** wählt den Weg nach Lage:
| Lage | Ergebnis |
|---|---|
| Unverbindlich | Ohne Buchung beendet; Absage optional, Grund im Verlauf. |
| Eigene Buchung | Storniert mit Initiator, Grund und Erfasser. Stornokostenaufgabe nach der eingefrorenen Regel; Erstattungsaufgabe, wenn mehr gezahlt wurde als die Kosten. |
| Portalbuchung (A3–A5) | „Stornierung im Portal veranlassen“. Der Vorgang **bleibt gebucht** und der Zeitraum belegt, bis „Stornierung bestätigen …“ mit dem Häkchen „im Portal wirksam (geprüft)“ erledigt ist. Meldet das Portal die Stornierung selbst (Paket 4), heißt die Aktion „Stornierung übernehmen …“. |
| A6 | „Sperre aufheben …“ bzw. „Aufenthalt absagen …“: keine Stornierung, keine Kosten, keine Mails. Die Portale werden freigegeben. |
Der Stornolink des Gastes führt wie bisher zur Aufgabe am Vorgang und damit in denselben Stornoweg. „Status von Hand ändern“ bleibt in der Expertenansicht mit Pflichtbegründung und kann eine verbindliche Buchung nicht zurücksetzen.
### Paket 6 – Eigene Nutzung, Besuch, Sperre
**„Neu“ hat zwei zusätzliche Einstiege:**
- „Eigene Nutzung oder Besuch von Familie und Freunden“, mit der Frage „Wir selbst / Familie oder Freunde“
- „Eine Sperre ohne Gäste“
Erfasst werden Zeitraum und Anlass. Bei Besuch kommen Gäste, Personen, Leistungen, vereinbarte Miete (Standard 0 €), Kurabgabe-Personen und Befreiungen dazu.
**Schnellwege:**
- im Belegungsplan „+ eintragen“ an jedem freien Tag und „Eigene Nutzung / Sperre eintragen“;
- in der Liste „Sperrzeiten“ führt „Zeitraum sperren“ in denselben Dialog.
**Der A6-Vorgang:**
- belegt sofort; Portale werden gesperrt (Aufgaben oder Kalenderexport, im Export ohne Buchungsnummer und wie eine Sperre);
- hat eigene Aktivitäten: eingetragen, Portalsperren, Aufenthaltsbestätigung (optional), Zahlung ohne Erinnerungen, Aufenthalt bzw. Sperrzeit;
- ohne Mietvertrag, Mahnungen, Bewertungsanfrage, Anreisemail und Marketing; das A6-Profil setzt diese Zuständigkeiten fest auf „Entfällt“.
**Kurabgabe:**
- als eigene Position „Kurabgabe (N Personen × M Nächte)“;
- der Satz je Person und Nacht steht an der Wohnung unter Preise, Feld „Kurabgabe je Person und Nacht“;
- Befreiungen trägt man im Vorgang als Text ein;
- keine kommunale Tariflogik.
**Aufenthaltsbestätigung:** eine eigene Dokumentart mit PDF ohne Mietvertrag und Mail `StayConfirmed`. Sie wird über die Zusammenstellung aus Paket 3 versendet und ist eine Arbeitsfassung, bis sie freigegeben ist.
**Bestandsübernahme `cases:adopt-blocks`:**
- Ohne Zusatz ist es eine Vorschau; mit `--apply` werden die Sperren übernommen.
- Ein zweiter Lauf übernimmt nichts doppelt; `--revert=<Bericht>` macht die Übernahme rückgängig.
- Bisherige manuelle Sperren werden zu A6-Vorgängen. Die Sperre bleibt als gelöschte Spur erhalten.
- **Der Kalenderexport ist danach identisch:** gleiche Kennung `block-…`, gleiche Felder, gleicher Zeitstempel. Es entstehen keine Portalaufgaben und keine Mails.
### Übergreifend – Wirksame Einstellungen
Neue Expertenseite **System › Wirksame Einstellungen**:
- je Wohnung und Eingangsweg (direkte Anfrage, jedes Portal mit Anfrage und fester Buchung, A6) jede Prozesseinstellung mit wirksamem Wert, Herkunft und dem Ort, an dem sie eingestellt wird;
- „Einen Vorgang prüfen“ zeigt das tatsächlich angewandte, eingefrorene Profil und die Entscheidung im Vorgang.
Details stehen in [KONFIGURATION_UND_WIRKSAMKEIT.md](KONFIGURATION_UND_WIRKSAMKEIT.md).
---
## 3. Technische Konsolidierungen und Architekturentscheidungen
| Entscheidung | Begründung |
|---|---|
| **Kein neues Zahlungsmodell, sondern `payments.kind`** (`PaymentKind`). `Booking::paidAmount()` zählt nur Zahlungen des Gastes; `paidToUs()`, `paidViaPortal()` und `payoutsReceived()` sind getrennt. | Bestehende Zahlungen bleiben gültig (Standard „Gast an uns“), Mahnläufe und Status arbeiten weiter. Auszahlungen zählen nicht doppelt. |
| **Beträge als Angaben (`case_amounts`, `AmountKind`)**, nie verrechnet; `App\Pricing\CaseMoney` beantwortet die vier Geldfragen. | Vorgabe K01/E-014/E-015: keine Scheingenauigkeit, Widersprüche bleiben sichtbar. |
| **Eine Aktion `ChangeBooking`** mit `preview`, `apply`, `propose`, `accept`, `decline`, `withdraw`; Änderungen als `booking_changes` mit vorher/nachher und Folgen. | Ein Weg für A1–A6; Vorschau und Ausführung rechnen identisch. Kalender und Portalaufgaben folgen über den bestehenden `BookingObserver`. |
| **Gastzustimmung nur über den signierten Link** (`ChangeBasis::GuestLink` ist nur dort möglich). Eine Änderungsbestätigung setzt `confirmation_sent_at`, nicht `decided_at`. | Auftrag §5: Eine versendete Bestätigung ist keine Zustimmung. |
| **Portalstorno zweistufig** (`portal_cancellation_requested_at`, `CancelBooking::confirmOnPortal`). | Abnahme 5.5: erst storniert, wenn im Portal wirksam; nichts wird still freigegeben. |
| **A6 ist ein `Booking`** mit `intake = internal`, `internal_kind`, Quelle `internal`; das Profil setzt Unterlagen, Zahlungen und Gastmails fest auf `Responsibility::Nobody`. | Ein Vorgangskern, keine zweite Verwaltung. Die Sperrliste bleibt nur für Altbestand und Portalsperren. |
| **`bookings.export_uid`** für übernommene Sperren. | Der Portalexport bleibt identisch (Abnahme 6.3). |
| **Kurabgabe als `QuoteLineType::TouristTax`**, Satz an der Wohnung. | Empfehlung B1 und Auftrag: gepflegter Satz, Befreiung manuell, keine Rechtslogik. |
| **Befehle melden Fehler eines Mandanten sichtbar.** Der `TenantRunner` protokolliert Fehler nur; die Übernahmebefehle prüfen deshalb die Zahl der erfolgreichen Läufe. | Beim Test gefunden: Ohne diese Prüfung meldete ein Fehler „keine Sperren“. |
---
## 4. Erfüllte Abnahmekriterien
| ID | Kriterium | Nachweis | Ergebnis |
|---|---|---|---|
| 5.1 | Änderung nach Buchung (A1) mit Folgenvorschau; danach Kalender, Portalaufgaben, Zahlungsplan, Verlauf | T07; Screenshot `Abnahme/2026-11-01/T07-aendern-folgen.png` | erfüllt |
| 5.2 | Änderung extern (A4) mit Portalbetrag, keine Neuberechnung | `ChangeBooking::price` (Portalzweig); Dialogfeld „Neuer Gesamtpreis laut Portal“ | erfüllt (kein eigener Durchgangstest; durch T04/T11 und Vorschaulogik abgedeckt) |
| 5.3 | Abbruch unverbindlich | T08 (Anfrage) | erfüllt |
| 5.4 | Abbruch verbindlich mit Initiator, Grund, Kosten, Erstattung | T08 (eigene Buchung) | erfüllt |
| 5.5 | Abbruch extern: Portalaufgabe, erst storniert nach Wirksamkeit | T08 (Portalbuchung), `PortalBookingTest` | erfüllt |
| 5.6 | Storno durch Gast im selben Weg | bestehender `CancellationPolicyTest`, Aufgabe → „Stornieren …“ | erfüllt |
| 6.1 | Private Überlassung mit Gästen, Leistungen, Kurabgabe, ohne Vertrag/Bewertung/Marketing | T09; Screenshots T09 | erfüllt |
| 6.2 | Wartungssperre, verlängern, aufheben ohne Storno | T10; Screenshot T10 | erfüllt |
| 6.3 | Bestandsmigration, Export identisch | Test `test_existing_manual_blocks_become_cases_without_changing_the_portal_calendar` | erfüllt |
| 8.1 | R09 exakt erfassbar, nichts erfunden oder doppelt | T11; Screenshot T11 | erfüllt |
| 8.2 | Bezahlt laut Portal ≠ eingegangen; offen nur beim Einziehenden | T11, T04 | erfüllt |
---
## 5. Tests und verbleibende Risiken
- **Automatisiert:** 685 Tests, 3889 Zusicherungen, alle grün. Darunter T01–T14 und 6.3 als Durchgangstests über die echten Dialoge (Livewire) und die Gast-Links (HTTP).
- **Browser:** Chromium mit Zwei-Faktor-Anmeldung auf einer Kopie der lokalen Datenbank. Geprüft: Ändern mit Folgen, R09-Übersicht, Neu-Dialog Besuch, Familienbesuch, Sperre aufheben, Wirksame Einstellungen, Gastseite Änderungsvorschlag. Keine Konsolenfehler.
- **Gefunden und behoben:**
- A6 zeigte „Über: internal“;
- A6 zeigte den Schalter „Sie geben frei“ und eine Vorlage;
- Vergabe der Vorgangsnummer bei der Bestandsübernahme;
- verschluckte Fehler in Übernahmebefehlen;
- fehlende Imports durch Windows-Zeilenenden.
**Risiken:**
- Bei Portalzahlung springt der Status auf „Anzahlung erhalten / bezahlt“, sobald „laut Portal bezahlt“ eingetragen ist. Im Verlauf steht dann „Anzahlung eingegangen“, obwohl kein Geld auf unserem Konto ist. Die Übersicht ist korrekt, der Statusname missverständlich (→ §7).
- Ein Änderungsvorschlag reserviert die neuen Nächte nicht. Bei der Annahme wird die Verfügbarkeit neu geprüft und gegebenenfalls freundlich abgelehnt.
- Für die Änderungsbestätigung und die Aufenthaltsbestätigung ist die Mail jeweils eine Arbeitsfassung; sie braucht eine Prüfung bzw. Freigabe durch den Betreiber.
- Die Migration auf MariaDB ist nicht geprüft (wie schon bei den Paketen 1–4).
- Ein Testsystem wurde nicht genutzt; es gibt keine Deployment-Freigabe.
---
## 6. Migrationsbedarf und Auswirkungen auf Bestandsdaten
- Die Migration `2026_11_04_090000_create_amounts_changes_and_internal_cases` ist rein additiv. Bestehende Zahlungen werden zu „Gast an uns“.
- **Manuelle Sperren:** `php artisan cases:adopt-blocks` zuerst als Vorschau, dann mit `--apply`; vorher eine Datenbanksicherung. Der Bericht liegt unter `storage/app/private/block-adoptions/`, die Rücknahme geht mit `--revert`. Ohne diesen Lauf bleiben die Altsperren wie bisher wirksam; neue Sperren entstehen nur noch als A6-Vorgang.
- Portalbuchungen, die schon storniert wurden, bleiben storniert. Die neue Zweistufigkeit gilt nur für künftige Stornierungen.
---
## 7. Noch erforderliche fachliche Entscheidungen
| Frage | Vorschlag | Bis dahin |
|---|---|---|
| **Statusname bei Portalzahlung:** Soll „laut Portal bezahlt“ den Status „Anzahlung erhalten/Bezahlt“ setzen? | Eigene Bezeichnung „laut Portal bezahlt“ oder keinen Statuswechsel. Gehört fachlich zum Abschluss-Gate B4 (Paket 9). | Statuswechsel wie bei Gastzahlungen. |
| **B3 Änderung nach Verbindlichkeit:** Wann ist ein Vorschlag mit Zustimmung Pflicht (z. B. bei Preiserhöhung)? | Beide Wege sind da. Eine Pflichtregel braucht eine fachliche bzw. rechtliche Entscheidung. | Die Vermieterin wählt den Weg. |
| **Texte:** Änderungsbestätigung, Änderungsvorschlag, Aufenthaltsbestätigung | Prüfen und freigeben (Aufenthaltsbestätigung unter So arbeite ich › Dokumente). | Arbeitsfassungen. |
| **Kurabgabe-Satz** je Wohnung | Den Satz der Gemeinde eintragen (Wohnung › Preise). | Keine Berechnung ohne Satz. |
| **B1, B4, B5** | Unverändert offen; B1 ist mit dem gepflegten Satz praktisch beantwortet. | – |
Pakete 7 und 9 wurden nicht begonnen.
@@ -0,0 +1,143 @@
# Umsetzungsergebnis Pakete 7 und 9
Stand: 02.11.2026 · Branch `feature/aufenthalt` (aufbauend auf `develop` = Pakete 1–6 und 8, Commit `3bcfc09`) · Grundlage: [UMSETZUNGSPLAN_v0.10](UMSETZUNGSPLAN_v0.10.md) §5.8, §5.10, Abnahmekriterien 7.x und 9.x, Abschlussauftrag vom 02.11.2026. Die normative Prozessarchitektur v0.10 wurde nicht verändert.
Begleitdokumente: [GESAMTABNAHME_v0.10](GESAMTABNAHME_v0.10.md) (Bewertung ohne Codekenntnisse), [END_TO_END_ABNAHME](END_TO_END_ABNAHME.md) (T01–T25), [KONFIGURATION_UND_WIRKSAMKEIT](KONFIGURATION_UND_WIRKSAMKEIT.md).
---
## 1. Stand je Paket
| Paket | Stand | Einschränkungen |
|---|---|---|
| **7 – Haltefrist 0: Auskunft und Buchungswunsch** | umgesetzt | Die Auskunft gilt so lange, wie die Einstellung „Gültigkeit Angebot/Auskunft“ sagt (eine eigene Frist gibt es nicht, E-026). Der Buchungswunsch reserviert nichts, bis bestätigt ist. |
| **9 – Aufenthalt und Abschluss** | umgesetzt | Keine Melde- und Abgabefelder (rechtlich offen, P04). Keine Personal- oder Dienstleisterplanung, nur Aufgaben am Vorgang. Die Frist der Auszahlungsprüfung ist fest: Abreise + 14 Tage. |
| **Abschnitt 5 – Zahlungsstatus bei Portalzahlung** | behoben | Gespeicherte Status werden nur über `cases:recheck-payment-status` korrigiert (Vorschau, dann `--apply`). |
| **Abschnitt 6 – Testbetrieb** | geprüft und ergänzt | Der Nachweis lief über einen echten, isolierten SMTP-Empfänger (T23). Ein Gerät mit Mailprogramm habe ich nicht geprüft. |
**Tests:** 700 Tests mit 4200 Zusicherungen sind grün; vorher waren es 685. Neu sind die Durchgangstests T16–T25 mit Sonderfällen (`EndToEndStayAcceptanceTest`) und T23 (`TestOperationSmtpAcceptanceTest`). Pint ist sauber. Die Browserprüfung lief auf einer Datenbankkopie (Abschnitt 5).
---
## 2. Geschäftsfunktionen
### Paket 7 – Anfrage ohne Haltefrist
| Schritt | Verhalten |
|---|---|
| Anfrage | Bei „Reservieren? nein“ entsteht eine Anfrage ohne Reservierung. Der Kalender bleibt frei. Der Gast liest im Formular und in der Eingangsmail, dass er eine Auskunft bekommt. |
| Auskunft | „Unverbindliche Auskunft prüfen und senden“ geht automatisch oder per Klick, je nach wirksamer Einstellung. Sie läuft über die Zusammenstellung aus Paket 3 (Dokumentart „Auskunft unter Vorbehalt“, Arbeitsfassung bis zur Freigabe). Gast-Mail und Gastseite sagen: „Dies ist noch keine Buchung und keine Reservierung“, mit dem Prüfstand (Datum, Uhrzeit). Es gibt keinen Annahmelink, nur „Buchung anfragen“. Eine neue Auskunft ersetzt die alte: Der alte Link funktioniert nicht mehr, und ein Wunsch darauf verfällt. |
| Buchungswunsch | Der Gast bestätigt die Bedingungen und klickt „Buchung anfragen“. Unter Sperre (Wohnung + Vorgang) wird erneut geprüft: ganzer Zeitraum frei, Kalenderimporte aktuell (vorher wird ein Abruf versucht), Preis wie in der Auskunft, Gastdaten vollständig, Zusammenstellung der Bestätigung ohne Prüfpunkte. Festgehalten werden Zeitpunkt, gehashte Adresse, genannter und heutiger Preis sowie die Befunde. |
| Entscheidung | Automatisch und alles in Ordnung: Die Buchung wird sofort verbindlich, Vertrag und Bestätigung gehen hinaus. Sonst entsteht die Aufgabe „Buchungswunsch bestätigen?“ mit den Befunden, und der Gast erhält „eingegangen, noch nicht verbindlich“. Der Dialog bestätigt zum Preis der Auskunft, zum niedrigeren heutigen Preis oder sagt ab. Ein höherer Preis braucht eine neue Auskunft. |
| Konflikt | Ist der Zeitraum inzwischen belegt (eigene Buchung, anderer Gast, Kalenderimport), entsteht keine Buchung. Der Gast bekommt eine freundliche Absage, die Vermieterin eine Mail und einen Postfacheintrag. Bei einem offenen Wunsch zeigt die Aufgabe live „Zeitraum inzwischen belegt – bitte absagen“. |
| Wiederholung, alter Link, Ablauf | Ein zweiter Klick bleibt ohne Wirkung. Ein alter oder abgelaufener Link zeigt einen verständlichen Hinweis. Eine unbeantwortete Auskunft endet nach Ablauf als „ohne Buchung beendet“, die Vermieterin wird benachrichtigt. |
| Widerspruch L5 | Er ist beseitigt: Ohne Haltefrist ist die Auskunft der vorgesehene Weg. „Stattdessen verbindliches Angebot mit Reservierung senden“ bleibt als bewusste Entscheidung im einzelnen Vorgang, mit ausdrücklicher Bestätigung. |
### Paket 9 – Aufenthalt
| Bereich | Verhalten |
|---|---|
| Vorbereitung (täglicher Lauf) | Aufenthalte der nächsten 14 Tage werden vorbereitet, einmal je Vorgang und Aufgabe, egal wie oft der Lauf läuft. Pflichtaufgaben je Aufenthalt und Termine passen sich an, wenn sich der Zeitraum ändert. |
| Anreisedaten | Fehlen Kontakt (E-Mail oder Telefon) oder die Anreisezeit (falls die Wohnung danach fragt), entsteht rechtzeitig die Aufgabe „Anreisedaten beim Gast erfragen“: 2 Tage vor dem Versand der Anreise-Information. Bei Portalbuchungen steht der Hinweis „ggf. im Portal nachsehen“ dabei. Liegen die Angaben vor („Anreisedaten eintragen“), schließt sich die Aufgabe selbst. |
| Leistungen und Dienstleister | Aufgaben je Wohnung werden eingestellt, z. B. Schlüsselübergabe am Anreisetag oder Endreinigung am Abreisetag durch „Reinigung Müller“, je nach Art des Aufenthalts. Gebuchte Leistungen unseres eigenen Preises werden zu „Bereitstellen: 3 × Wäschepaket“. Stornierungen lassen die Vorbereitungsaufgaben entfallen. |
| Portal übernimmt | Ist die Anreise-Information Sache des Portals, steht dort „durch FeWo-direkt (angekündigt) – eine Zustellung ist damit nicht nachgewiesen“. Es geht keine eigene Mail hinaus, und es gibt keine Mahnungen. |
| Während des Aufenthalts | „Abweichung oder Aufgabe festhalten …“ kennt drei Arten. Eine Abweichung oder ein Problem muss vor dem Abschluss geklärt sein. Eine Leistung wird vorbereitet. Eine Folgeaufgabe hält den Abschluss nicht auf. „Aufgabe erledigen …“ kennt drei Ergebnisse: erledigt, übergeben an jemanden oder entfällt; immer mit Notiz im Verlauf. Erledigte Aufgaben bleiben im Ablauf als Nachweis sichtbar. |
### Paket 9 – Zwei Abschlüsse
| Aussage | Wann | Was bleibt |
|---|---|---|
| **Aufenthalt abgeschlossen** (Status „Abgeschlossen“) | Automatisch in der Nacht nach der Abreise, sobald keine Aufgabe des Aufenthalts mehr offen ist (Leistung, Abweichung, gemeldete Portaländerung). Sonst „Aufenthalt abschließen …“ von Hand: Offene Aufenthaltsaufgaben werden mit Notiz als erledigt bzw. übergeben vermerkt. Offenes Geld hält den Abschluss nicht auf. | Offene Forderungen werden zur Aufgabe „Offenen Betrag nach der Abreise klären“, sofern keine Mahnaufgabe läuft. Eine ausstehende Portalauszahlung wird zu „Auszahlung des Portals prüfen“ (fällig Abreise + 14 Tage, bis dahin „wartet“). Schäden sind Folgeaufgaben. Alles bleibt am selben Vorgang und in „Zu erledigen“. |
| **Kaufmännisch abgeschlossen** (`settled_at`) | Automatisch, sobald nichts mehr offen ist. Offen heißt hier: ein Betrag vom Gast, eine Überzahlung, eine fehlende oder unvollständige Auszahlung, widersprüchliche Auszahlungsangaben, ein unbekannter Portalpreis, eine bei A6 vereinbarte, unbezahlte Zahlung oder eine offene Geldaufgabe (Mahnung, Stornokosten, Erstattung, Auszahlung, Forderung). Von Hand „Kaufmännisch abschließen …“ nur mit Begründung, z. B. „Differenz 5,51 € akzeptiert“. Gilt auch für stornierte Vorgänge (Stornokosten, Erstattung). | Kommt später eine neue Geldaufgabe hinzu, öffnet sich der automatische Abschluss wieder, mit Eintrag im Verlauf. |
Die Vorgangsseite zeigt beide Aussagen als Aktivität mit den offenen Punkten. Der Satz oben lautet z. B. „Aufenthalt abgeschlossen, kaufmännisch noch offen“.
### Abschnitt 5 – Zahlungsstatus
| Aussage | Wo sie steht |
|---|---|
| Gast hat laut Portal bezahlt | Zahlungsart „laut Portal ans Portal“. Verlauf: „Laut FeWo-direkt hat der Gast 979,51 € an das Portal gezahlt – noch kein Geld bei uns“. Aktivität: „Zahlung des Gastes an FeWo-direkt“, übernimmt das Portal. |
| Portal plant eine Auszahlung | Angabe „angekündigte Auszahlung“ (Paket 8); Aktivität „Auszahlung von … auf unser Konto“ (wartet). |
| Geld vom Portal ausgezahlt | Zahlungsart „Auszahlung vom Portal“. Verlauf: „Auszahlung von FeWo-direkt auf unserem Konto eingegangen“. Die Aufgabe „Auszahlung prüfen“ schließt sich. |
| Zahlung des Gastes bei uns eingegangen | Nur das ändert den Status (Bestätigt → Anzahlung erhalten → Bezahlt). Erledigte Mahnaufgaben schließen sich mit der Zahlung. |
| Weitere Forderungen oder Erstattungen offen | Punkte des kaufmännischen Abschlusses, Aufgaben „Offenen Betrag klären“ bzw. „Erstattung prüfen“. |
Erinnerungen und Mahnungen gibt es nur, wenn wir selbst kassieren (unverändert). Bestehende Daten werden nicht still umgedeutet: `php artisan cases:recheck-payment-status` zeigt betroffene Vorgänge, `--apply` korrigiert sie mit Begründung im Verlauf.
### Abschnitt 6 – Testbetrieb
- Alle neuen Mails laufen über den Laravel-Mailer und damit durch die eine Schranke `EnforceMailTestMode`: Auskunft, Buchungswunsch (Gast und Vermieterin), Absage und Aufenthaltsbestätigung. Die bestehende Prüfung `MailTestModeGateTest` findet keinen Versandweg daran vorbei.
- T23 schickt den ganzen Ablauf über echtes SMTP an einen isolierten Empfänger: automatisch, manuell, geplant (Anreise-Information), mit Cc und Bcc an fremde Adressen und aus der Warteschlange. Eine Mail, die im Livebetrieb eingereiht und nach dem Zurückschalten in den Testbetrieb versendet wird, geht ebenfalls nur an die Testadresse. Keine Originaladresse erscheint im SMTP-Umschlag.
- Im Verlauf steht bei umgeleiteten Mails „E-Mail im Testbetrieb an die Testadresse (nicht an den Gast)“, bei Fakten wie „Bestätigung gesendet“ der Zusatz „Testbetrieb: nur an die Testadresse, nicht an den Gast“. Maßgeblich ist der Umleitungsvermerk in der Mail selbst; damit gilt das auch bei der Server-Vorgabe `FEWO_MAIL_REDIRECT_TO`.
- iCal-Import, -Export und Abgleich sind vom Testbetrieb unabhängig. Testvorgänge verändern Portalbelegungen nur über den normalen Export bzw. über Portalaufgaben, die jemand von Hand erledigen muss.
---
## 3. Technische Entscheidungen
| Entscheidung | Begründung |
|---|---|
| Keine neuen Status. Auskunft und Wunsch sind Felder am Vorgang (`information_*`, `wish_*`), der Status bleibt „Anfrage“ bis zur Bestätigung. Der Aufenthaltsabschluss nutzt den vorhandenen Status „Abgeschlossen“, der kaufmännische Abschluss ein Datum (`settled_at`). | Auftrag §4.4: keine zusätzliche Statusmaschine; Gates bleiben abgeleitet (G00). |
| `SubmitBookingWish` und `DecideBookingWish` binden über `ConfirmBooking::bind` unter derselben Wohnungssperre wie alle Buchungswege. | Zwei Wünsche oder Wunsch und Portalimport können nie beide zur Buchung werden. |
| Aufgaben sind nicht mehr nur eine je Art (`booking_tasks.subject`, eigener Titel, Zuständigkeit). Jede Art sagt selbst, ob sie den Aufenthalt (`blocksStay`) oder das Kaufmännische (`isCommercial`) aufhält. | Leistungen, Abweichungen und Nachläufer ohne zweite Vorgangsverwaltung (§4.2). |
| `CaseClosure` leitet offene Punkte aus Aufgaben und `CaseMoney` ab und wird nach Zahlung, Aufgabenwechsel, Storno und Abschluss neu bewertet. | Kein Punkt verschwindet beim Abschluss; der Abschluss erfindet keine Beträge. |
| Statusregel nur über `paidToUs()`, Verlaufstext je Zahlungsart im Zahlungsmodell. | Abschnitt 5; die Zahlungsübersicht aus Paket 8 bleibt unverändert. |
| Nach der Abreise gelten offene Schritte vor dem Aufenthalt als „entfällt“ (Unterlagen, Kontakt, Anreise-Info). | Gefunden in der Browserprüfung: Ein vergangener Aufenthalt bot sonst noch „Bestätigung senden“ an. |
---
## 4. Abnahmekriterien
| ID | Kriterium | Nachweis | Ergebnis |
|---|---|---|---|
| 7.1 | Haltefrist 0: Kalender frei, Auskunft mit „Buchung anfragen“, ohne Annahmewirkung | T16, Screenshot `T16-gast-auskunft.png` | erfüllt |
| 7.2 | Wunsch automatisch, frei: bestätigt, Vertrag und Zahlungsplan | T18, T24 | erfüllt |
| 7.3 | Wunsch manuell: Aufgabe „Buchungswunsch bestätigen?“ | T16, Screenshots `T16-buchungswunsch-*.png` | erfüllt |
| 7.4 | Zwischenzeitlich belegt: keine Buchung, Absage, Hinweis | T17, T18 | erfüllt |
| 9.1 | Fehlende Anreisedaten erzeugen rechtzeitig eine Aufgabe; Portalnachricht „durch Portal (angekündigt)“ | T19, T20, T24, Sonderfälle | erfüllt |
| 9.2 | Abschluss mit Nachläufer: Vorgang abgeschlossen, Forderung bleibt als Aufgabe sichtbar | T22, Screenshot `T22-kaufmaennisch-offen.png` | erfüllt |
| §4.4 | Aufenthalt und Kaufmännisches getrennt; Portalauszahlung hält den Aufenthalt nicht auf | T20, T22 | erfüllt |
| §5 | „Laut Portal bezahlt“ ist kein „Anzahlung erhalten“; Altbestand nur auf Anfrage | T20, Test `existing_payment_statuses_…` | erfüllt |
| §6 | Testbetrieb über echtes SMTP, Cc/Bcc, Warteschlange, Verlauf | T23 | erfüllt |
---
## 5. Prüfungen und Risiken
- **Automatisiert:** Die gesamte Suite ist grün (700/4200). Die Abnahmefälle laufen über die echten Dialoge (Livewire), die Gast-Links (HTTP) und den täglichen Lauf.
- **Browser:** Chromium mit Zwei-Faktor-Anmeldung auf einer Kopie der lokalen Datenbank, Server lokal, Mails nur ins Log. Geprüft habe ich: Gastseite Auskunft, Vorgang mit Buchungswunsch und Entscheidungsdialog, Aufenthalt mit offener Reinigung und Abweichung, „Aufgabe erledigen“ mit Übergabe, abgeschlossener Aufenthalt mit offenem Betrag, Wohnungseinstellung „Aufenthalt vorbereiten“, Wirksame Einstellungen und Zu erledigen. Es gab keine Konsolenfehler. Gefunden und behoben:
- Direkt bestätigte Vorgänge zeigten Auskunft und Wunsch als „erledigt“.
- Ein vergangener Aufenthalt bot „Bestätigung senden“ an.
- „Als Nächstes“ zeigte einen Detailtext eines anderen Schritts.
- Das Formular der Aufenthaltsaufgaben war zu schmal.
- **Migration:** Auf SQLite habe ich vor, zurück und wieder vor geprüft. Auf MariaDB ist sie nicht geprüft: Lokal steht keine MariaDB zur Verfügung, und ohne Freigabe gibt es keine Auslieferung. Der neue Eindeutigkeitsschlüssel wird vor dem Entfernen des alten angelegt, damit der Fremdschlüssel unter MariaDB einen Index behält.
- **Risiken:** In Abschnitt 6 der [GESAMTABNAHME](GESAMTABNAHME_v0.10.md); die wichtigsten:
- Die Rechtsprüfung des Buchungswunsches als Antrag des Gastes steht aus.
- Echte Mietbedingungen statt Mustertext fehlen noch (die Gastseite zeigt „[MUSTER …]“).
- Die Migration ist auf MariaDB nicht geprüft.
- Die Bedienprobe hat nicht stattgefunden.
---
## 6. Migrationsbedarf
- Die Migration `2026_11_05_090000_create_information_wish_and_stay_closure` ist additiv. Neue Spalten gibt es an `bookings`, `properties` (`stay_tasks`, `asks_arrival_time`) und `booking_tasks` (`subject`, `title`, `responsible`). Der Eindeutigkeitsschlüssel der Aufgaben wird auf (Vorgang, Art, Gegenstand) erweitert.
- Bestandsvorgänge:
- Noch nicht abgeschlossene, schon abgereiste Aufenthalte schließt der nächste tägliche Lauf. Ihre offenen Geldpunkte werden zu Nachläufern. Bisher wurden nur vollständig bezahlte Aufenthalte abgeschlossen.
- Schon abgeschlossene oder stornierte Vorgänge (Abreise im letzten Jahr) bewertet der tägliche Lauf ebenfalls. Ist nichts offen, gelten sie als kaufmännisch abgeschlossen, mit Eintrag „System (automatisch)“ im Verlauf. Sonst zeigen sie die offenen Punkte.
- Nach der Auslieferung: zuerst `php artisan cases:recheck-payment-status` als Vorschau, `--apply` nur nach Durchsicht. Aufgaben je Wohnung und „Anreisezeit erfragen“ einstellen.
---
## 7. Offene Entscheidungen
| Frage | Vorschlag | Bis dahin |
|---|---|---|
| **Buchungswunsch rechtlich:** Ist der Klick „Buchung anfragen“ mit bestätigten Bedingungen der Antrag, den unsere Bestätigung annimmt (BGB §§ 145 ff., 305)? | Texte von Gastseite und Mails prüfen lassen. | Der Text lautet: „Der Vertrag kommt erst mit unserer Buchungsbestätigung zustande.“ |
| **Gültigkeit der Auskunft:** Eigene Frist, oder wie bisher die Frist von Angebot und Reservierung? | Beibehalten (E-026: keine Preisbindefrist). | Gleiche Einstellung wie Angebote. |
| **Auszahlungsprüfung:** Wann ist eine Portalauszahlung überfällig? | Je Portal einstellbar machen, wenn die Erfahrungswerte bekannt sind. | Fest: Abreise + 14 Tage. |
| **Melde- und Abgabefelder, Kurabgabe bei Mietgästen** | Nach rechtlicher Klärung (Offene_Fragen) als Felder am Vorgang. | Die Kurabgabe wird nur bei A6 berechnet; Gäste zahlen vor Ort. |
| **B3:** Pflicht zur Gastzustimmung bei Preiserhöhung nach Verbindlichkeit | wie in Paket 5 | Die Vermieterin wählt den Weg. |
| **Abschluss automatisch über Nacht** (B4, jetzt entschieden) | Vom Betreiber in der Bedienprobe bestätigen lassen. | Umgesetzt wie in Abschnitt 2 beschrieben. |
Die Pakete 1–9 der v0.10 sind damit umgesetzt. Weitere Ausbauschritte stehen in [GESAMTABNAHME_v0.10](GESAMTABNAHME_v0.10.md) §7.
+30
View File
@@ -1,5 +1,35 @@
# Projektstand # Projektstand
## Aktueller Stand (02.11.2026)
**Prozessarchitektur v0.10: Pakete 1–9 umgesetzt.**
| Branch | Inhalt | Stand |
|---|---|---|
| `main` | Produktion | unverändert |
| `develop` (Testsystem stommer.info) | Pakete 1–6 und 8 | ausgeliefert, Migration vom Betreiber als erfolgreich gemeldet |
| `feature/aufenthalt` | zusätzlich Pakete 7 und 9 | **nicht** gemergt oder ausgeliefert; Merge und Auslieferung nur nach Freigabe |
- **Paket 7:** Anfrage ohne Haltefrist → unverbindliche Auskunft → „Buchung anfragen“ → erneute Prüfung → automatisch oder von Hand bestätigt bzw. abgesagt.
- **Paket 9:**
- Vorbereitung: Anreisedaten, Aufgaben je Wohnung, gebuchte Leistungen.
- Während des Aufenthalts: Abweichungen und Folgeaufgaben am Vorgang.
- Getrennt „Aufenthalt abgeschlossen“ und „kaufmännisch abgeschlossen“; Nachläufer bleiben sichtbar.
- **Zahlungsstatus:** Nur Geld auf unserem Konto ändert ihn; Altbestand über `cases:recheck-payment-status`.
- **Testbetrieb:** über echtes SMTP nachgewiesen (T23).
- **Tests:** 700 grün.
Zur Bewertung ohne Code: [Prozessarchitektur/GESAMTABNAHME_v0.10.md](Prozessarchitektur/GESAMTABNAHME_v0.10.md), darin was den Produktivbetrieb blockiert und das Drehbuch der Bedienprobe. Weitere Dokumente: [UMSETZUNGSERGEBNIS_P7_P9](Prozessarchitektur/UMSETZUNGSERGEBNIS_P7_P9.md), [END_TO_END_ABNAHME](Prozessarchitektur/END_TO_END_ABNAHME.md) (T01–T25, getrennt nach automatisiert / Browser / Testsystem / Betreiber), [KONFIGURATION_UND_WIRKSAMKEIT](Prozessarchitektur/KONFIGURATION_UND_WIRKSAMKEIT.md).
**Nächste Schritte:**
1. Freigabe zum Merge nach `develop`, dann Abnahme auf dem Testsystem (MariaDB).
2. Echte Mietbedingungen und Bank eintragen, Texte freigeben, Rechtsprüfung der Gastschritte.
3. Bedienprobe mit der Vermieterin.
## Verlauf (historisch, neueste zuerst)
**Pakete 8, 5 und 6 der Prozessarchitektur v0.10 (01.11.2026, Branch `feature/abwicklung`, nicht ausgeliefert):** **Beträge und Zahlungen** – Zahlungen mit Art (Gast an uns / laut Portal ans Portal / Auszahlung Portal / Erstattung), Portalbeträge als Angaben mit Quelle (`case_amounts`), Übersicht `App\Pricing\CaseMoney` trennt Gastforderung, Portalzahlung, Auszahlung und Kontoeingang; R09 exakt erfassbar. **Ändern und Beenden** – `ChangeBooking` mit Folgenvorschau, „mit dem Gast vereinbart“ (Grundlage, Zeitpunkt) oder „dem Gast vorschlagen“ (signierter Link, Annahme mit Nachweis); ein Stornoweg mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portalbuchungen erst storniert, wenn im Portal bestätigt. **A6** – Eigene Nutzung, Besuch und Sperre als Vorgang („Neu“, Belegungsplan „+ eintragen“), Kurabgabe als Position (Satz an der Wohnung), Aufenthaltsbestätigung ohne Mietvertrag, keine Mahnung/Bewertung/Marketing; Altsperren per `cases:adopt-blocks` (Vorschau, `--apply`, `--revert`, Export identisch). **System › Wirksame Einstellungen** zeigt je Eingangsweg und Vorgang die angewandten Werte. **685 Tests grün** (inkl. Abnahmekatalog T01–T14). Dokumente: [UMSETZUNGSERGEBNIS_P5_P6_P8](Prozessarchitektur/UMSETZUNGSERGEBNIS_P5_P6_P8.md), [END_TO_END_ABNAHME](Prozessarchitektur/END_TO_END_ABNAHME.md), [KONFIGURATION_UND_WIRKSAMKEIT](Prozessarchitektur/KONFIGURATION_UND_WIRKSAMKEIT.md).
**Ein Eingang für alle Kanäle – Paket 4 der Prozessarchitektur v0.10 (03.11.2026, Branch `feature/eingang`, nicht ausgeliefert):** Portalbuchungen und -anfragen kommen über einen Eingang (`App\Channels\Intake\PortalIntake`, aufgerufen nach jedem Kalenderabgleich und aus `ProcessPortalMail`): sicher erkannte Buchungen (Buchungsmail mit Nummer, Kalenderregel „Reservierung dieses Portals“) werden zum Vorgang ohne Angebot/Annahme, Anfrage-Mails zur A2-Anfrage; Dubletten über Buchungsnummer → gleiches Portal mit gleichen Nächten → Spiegelung, nie nach bloßer Überschneidung; Unsicheres wird unter „Zu erledigen“ geklärt („Klären: Was ist das?“). Stornomail, verschwundener oder geänderter Kalendereintrag eines gebuchten Vorgangs → Aufgabe am Vorgang, keine stille Stornierung. Schalter je Kanal `channels.case_intake` (Aus = Standard, Beobachten, Anlegen, Anlegen + weiter); Eingangsprotokoll (System › Eingangsprotokoll, `channels:intake-report`); Bestandsübernahme `channels:adopt-occupations` (Vorschau, `--apply`, `--revert`). Portalaufgaben mit Nachweisstufe (veranlasst / im Portal gesehen / bestätigt). **662 Tests grün**, Browserprüfung durchgeführt. Ergebnis und Aktivierungsweg: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md). **Ein Eingang für alle Kanäle – Paket 4 der Prozessarchitektur v0.10 (03.11.2026, Branch `feature/eingang`, nicht ausgeliefert):** Portalbuchungen und -anfragen kommen über einen Eingang (`App\Channels\Intake\PortalIntake`, aufgerufen nach jedem Kalenderabgleich und aus `ProcessPortalMail`): sicher erkannte Buchungen (Buchungsmail mit Nummer, Kalenderregel „Reservierung dieses Portals“) werden zum Vorgang ohne Angebot/Annahme, Anfrage-Mails zur A2-Anfrage; Dubletten über Buchungsnummer → gleiches Portal mit gleichen Nächten → Spiegelung, nie nach bloßer Überschneidung; Unsicheres wird unter „Zu erledigen“ geklärt („Klären: Was ist das?“). Stornomail, verschwundener oder geänderter Kalendereintrag eines gebuchten Vorgangs → Aufgabe am Vorgang, keine stille Stornierung. Schalter je Kanal `channels.case_intake` (Aus = Standard, Beobachten, Anlegen, Anlegen + weiter); Eingangsprotokoll (System › Eingangsprotokoll, `channels:intake-report`); Bestandsübernahme `channels:adopt-occupations` (Vorschau, `--apply`, `--revert`). Portalaufgaben mit Nachweisstufe (veranlasst / im Portal gesehen / bestätigt). **662 Tests grün**, Browserprüfung durchgeführt. Ergebnis und Aktivierungsweg: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md).
**Dokumentenzusammenstellung und Vorlagensteuerung – Paket 3 der Prozessarchitektur v0.10 (02.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Vor jedem Dokument dieselbe Zusammenstellung (`App\Documents\DocumentComposer`, Ansicht `filament/document-composition`): Empfänger, Zeitraum, Preis mit Herkunft, Leistungen, Stornoregel, Vorlage mit Herkunft, Anlagen, Hinweise (fehlt / bitte prüfen / Info), E-Mail- und PDF-Vorschau. Dokumentart je Vorgang automatisch (`App\Enums\DocumentKind`): Anfrage → Angebot mit Annahmelink, eigene Buchung → Bestätigung mit Mietvertrag, beim Portal verbindlich (A3/A4) → **Buchungsunterlagen ohne Annahmelink** (`BookingDocumentation`). Unterlagen verbindlicher Vorgänge nur über `SendBookingDocuments` (automatisch nur ohne Prüfpunkte, von Hand mit bestätigten Hinweisen, einmalig per Sperre); Angebote mit `expected_version` gegen Doppelversand; ohne Vorreservierung (Hold 0) kein Angebot ohne ausdrückliche Entscheidung. Vorlagen haben Freigabe und „gibt nur Portalbedingungen wieder“ (entfallen bei Textänderung); die Buchungsunterlagen extern sind eine Arbeitsfassung bis zur Freigabe unter So arbeite ich › Dokumente. **648 Tests grün**, Browserprüfung durchgeführt. Ergebnis, offene Freigaben (FeWo-direkt-Vorlage FW-01, Unterlagentext) und Empfehlung Paket 4: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md). **Dokumentenzusammenstellung und Vorlagensteuerung – Paket 3 der Prozessarchitektur v0.10 (02.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Vor jedem Dokument dieselbe Zusammenstellung (`App\Documents\DocumentComposer`, Ansicht `filament/document-composition`): Empfänger, Zeitraum, Preis mit Herkunft, Leistungen, Stornoregel, Vorlage mit Herkunft, Anlagen, Hinweise (fehlt / bitte prüfen / Info), E-Mail- und PDF-Vorschau. Dokumentart je Vorgang automatisch (`App\Enums\DocumentKind`): Anfrage → Angebot mit Annahmelink, eigene Buchung → Bestätigung mit Mietvertrag, beim Portal verbindlich (A3/A4) → **Buchungsunterlagen ohne Annahmelink** (`BookingDocumentation`). Unterlagen verbindlicher Vorgänge nur über `SendBookingDocuments` (automatisch nur ohne Prüfpunkte, von Hand mit bestätigten Hinweisen, einmalig per Sperre); Angebote mit `expected_version` gegen Doppelversand; ohne Vorreservierung (Hold 0) kein Angebot ohne ausdrückliche Entscheidung. Vorlagen haben Freigabe und „gibt nur Portalbedingungen wieder“ (entfallen bei Textänderung); die Buchungsunterlagen extern sind eine Arbeitsfassung bis zur Freigabe unter So arbeite ich › Dokumente. **648 Tests grün**, Browserprüfung durchgeführt. Ergebnis, offene Freigaben (FeWo-direkt-Vorlage FW-01, Unterlagentext) und Empfehlung Paket 4: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md).
+42
View File
@@ -0,0 +1,42 @@
@extends('theme::layouts.app', ['title' => 'Änderung Ihrer Buchung'])
@push('head')
<meta name="robots" content="noindex">
@endpush
@section('content')
<div class="mx-auto max-w-3xl px-4 py-14 sm:px-8">
<p class="eyebrow">Buchung {{ $booking->reference }}</p>
<h1 class="heading-display">Vorschlag zur Änderung</h1>
<p class="mt-2 text-muted">{{ $booking->property->name }} · für {{ $booking->guestName() }}</p>
@if (session('change.success'))
<div class="mt-8 rounded border border-accent bg-surface p-5" role="status">{{ session('change.success') }}</div>
@endif
@if (session('change.error'))
<div class="mt-8 rounded border border-line bg-surface p-5" role="alert">{{ session('change.error') }}</div>
@endif
<ul class="mt-8 list-disc space-y-1 pl-6">
@foreach (explode(' · ', $change->summary()) as $line)
<li>{{ $line }}</li>
@endforeach
</ul>
@if ($change->status === \App\Enums\ChangeStatus::Proposed && ! session('change.success'))
<p class="mt-6 text-muted">Bis zu Ihrer Zustimmung bleibt Ihre Buchung unverändert. Der Vorschlag gilt bis {{ $change->expires_at?->format('d.m.Y') }}.</p>
<form method="post" action="{{ URL::temporarySignedRoute('changes.accept', $change->expires_at ?? now()->addDay(), ['change' => $change]) }}" class="mt-6">
@csrf
<label class="flex items-start gap-3"><input type="checkbox" name="agree" value="1" class="mt-1"> <span>Ich bin mit dieser Änderung einverstanden.</span></label>
@error('agree')<p class="mt-2 text-sm">{{ $message }}</p>@enderror
<button type="submit" class="btn-accent mt-4 w-full sm:w-auto">Änderung annehmen</button>
</form>
<form method="post" action="{{ URL::temporarySignedRoute('changes.decline', $change->expires_at ?? now()->addDay(), ['change' => $change]) }}" class="mt-3">
@csrf
<button type="submit" class="text-sm text-muted underline hover:text-ink">Ablehnen</button>
</form>
@elseif (! session('change.success'))
<div class="mt-8 rounded border border-line bg-surface p-5">Dieser Vorschlag ist {{ $change->status->getLabel() }}.</div>
@endif
</div>
@endsection
@@ -0,0 +1,58 @@
{{-- Prices and payments of a case, kept apart by who owes whom (package 8). --}}
@php
/** @var \App\Pricing\CaseMoney $money */
$euro = fn (?int $cents): string => $cents === null ? 'noch nicht bekannt' : \App\Support\Money::format($cents);
$row = 'display:flex;justify-content:space-between;gap:1rem;padding:.35rem 0;border-bottom:1px solid rgba(128,128,128,.15)';
$muted = 'color:#6b7280;font-size:.85rem';
$collector = $money->collector();
$payout = $money->payout();
$positions = $money->positions();
@endphp
<div style="font-size:.95rem">
<div style="{{ $row }}"><span><strong>Vereinbarter Gesamtpreis</strong> <span style="{{ $muted }}">{{ $money->totalSource() }}</span></span><strong>{{ $euro($money->total()) }}</strong></div>
@if ($collector === \App\Enums\Responsibility::Landlord)
<div style="{{ $row }}"><span>Vom Gast an uns gezahlt</span><span>{{ $euro($booking->paidToUs()) }}</span></div>
<div style="{{ $row }}"><span>Noch offen – zahlt der Gast an uns</span><span style="color:{{ $money->openForUs() > 0 ? '#dc2626' : '#15803d' }};font-weight:600">{{ $euro($money->openForUs()) }}</span></div>
@elseif ($collector === \App\Enums\Responsibility::Portal)
<div style="{{ $row }}"><span>Zahlung des Gastes läuft über {{ $booking->processChannel()?->name ?? 'das Portal' }}</span><span style="{{ $muted }}">keine Mahnung durch uns</span></div>
<div style="{{ $row }}"><span>Laut Portal vom Gast bezahlt</span><span>{{ $euro($booking->paidViaPortal()) }}</span></div>
<div style="{{ $row }}"><span>Laut Portal noch beim Gast offen</span><span>{{ $euro($money->openAtPortal()) }}</span></div>
@foreach ($money->installmentsDue() as $installment)
<div style="{{ $row }}"><span style="{{ $muted }}">Rate laut Portal fällig{{ $installment->due_on ? ' am '.$installment->due_on->format('d.m.Y') : '' }}</span><span style="{{ $muted }}">{{ $euro($installment->amount) }}</span></div>
@endforeach
<div style="{{ $row }}"><span>Auszahlung an uns angekündigt</span>
<span>{{ $payout['values'] === [] ? 'noch keine Angabe' : implode(' bzw. ', array_map($euro, $payout['values'])) }}</span></div>
@if ($payout['difference'] > 0)
<div style="{{ $row }}"><span style="color:#b45309">Die Angaben zur Auszahlung weichen um {{ $euro($payout['difference']) }} voneinander ab – ungeklärt.</span><span></span></div>
@endif
<div style="{{ $row }}"><span>Auszahlung tatsächlich erhalten</span><span>{{ $euro($payout['received']) }}</span></div>
@if ($payout['outstanding'] !== null)
<div style="{{ $row }}"><span>Noch auszuzahlen (laut Ankündigung)</span><span>{{ $euro($payout['outstanding']) }}</span></div>
@endif
@else
<div style="{{ $row }}"><span>Bezahlt</span><span>{{ $euro($booking->paidAmount()) }}</span></div>
<div style="{{ $row }}"><span style="{{ $muted }}">Keine Zahlungserinnerungen bei eigener Nutzung / privatem Aufenthalt.</span><span></span></div>
@endif
<div style="{{ $row }}"><span>Auf unserem Konto eingegangen</span><span>{{ $euro($money->receivedOnAccount()) }}</span></div>
@if ($positions['positions']->isNotEmpty() || $money->commissions()->isNotEmpty() || $payout['announcements']->isNotEmpty())
<details style="margin-top:.6rem">
<summary style="cursor:pointer;font-weight:600">Einzelangaben laut Portal</summary>
<div style="margin-top:.4rem">
@foreach ($positions['positions'] as $position)
<div style="{{ $row }}"><span>{{ $position->title() }} <span style="{{ $muted }}">{{ $position->source }}{{ $position->stated_on ? ', '.$position->stated_on->format('d.m.Y') : '' }}</span></span><span>{{ $euro($position->amount) }}</span></div>
@endforeach
@if ($positions['positions']->isNotEmpty())
<div style="{{ $row }}"><span style="{{ $muted }}">Summe der Positionen</span><span style="{{ $muted }}">{{ $euro($positions['sum']) }}{{ $positions['difference'] === 0 ? ' = Gesamtpreis' : ($positions['difference'] !== null ? ' – Abweichung zum Gesamtpreis '.$euro($positions['difference']) : '') }}</span></div>
@endif
@foreach ($money->commissions() as $commission)
<div style="{{ $row }}"><span>{{ $commission->title() }} <span style="{{ $muted }}">{{ $commission->source }} · trägt der Vermieter, kein Betrag des Gastes</span></span><span>{{ $euro($commission->amount) }}</span></div>
@endforeach
@foreach ($payout['announcements'] as $announcement)
<div style="{{ $row }}"><span>{{ $announcement->title() }} <span style="{{ $muted }}">{{ $announcement->source }}{{ $announcement->stated_on ? ', '.$announcement->stated_on->format('d.m.Y') : '' }}{{ $announcement->note ? ' · '.$announcement->note : '' }}</span></span><span>{{ $euro($announcement->amount) }}</span></div>
@endforeach
</div>
</details>
@endif
</div>
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more