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
69 changed files with 3703 additions and 175 deletions

No files matched your search

+21 -7
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 {
if (! $booking->process()->preReservation()) {
$this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]);
} else {
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]); $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;
+8
View File
@@ -11,6 +11,7 @@
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\Process\CaseLog;
use App\Support\CancellationCost; use App\Support\CancellationCost;
use App\Support\Money; use App\Support\Money;
@@ -65,6 +66,11 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported]) ->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
->where('status', BookingTaskStatus::Open) ->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); $this->refundTask($booking);
@@ -79,6 +85,8 @@ 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);
} }
+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.',
},
]);
}
}
}
}
+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);
}
}
}
+6 -1
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(fn ($query) => $query
->where('hold_expires_at', '<=', now()) ->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;
}
}
+83 -16
View File
@@ -3,17 +3,27 @@
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\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 payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the * Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
* portal paid out to us, or we refunded the guest. Only the guest's payments move the booking along * portal paid out to us, or we refunded the guest. A refund is stored as a negative amount.
* (Bestätigt → Anzahlung erhalten → Bezahlt); 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
{ {
@@ -21,7 +31,7 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P
{ {
$amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount; $amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment { $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(),
@@ -34,27 +44,84 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P
$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.');
}
}
}
}
} }
+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,
);
}
}
}
@@ -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) {
+28 -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,11 +56,12 @@ 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, $kind === DocumentKind::StayConfirmation => null,
@@ -99,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 {
@@ -141,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,
@@ -149,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.');
@@ -176,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) {
@@ -249,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',
}; };
+49 -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
{ {
@@ -20,6 +24,13 @@ enum BookingTaskKind: string implements HasLabel
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 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
{ {
@@ -33,12 +44,48 @@ public function getLabel(): string
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::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, self::RefundCheck], 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];
} }
/** /**
@@ -52,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, self::RefundCheck => null, default => null,
}; };
} }
} }
+5 -4
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,7 +40,7 @@ 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, nur auf Wunsch.', self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
@@ -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, self::StayConfirmation], true); return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
} }
/** /**
+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?',
@@ -9,6 +9,7 @@
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\Mail\StayConfirmed;
use App\Models\Booking; use App\Models\Booking;
@@ -86,6 +87,7 @@ 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(), DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(),
default => (new BookingConfirmed($draft))->render(), default => (new BookingConfirmed($draft))->render(),
@@ -100,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) {
+1 -1
View File
@@ -34,7 +34,7 @@ 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::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->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),
+32
View File
@@ -12,6 +12,7 @@
use App\Models\Property; use App\Models\Property;
use App\Process\ProcessProfile; use App\Process\ProcessProfile;
use App\Process\ProcessSettings; use App\Process\ProcessSettings;
use App\Support\Money;
use BackedEnum; use BackedEnum;
use Filament\Pages\Page; use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon; use Filament\Support\Icons\Heroicon;
@@ -102,6 +103,37 @@ public static function where(ProcessSetting $setting): string
: 'System › So arbeite ich; Abweichung: Wohnung (Experte), Portal je Anfrage/feste Buchung'.($setting->channelIntakes() === [] ? ' (kein Portal)' : ''); : '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. * Recent cases to check.
* *
@@ -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;
}
}
}
@@ -31,6 +31,7 @@
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\BookingChange;
use App\Models\BookingTask; use App\Models\BookingTask;
@@ -79,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. */
@@ -97,8 +100,15 @@ 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(),
@@ -143,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')
@@ -151,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;
@@ -144,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)
@@ -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 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])]);
}
}
+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');
}
}
+18
View File
@@ -99,6 +99,17 @@
'tourist_tax_note', 'tourist_tax_note',
'portal_cancellation_requested_at', 'portal_cancellation_requested_at',
'export_uid', '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
{ {
@@ -187,6 +198,13 @@ protected function casts(): array
'archived_at' => 'immutable_datetime', 'archived_at' => 'immutable_datetime',
'internal_kind' => InternalKind::class, 'internal_kind' => InternalKind::class,
'portal_cancellation_requested_at' => 'immutable_datetime', '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',
]; ];
} }
+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;
} }
} }
+2 -2
View File
@@ -2,11 +2,11 @@
namespace App\Models; namespace App\Models;
use App\Actions\RecordPayment;
use App\Enums\PaymentKind; 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;
@@ -27,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->kind ?? PaymentKind::Guest)->getLabel().': '.Money::format(abs($payment->amount)).($payment->source ? ' ('.$payment->source.')' : ''), 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]);
} }
}); });
} }
+32
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.
@@ -47,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
{ {
@@ -85,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',
@@ -188,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;
}
} }
+143 -12
View File
@@ -3,7 +3,9 @@
namespace App\Process; namespace App\Process;
use App\Actions\EndInternalCase; 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\BookingTaskKind;
@@ -18,6 +20,7 @@
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;
@@ -45,7 +48,11 @@ 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()) { if ($booking->isInternal()) {
@@ -67,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,
@@ -125,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 {
@@ -142,7 +191,7 @@ 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[] = self::task($task); $activities[] = self::task($task);
} }
@@ -152,8 +201,17 @@ public static function for(Booking $booking): array
$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,
@@ -164,9 +222,64 @@ 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. * Own use, private stay or block (A6): only what such a case has – no contract, no reminders, no reviews.
* *
@@ -190,12 +303,12 @@ private static function internal(Booking $booking, bool $closed, callable $later
$paid = $booking->paidAmount(); $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'); $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 (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) { foreach (self::tasks($booking) as $task) {
$activities[] = self::task($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')); $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; return [...$activities, ...self::closing($booking, $closed)];
} }
/** /**
@@ -206,11 +319,24 @@ private static function task(BookingTask $task): Activity
$action = match ($task->kind) { $action = match ($task->kind) {
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation', BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
BookingTaskKind::PortalChangeReported => 'change', BookingTaskKind::PortalChangeReported => 'change',
BookingTaskKind::RefundCheck => null, BookingTaskKind::BookingWish => 'decideWish',
default => $task->kind->isPayment() ? null : 'end', 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->kind->getLabel(), ActivityState::Open, trim(($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->note ? ' · '.$task->note : ''), ' ·'), $action); return new Activity('task_'.$task->kind->value, $task->label(), $state, $detail, $state === ActivityState::Done ? null : $action);
} }
/** /**
@@ -251,12 +377,17 @@ public static function situation(Booking $booking): string
$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',
+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,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: 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

+67 -47
View File
@@ -1,53 +1,72 @@
# Fachliche End-to-End-Abnahme # Fachliche End-to-End-Abnahme
Wiederverwendbarer Katalog repräsentativer Geschäftsfälle. Jeder Fall ist aus Sicht der Vermieterin beschrieben und hat zwei Nachweise: 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:
- einen automatisierten Durchgang über die echten Dialoge, Aktionen und Gast-Links, im Test `tests/Feature/EndToEndAcceptanceTest.php`, Methode `test_tNN_…`; - `tests/Feature/EndToEndAcceptanceTest.php` (T01–T15)
- wo sinnvoll eine Sichtprüfung im Browser, Screenshots unter `Abnahme/<Datum>/`. - `tests/Feature/EndToEndStayAcceptanceTest.php` (T16–T25 ohne T23, dazu die Sonderfälle)
- `tests/Feature/TestOperationSmtpAcceptanceTest.php` (T23)
Für weitere Pakete werden Fälle ergänzt und der Abschnitt „Durchführung“ neu datiert. Screenshots liegen unter `Abnahme/<Datum>/`.
**Durchführung 01.11.2026** ## Abnahmestand 02.11.2026
- Stand: Branch `feature/abwicklung`, Pakete 1–6 und 8.
- Automatisiert: 15 Fälle, alle bestanden (Teil der Suite mit 685 grünen Tests).
- Browser: lokale Datenbankkopie mit Testdaten (Gäste `@example.test`), Testbetrieb aktiv, Versandweg „log“, Anmeldung mit Zwei-Faktor-Code.
- Testsystem: nicht genutzt, keine Deployment-Freigabe.
- Echte Gastnachrichten oder Portalbelegungen: keine.
**Status:** ✅ erfolgreich · ◐ teilweise · ✗ fehlgeschlagen · – noch nicht ausführbar | 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 ## Testfälle
| ID | Fall | Ausgangslage und Konfiguration | Anwenderhandlungen | Soll | Ist | Status | Nachweis | | ID | Fall | Ausgangslage, Konfiguration | Handlungen | Soll | Ist | A | B | T | F | Nachweis |
|---|---|---|---|---|---|---|---| |---|---|---|---|---|---|---|---|---|---|---|
| T01 | Eigene Anfrage, automatisch | Vermieterstandard „automatisch“, Vertragstexte und Bank hinterlegt | Gast fragt über die Webseite an | Angebot geht ohne Klick hinaus; Vorgang wartet auf den Gast; nichts unter „Zu erledigen“ | wie Soll (A1, Angebot gesendet, Aktivität „Gast nimmt an“ wartet) | ✅ | `test_t01_…` | | 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 „Ostseeklar“ mit Handsperre | „Neu → Anfrage“; „Angebot prüfen und senden“; Gast nimmt per Link an | Zu erledigen „Angebot prüfen und senden“; nach Annahme gebucht, Vertrag, Bestätigung, Sperraufgabe | wie Soll | ✅ | `test_t02_…` | | 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; Anfrage per Telefon ohne E-Mail | „E-Mail-Adresse eintragen“ mit „automatisch weitermachen“ | verständliche Aufgabe, danach Angebot automatisch | wie Soll | ✅ | `test_t03_…` | | 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“, Zahlung über Portal | Buchungsmail kommt an; „Preis laut Portal eintragen“ 979,51 € | ein Vorgang A4, Portalpreis, keine eigenen Mahnungen | wie Soll | ✅ | `test_t04_…` | | T04 | FeWo-direkt-Direktbuchung | Kanal „Anlegen“, Portal kassiert | Buchungsmail; Preis laut Portal | ein A4-Vorgang, keine Mahnungen | wie Soll | ✅ | – | – | – | `test_t04_…` |
| T05 | Destination Solutions | Portal ohne Automatik, Zahlung durch uns | „Neu → Buchung von einem Portal“ mit Nummer, Preis, Gast | A3 gebucht ohne Angebot; Unterlagen und Zahlungsplan durch uns; Anzahlung bewegt den Status | wie Soll | ✅ | `test_t05_…` | | T05 | Destination Solutions | wir kassieren | Neu → Portalbuchung | A3, Unterlagen und Zahlungsplan durch uns | wie Soll | ✅ | – | – | – | `test_t05_…` |
| T06 | Doppelte Portalmeldungen | Kanal mit iCal-Regel und Mail-Absender | Mail, danach zweimal Kalenderabgleich | genau ein Vorgang, Kalendereintrag zugeordnet | wie Soll | ✅ | `test_t06_…` | | T06 | Doppelte Portalmeldungen | Mail und Kalender | Mail, zweimal Abgleich | genau ein Vorgang | wie Soll | ✅ | – | – | – | `test_t06_…` |
| T07 | Buchungsänderung | gebuchte eigene Buchung 07.–10.11. | „Buchung ändern …“ bis 12.11., vereinbart am Telefon | Vorschau zeigt Folgen; danach Zeitraum, Preis, Zahlungsplan, Portalaufgabe, Verlauf | wie Soll (Preis +130 €, „Neu belegt“, Aufgabe Ostseeklar) | ✅ | `test_t07_…`, `T07-aendern-folgen.png` | | T07 | Buchungsänderung | gebuchte eigene Buchung | „Buchung ändern …“ | Folgenvorschau, Preis, Plan, Portalaufgabe, Verlauf | wie Soll | ✅ | ✅ | – | – | `test_t07_…`, `2026-11-01/T07-…` |
| T08 | Stornierung | eigene Buchung mit 100 € Zahlung; Portalbuchung; offene Anfrage | „Stornieren …“ bzw. „Beenden …“; bei Portal „Stornierung bestätigen …“ | eigene: storniert mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portal: erst nach Bestätigung storniert; Anfrage: ohne Buchung beendet, kein Storno | wie Soll | ✅ | `test_t08_…`, `T08-zu-erledigen-portalstorno.png` | | T08 | Stornierung | eigene, Portal-, Anfrage | „Stornieren …“, Portalbestätigung | richtiger Weg je Lage | wie Soll | ✅ | ✅ | – | – | `test_t08_…`, `2026-11-01/T08-…` |
| T09 | Familienbesuch | Kurabgabe 2,50 €; Leistung Wäschepaket 18 € | „Neu → Eigene Nutzung oder Besuch → Familie“, 5 Nächte, 3 Personen, Miete 0, 3 Wäschepakete, Kurabgabe 2 Personen | A6 mit 54 € + 25 € Kurabgabe = 79 €; Portale gesperrt; kein Vertrag, keine Mahnung, keine Bewertung | wie Soll | ✅ | `test_t09_…`, `T09-neu-besuch.png`, `T09-familienbesuch.png` | | T09 | Familienbesuch | Kurabgabe, Wäschepaket | Neu → Besuch | A6 79 €, kein Vertrag, keine Mahnung | wie Soll | ✅ | ✅ | – | – | `test_t09_…`, `2026-11-01/T09-…` |
| T10 | Wartungssperre | – | Belegungsplan „+ eintragen“ → Sperre; „Ändern oder verlängern …“; „Sperre aufheben …“ | ohne Gast, Vertrag, Zahlung; Verlängerung passt Portale an; Aufheben ist keine Stornierung, Portale werden freigegeben | wie Soll | ✅ | `test_t10_…`, `T10-sperre-aufheben.png` | | T10 | Wartungssperre | – | eintragen, verlängern, aufheben | keine Stornierung, Portale folgen | wie Soll | ✅ | ✅ | – | – | `test_t10_…`, `2026-11-01/T10-…` |
| T11 | Externe Zahlungen (R09) | FeWo-direkt-Buchung | Beträge laut Portal: 840 / −42 / 181,51 Sammelposten / 979,51 / −84,82 / 894,69 und 900,20 / Rate 588,90 fällig / 390,61 laut Portal bezahlt; später Auszahlung 894,69 € erfasst | Summe = Gesamtpreis; Abweichung 5,51 € ungeklärt angezeigt; offen bei uns 0; Konto erst nach Auszahlung; keine Doppelzählung | wie Soll | ✅ | `test_t11_…`, `T11-betraege-r09.png` | | 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 automatisch / 48 h; Wohnung 24 h; FeWo-direkt Anfrage „manuell“, Buchung Zahlung Portal | Anfrage über FeWo-direkt; im Vorgang auf „automatisch“ umstellen; Seite „Wirksame Einstellungen“ | jede Ebene wirkt mit richtiger Herkunft; die Vorgangsentscheidung gewinnt; Übersicht zeigt beides | wie Soll | ✅ | `test_t12_…`, `T12-wirksame-einstellungen.png` | | T12 | Einstellungshierarchie | Standard, Wohnung, Portal | Vorgang umstellen | jede Ebene mit Herkunft | wie Soll | ✅ | ✅ | – | – | `test_t12_…`, `2026-11-01/T12-…` |
| T13 | Testbetrieb | Testbetrieb mit Testadresse, echter Mailer | ganzer Ablauf: Anfrage, Angebot, Annahme, Änderung mit Bestätigung, Storno mit Mail | jede tatsächlich versendete Nachricht geht nur an die Testadresse | wie Soll (≥ 6 Nachrichten, alle an test@example.com) | ✅ | `test_t13_…`, zusätzlich `MailTestModeGateTest` | | T13 | Testbetrieb (Ablauf) | Testadresse, echter Mailer | Anfrage bis Storno | nur Testadresse | wie Soll | ✅ | – | – | – | `test_t13_…` |
| T14 | Änderungen mit Zustimmung | gebuchte eigene Buchung | Vorschlag an den Gast; Gast nimmt per Link an; danach vereinbarte Änderung mit Bestätigung | Vorschlag ändert nichts bis zur Annahme; Annahme mit Zeitpunkt; Bestätigung einer vereinbarten Änderung ist keine Zustimmung | wie Soll | ✅ | `test_t14_…`, `T14-gast-aenderungsvorschlag.png` | | 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 (6.3) | zwei manuelle Sperren, Exportkanal | `cases:adopt-blocks` Vorschau, `--apply`, nochmals `--apply` | zwei A6-Vorgänge, keine Dublette, Export identisch, keine Aufgaben oder Mails | wie Soll | ✅ | `test_existing_manual_blocks_…` | | 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
## Nicht ausführbare oder nur teilweise geprüfte Punkte | Fall | Erwartung | Ist | A | Nachweis |
|---|---|---|---|---|
| Punkt | Grund | | 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_…` |
| Durchführung auf dem Testsystem stommer.info | keine Deployment-Freigabe; geprüft wurde auf einer lokalen Datenbankkopie | | Stornierung kurz vor Anreise | Vorbereitungsaufgaben entfallen; Stornokosten halten den kaufmännischen Abschluss offen, bis sie erledigt sind | wie Soll | ✅ | `test_special_cases_…` |
| Echte FeWo-direkt-Mails und -Feeds | nur synthetische Muster (siehe Beobachtungsmodus aus Paket 4) | | 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_…` |
| Darstellung auf Tablet und Smartphone | nicht geprüft | | Alte Zahlungsstatus | Vorschau ändert nichts, `--apply` korrigiert mit Begründung | wie Soll | ✅ | `test_existing_payment_statuses_…` |
| Bedienprobe mit der Vermieterin | steht aus (Abnahme 2.5) | | Wiederholte Scheduler-Läufe | keine doppelten Aufgaben, Nachläufer oder Mails | wie Soll | ✅ | T19, T20, T22 (Läufe doppelt) |
| Änderung extern (5.2) als eigener Durchgang | durch die Preislogik und T04/T11 abgedeckt, kein eigener Testfall | | 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 |
--- ---
@@ -55,15 +74,16 @@ ## Erkannte Bedienungsprobleme
| Problem | Stand | | Problem | Stand |
|---|---| |---|---|
| Bei A6 erschien „Über: internal“, dazu der Schalter „Sie geben frei“ und eine Vorlagenangabe | behoben | | Direkt bestätigte Vorgänge zeigten „Auskunft“ und „Gast fragt an“ als erledigt | behoben (02.11.) |
| Ein Portal mit Buchungsmodell „gemischt“ (Sofortbuchung), dessen Kalenderexport nie abgeholt wurde, hält automatische Angebote und sogar Gastannahmen an („Verfügbarkeit nicht sicher“). Das ist fachlich richtig, für Testdaten aber überraschend. | dokumentiert; bei Einrichtung eines Portals das Buchungsmodell bewusst wählen | | Nach der Abreise blieb „Bestätigung senden“ der nächste Schritt | behoben: Schritte vor dem Aufenthalt entfallen danach |
| Bei Portalzahlung zeigt der Status „Anzahlung erhalten“, der Verlauf „Anzahlung eingegangen“, obwohl nur laut Portal bezahlt ist | offen (Entscheidung, siehe Ergebnisdokument §7) | | „Als Nächstes“ zeigte den Detailtext eines anderen Schritts | behoben |
| Der Dialog „Buchung ändern“ ist lang (Termin, Leistungen, Preis, Folgen, Grundlage) | offen – Vorschlag: Grundlage oben, Leistungen zuklappen | | Wohnungsformular „Aufgaben je Aufenthalt“ zu schmal | behoben |
| „Wirksame Einstellungen“: die Spalte „Wo einstellen?“ wiederholt sich je Zeile | offen, rein kosmetisch | | 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 ## Offene Arbeiten
1. Abnahme auf dem Testsystem nach Freigabe (Migration MariaDB, `cases:adopt-blocks` Vorschau mit echten Daten). 1. Auslieferung auf das Testsystem nach Freigabe, MariaDB-Migration prüfen, dann diesen Katalog dort wiederholen (Spalte T).
2. Bedienprobe mit der Vermieterin mit T02, T07, T09 und T10 als Drehbuch. 2. Bedienprobe mit der Vermieterin nach Drehbuch (Spalte F).
3. Statusbezeichnung bei Portalzahlung klären (mit B4 / Paket 9). 3. Texte freigeben und rechtlich prüfen lassen ([GESAMTABNAHME](GESAMTABNAHME_v0.10.md) §4).
4. Texte Änderungsbestätigung, Änderungsvorschlag und Aufenthaltsbestätigung freigeben.
@@ -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.
@@ -1,6 +1,6 @@
# Konfiguration und Wirksamkeit # Konfiguration und Wirksamkeit
Welche fachlichen Einstellungen es gibt, wo man sie vornimmt, wie sie sich vererben und wie man nachprüft, dass sie in einem konkreten Vorgang wirklich angewandt wurden. Stand 01.11.2026, Pakete 1–6 und 8. 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.
--- ---
@@ -8,13 +8,13 @@ ## 1. Wo man die Wirksamkeit sieht
| Werkzeug | Zeigt | | Werkzeug | Zeigt |
|---|---| |---|---|
| **System › Wirksame Einstellungen** (Expertenansicht) | Je Wohnung und Eingangsweg (direkte Anfrage, jedes Portal getrennt nach Anfrage und fester Buchung, A6) den Wert jeder Prozesseinstellung, der für einen **neuen** Vorgang gilt, mit Herkunft und dem Ort, an dem man ihn ändert. „Einen Vorgang prüfen“ zeigt das tatsächlich angewandte Profil eines Vorgangs und eine Umstellung im Vorgang. Direktaufruf: `…/admin/wirksame-einstellungen?vorgang=<ID>`. | | **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 › Technische Angaben** (Expertenansicht) | eingefrorenes Abwicklungsprofil mit Herkunft je Wert, Quellen und Kalenderdarstellungen | | **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 › Zusammenstellung** (Paket 3) | Vorlage mit Herkunft („eingestellt für FeWo-direkt (Verbindliche Buchung)“) | | **Vorgang › Technische Angaben** (Experte) | eingefrorenes Abwicklungsprofil mit Herkunft je Wert |
| `php artisan process:settings-report` | alle Standards und Abweichungen als Text | | `php artisan process:settings-report` | alle Standards und Abweichungen als Text |
| `php artisan channels:intake-report` | was der Eingang je Portal erkannt hat (Paket 4) | | `php artisan cases:recheck-payment-status` | Vorgänge, deren gespeicherter Zahlungsstatus der neuen Regel widerspricht (Vorschau) |
Nachweis im Test: `EndToEndAcceptanceTest::test_t12_settings_hierarchy_is_applied_and_visible`; Screenshot `Abnahme/2026-11-01/T12-wirksame-einstellungen.png`. Nachweise: `test_t12_…`, `test_t24_…`; Screenshots `Abnahme/2026-11-01/T12-wirksame-einstellungen.png` und `Abnahme/2026-11-02/T24-wirksame-einstellungen.png`.
--- ---
@@ -23,16 +23,16 @@ ## 2. Vererbung
``` ```
Grundeinstellung (im Code) Grundeinstellung (im Code)
→ Ihr Standard System › So arbeite ich → Ihr Standard System › So arbeite ich
→ Wohnung Wohnung bearbeiten › „Abweichende Abwicklung dieser Wohnung“ (Expertenansicht) → Wohnung Wohnung bearbeiten › „Abweichende Abwicklung dieser Wohnung“ (Experte)
→ Portal je Eingangsart Portal bearbeiten › „Anfragen über dieses Portal“ / „Feste Buchungen über dieses Portal“ → Portal je Eingangsart Portal bearbeiten › „Anfragen über dieses Portal“ / „Feste Buchungen über dieses Portal“
→ Vorgang Schalter „Läuft automatisch / Sie geben frei“ auf der Vorgangsseite → 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. - **Leer heißt „erbt“.** Ein bewusst gesetztes „nein“, „0“ oder „manuell“ ist ein eigener Wert.
- **Eingefroren beim Eingang.** Ein Vorgang behält die Werte, die bei seinem Eingang galten. Spätere Änderungen gelten nur für neue Vorgänge. Ausnahme ist die Vertragsvorlage: Sie wird erst festgehalten, wenn das Dokument erstellt wird. - **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.** Für eigene Nutzung, Besuch und Sperre stehen Unterlagen, Zahlungen und Gastmails unabhängig von jeder Einstellung auf „Entfällt“ (Herkunft „fest für diese Vorgangsart“). - **A6 fest:** Unterlagen, Zahlungen und Gastmails „Entfällt“.
- **Anfragen:** Unterlagen schicken immer wir (Herkunft „Grundeinstellung“), denn das Angebot ist unser eigenes. - **Anfragen:** Unterlagen schicken immer wir.
- **Die Vorgangsart ergibt sich aus den wirksamen Werten.** Anfrage direkt = A1, über ein Portal = A2; feste Portalbuchung = A3 (wir zahlen und schicken Unterlagen), A4 (Portal zahlt), A5 (Portal schickt Unterlagen); intern = A6. - **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.
--- ---
@@ -40,49 +40,81 @@ ## 3. Einstellbare Prozessparameter
| Einstellung | Standard | Übersteuerbar auf | Wirkung | | Einstellung | Standard | Übersteuerbar auf | Wirkung |
|---|---|---|---| |---|---|---|---|
| Bearbeitung neuer Vorgänge (automatisch / Sie geben frei) | Sie geben frei | Vermieter, Wohnung, Portal (Anfrage und Buchung), Vorgang | Ob Angebote und Unterlagen ohne Klick hinausgehen, sobald nichts fehlt und nichts zu prüfen ist | | 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) | Belegt den Zeitraum bis zum Ablauf. Bei „nein“ gibt es kein Angebot mit Annahmelink ohne ausdrückliche Bestätigung (Hold-0-Schutz bis 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 / Reservierung | 48 Stunden | Vermieter, Wohnung, Portal (Anfrage) | Frist für Angebot und Reservierung | | 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 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, Übersicht „laut Portal“ (Paket 8) | | 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 → keine eigenen Mails | | 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 | | Anreise-Info Tage vorher | 3 | Vermieter, Wohnung | Zeitpunkt der Anreisemail. Die Anreisedaten werden 2 Tage davor geprüft. |
| Vertragsvorlage | Texte der Webseite | Wohnung, Portal (Anfrage und Buchung), Vorgang (Zusammenstellung) | Inhalt von Angebot, Bestätigung und Buchungsunterlagen | | Vertragsvorlage | Texte der Webseite | Wohnung, Portal, Vorgang (Zusammenstellung) | Inhalt von Angebot, Auskunft, Bestätigung und Unterlagen |
**Weitere Einstellungen außerhalb dieser Hierarchie:** ## 4. Weitere Einstellungen
| Einstellung | Wo | Ebene | Wirkung | | Einstellung | Wo | Ebene | Wirkung |
|---|---|---|---| |---|---|---|---|
| Erkannte Buchungen automatisch übernehmen | Portal bearbeiten | Kanal | Aus / Beobachten / Anlegen / Anlegen und weiterbearbeiten (Paket 4) | | **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). |
| Was kommt über dieses Portal? (Anfrage / Portalbuchung / gemischt) | Portal bearbeiten | Kanal | Sofortbuchungsschutz (`CalendarClearance`); „nur Anfragen“ lässt feste Buchungen klären | | **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. |
| Zusätzlich von Hand sperren | Portal bearbeiten | Kanal | Portalaufgaben mit Nachweisstufe | | Gebuchte Leistungen | Wohnung › Zusatzleistungen | Wohnung | werden automatisch zu „Bereitstellen: …“ (nur bei eigenem Preis bzw. A6) |
| Freigabe der Dokumentarten | System › So arbeite ich › Dokumente | Vermieter | Arbeitsfassungen gehen nie automatisch hinaus | | Kurabgabe je Person und Nacht | Wohnung › Preise | Wohnung | Position bei A6 |
| Freigabe / Portalbedingungen einer Vorlage | Vorlagen › Freigabe | Vorlagenversion | Schutz vor unvereinbarten Bedingungen (Paket 3) | | Erkannte Buchungen übernehmen | Portal | Kanal | Aus / Beobachten / Anlegen / Anlegen und weiter (Paket 4) |
| Kurabgabe je Person und Nacht | Wohnung › Preise | Wohnung | Position „Kurabgabe“ bei A6 | | Was kommt über dieses Portal? | Portal | Kanal | Sofortbuchungsschutz (`CalendarClearance`) |
| Testbetrieb / Testadresse | System › Betrieb | Vermieter (Server-Vorgabe `FEWO_MAIL_REDIRECT_TO` gewinnt) | Jede ausgehende Mail nur an die Testadresse | | 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 | | 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
--- ---
## 4. Nachweis an konkreten Vorgängen (Abnahme 01.11.2026) ## 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 | | Konstellation | Erwartung | Beobachtet |
|---|---|---| |---|---|---|
| Standard „automatisch“, Wohnung „24 Stunden“, direkte Anfrage | automatisch (Ihr Standard), 24 h (Wohnung) | identisch (T12) | | Standard automatisch, Wohnung 24 h, direkte Anfrage | automatisch (Standard), 24 h (Wohnung) | identisch (T12) |
| FeWo-direkt Anfrage „manuell“ | manuell, Herkunft Portal | identisch (T12) | | FeWo-direkt feste Buchung, Zahlung Portal | A4, keine Mahnung, Status bleibt „Bestätigt“ trotz „laut Portal bezahlt“ | identisch (T04, T20) |
| FeWo-direkt feste Buchung ohne eigene Bearbeitungseinstellung | automatisch, Herkunft „Ihr Standard“ – erbt | identisch (T12) | | Standard mit Reservierung, Ostseeklar-Anfragen ohne Reservierung und manuell | direkte Anfrage: Angebot und Reservierung. Ostseeklar: keine Reservierung, Aufgabe „Auskunft senden“ | identisch (T24) |
| FeWo-direkt feste Buchung, Zahlung Portal | A4 | identisch (T04, T12) | | Ostseeklar-Anfrage im Vorgang auf automatisch | Auskunft sofort, Wunsch automatisch bestätigt | identisch (T24) |
| Anfrage über FeWo-direkt, im Vorgang auf „automatisch“ umgestellt | Vorgang automatisch, Hinweis „für diesen Vorgang umgestellt“ | identisch (T12, Seite „Wirksame Einstellungen“) | | Wohnung Anreise-Info 5 Tage, Anreisezeit erfragen | Anreisedaten-Aufgabe 7 Tage, Anreisemail 5 Tage vorher | identisch (T24) |
| Familienbesuch | Unterlagen, Zahlungen, Gastmails „Entfällt (fest A6)“ | identisch (T09, Screenshot T12) | | 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) |
--- ---
## 5. Lücken und widersprüchliche Stellen ## 7. Lücken und widersprüchliche Stellen
| Stelle | Beschreibung | Empfehlung | | Stelle | Beschreibung | Empfehlung |
|---|---|---| |---|---|---|
| **Buchungsmodell am Portal und Abwicklungsprofil** | „Was kommt über dieses Portal?“ steuert noch den Sofortbuchungsschutz und den Hinweis „nur Anfragen“. Das Profil je Eingangsart steuert die Abwicklung. Beides kann sich widersprechen, z. B. Modell „nur Anfragen“, aber Abweichungen für feste Buchungen gepflegt. | Beim nächsten Paket das Modell aus den gepflegten Eingangsarten ableiten oder einen Hinweis im Portalformular zeigen. | | 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` usw. und Kanal-Booleans werden seit Paket 1 nicht mehr gelesen, stehen aber noch in der Datenbank. | Nach erfolgreicher Migration auf Produktion entfernen. | | Alte Spalten | `properties.hold_hours`, `pre_reservation_enabled`, `arrival_info_days_before` u. a. werden nicht mehr gelesen. | Nach erfolgreicher Migration auf Produktion entfernen. |
| **Kurabgabe** | Satz nur an der Wohnung, nicht in der Hierarchie; bei Gästen regulärer Buchungen nicht berechnet (die Verträge sagen „vor Ort“). | Bewusst so (B1); erweitern, falls auch reguläre Buchungen sie ausweisen sollen. | | Aufgaben je Aufenthalt | nur je Wohnung, nicht je Portal | ausreichend für 1–3 Wohnungen |
| **Bearbeitungsart bei A6** | wird angezeigt, ist aber ohne Wirkung; bei A6 gibt es nichts Automatisches | ohne Handlungsbedarf | | Feste Fristen | Vorbereitung, Anreisedaten-Prüfung, Auszahlungsprüfung | einstellbar machen, wenn Erfahrungswerte vorliegen |
| **Einstellungen im Vorgang** | Nur die Bearbeitungsart und die Vorlage (im Dokument) lassen sich je Vorgang umstellen, sonst nichts. | entspricht dem Plan | | Gültigkeit der Auskunft | dieselbe Einstellung wie das Angebot | bewusst so (E-026) |
@@ -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.
+28
View File
@@ -1,5 +1,33 @@
# 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). **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).
@@ -36,9 +36,19 @@
<td style="{{ $cell }};{{ $muted }}">{{ \App\Filament\Pages\EffectiveSettings::where($setting) }}</td> <td style="{{ $cell }};{{ $muted }}">{{ \App\Filament\Pages\EffectiveSettings::where($setting) }}</td>
</tr> </tr>
@endforeach @endforeach
<tr>
<td style="{{ $cell }}"><em>Daraus folgt: Antwort auf eine Anfrage</em></td>
@foreach ($block['columns'] as $column)
<td style="{{ $cell }}">{{ \App\Filament\Pages\EffectiveSettings::answer($column['profile']) }}</td>
@endforeach
<td style="{{ $cell }};{{ $muted }}">abgeleitet aus „Reservieren?“ (Paket 7)</td>
</tr>
</tbody> </tbody>
</table> </table>
</div> </div>
@php($stay = \App\Filament\Pages\EffectiveSettings::stay($block['property']))
<p style="margin-top:.8rem;font-size:.85rem"><strong>Aufenthalt (gilt für jeden Eingangsweg dieser Wohnung):</strong> {{ $stay }}</p>
<p style="{{ $muted }}">Einstellen unter Wohnung › Aufenthalt vorbereiten und abschließen bzw. Preise (Kurabgabe). Im einzelnen Vorgang lassen sich Aufgaben ergänzen, erledigen, übergeben oder als „entfällt“ markieren.</p>
</x-filament::section> </x-filament::section>
@endforeach @endforeach
@@ -66,6 +76,16 @@
<td style="{{ $cell }};font-weight:600">{{ $booking->processingMode()->getLabel() }}</td> <td style="{{ $cell }};font-weight:600">{{ $booking->processingMode()->getLabel() }}</td>
<td style="{{ $cell }};{{ $muted }}">{{ $booking->processing_mode !== null ? 'für diesen Vorgang umgestellt' : 'aus dem Profil' }}</td> <td style="{{ $cell }};{{ $muted }}">{{ $booking->processing_mode !== null ? 'für diesen Vorgang umgestellt' : 'aus dem Profil' }}</td>
</tr> </tr>
<tr>
<td style="{{ $cell }}">Dokument, das dieser Vorgang jetzt braucht</td>
<td style="{{ $cell }};font-weight:600">{{ \App\Enums\DocumentKind::forCase($booking)?->getLabel() ?? 'keines von uns (übernimmt das Portal)' }}</td>
<td style="{{ $cell }};{{ $muted }}">aus Vorgangsart und Stand</td>
</tr>
<tr>
<td style="{{ $cell }}">Aufenthalt abgeschlossen / kaufmännisch abgeschlossen</td>
<td style="{{ $cell }};font-weight:600">{{ $booking->status === \App\Enums\BookingStatus::Completed ? 'ja' : 'nein' }} / {{ $booking->settled_at ? 'ja ('.$booking->settled_at->format('d.m.Y').')' : 'nein' }}</td>
<td style="{{ $cell }};{{ $muted }}">{{ $booking->settled_at === null && in_array($booking->status, [\App\Enums\BookingStatus::Completed, \App\Enums\BookingStatus::Cancelled], true) ? implode(' ', \App\Process\CaseClosure::commercialPoints($booking)) : 'abgeleitet aus Aufgaben und Geld' }}</td>
</tr>
</table> </table>
@endif @endif
</x-filament::section> </x-filament::section>
+84
View File
@@ -0,0 +1,84 @@
@php($owner = \App\Documents\OfferTerms::owner($booking))
@php($money = fn (int $cents): string => \App\Support\Money::format($cents))
@extends('theme::layouts.app', ['title' => 'Unverbindliche Auskunft'])
@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">Unverbindliche Auskunft · Anfrage {{ $booking->reference }}</p>
<h1 class="heading-display">{{ $booking->property->name }}</h1>
<p class="mt-2 text-muted">für {{ $booking->guestName() }}</p>
@if (session('information.success'))
<div class="mt-8 rounded border border-accent bg-surface p-5" role="status">{{ session('information.success') }}</div>
@elseif (session('information.error') || $problem)
<div class="mt-8 rounded border border-line bg-surface p-5" role="alert">{{ session('information.error') ?? $problem }}</div>
@endif
<div class="mt-8 rounded border border-line p-5">
<p class="font-semibold">Dies ist noch keine Buchung und keine Reservierung.</p>
<p class="mt-2 text-muted">Preis und Verfügbarkeit gelten für den Stand vom {{ $booking->information_sent_at?->format('d.m.Y, H:i') }} Uhr. Der Zeitraum kann in der Zwischenzeit anderweitig vergeben werden. Wenn Sie die Buchung anfragen, prüfen wir beides erneut; verbindlich wird sie erst mit unserer Buchungsbestätigung.</p>
</div>
<section class="mt-10 rounded bg-surface p-7" aria-labelledby="information-stay">
<h2 id="information-stay" class="font-display text-2xl">Ihr Aufenthalt</h2>
<dl class="mt-4 grid grid-cols-[auto_1fr] gap-x-6 gap-y-1">
<dt class="text-muted">Anreise</dt><dd>{{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif</dd>
<dt class="text-muted">Abreise</dt><dd>{{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif</dd>
<dt class="text-muted">Nächte</dt><dd>{{ $booking->nights() }}</dd>
<dt class="text-muted">Personen</dt><dd>{{ $booking->guests }}</dd>
<dt class="text-muted">Anfragen bis</dt><dd>{{ $booking->information_valid_until?->format('d.m.Y, H:i') }} Uhr</dd>
</dl>
<h2 class="mt-8 font-display text-2xl">Preis (Stand der Auskunft)</h2>
<table class="mt-3 w-full">
@foreach ($booking->quote['lines'] ?? [] as $line)
<tr class="border-b border-line"><td class="py-2">{{ $line['label'] }}</td><td class="py-2 text-right whitespace-nowrap">{{ $money($line['amount']) }}</td></tr>
@endforeach
<tr class="font-semibold"><td class="pt-3">Gesamtpreis</td><td class="pt-3 text-right">{{ $money((int) $booking->total) }}</td></tr>
</table>
<p class="mt-3 text-sm text-muted">Anzahlung {{ $money((int) $booking->deposit) }} nach der Buchungsbestätigung, Restbetrag {{ $money((int) $booking->total - (int) $booking->deposit) }} bis {{ $booking->balance_due_on?->format('d.m.Y') }}. Die Kurtaxe ist nicht enthalten und wird vor Ort entrichtet.</p>
@if ($booking->offer_message)
<p class="mt-6 rounded border border-line p-4">{{ $booking->offer_message }}</p>
@endif
@php($contractDocument = \App\Documents\OfferTerms::document($booking))
@if ($contractDocument)
<h2 class="mt-8 font-display text-2xl">Mietbedingungen</h2>
<div class="prose-theme mt-3">{!! $contractDocument['body'] !!}</div>
@if ($contractDocument['annex'])
<h3 class="mt-6 font-semibold">{{ $contractDocument['annex_title'] ?: 'Anlage' }}</h3>
<div class="prose-theme mt-2">{!! $contractDocument['annex'] !!}</div>
@endif
@else
<h2 class="mt-8 font-display text-2xl">Bedingungen</h2>
<div class="prose-theme mt-3">{{ $booking->offerHtml('contract.terms') }}</div>
@if ($booking->offerText('stay.cancellation'))
<h3 class="mt-6 font-semibold">Rücktritt / Stornierung</h3>
<div class="prose-theme mt-2">{{ $booking->offerHtml('stay.cancellation') }}</div>
@endif
@endif
</section>
@if ($canAsk && ! session('information.success'))
<section class="mt-8 rounded bg-surface p-7" aria-label="Buchung anfragen">
<form method="post" action="{{ $wishUrl }}">
@csrf
<label class="flex items-start gap-3">
<input type="checkbox" name="terms" value="1" required class="mt-1">
<span>Ich habe die Angaben und Bedingungen gelesen und möchte zu diesen Bedingungen buchen.</span>
</label>
@error('terms')<p class="mt-1 text-sm" role="alert">{{ $message }}</p>@enderror
<p class="mt-4 text-sm text-muted">Mit „Buchung anfragen“ senden Sie uns Ihren Buchungswunsch. Wir prüfen Verfügbarkeit und Preis erneut. Der Vertrag kommt erst mit unserer Buchungsbestätigung zustande, die Sie per E-Mail erhalten.</p>
<button type="submit" class="btn-accent mt-4 w-full sm:w-auto">Buchung anfragen</button>
</form>
</section>
@endif
<p class="mt-8 text-sm text-muted">Fragen? {{ $owner['name'] ?? '' }} · {{ $owner['phone'] ?? '' }} · <a class="underline" href="mailto:{{ $owner['email'] ?? '' }}">{{ $owner['email'] ?? '' }}</a></p>
</div>
@endsection
@@ -5,7 +5,7 @@
<p class="mt-3 text-emerald-900"> <p class="mt-3 text-emerald-900">
Ihre Anfrage <strong>{{ $booking->reference }}</strong> ist eingegangen. Wir haben den Zeitraum Ihre Anfrage <strong>{{ $booking->reference }}</strong> ist eingegangen. Wir haben den Zeitraum
<strong>{{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}</strong> <strong>{{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}</strong>
@if ($booking->isHoldActive())bis <strong>{{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr</strong> für Sie vorgemerkt.@elseif ($booking->status === \App\Enums\BookingStatus::OfferSent)bereits geprüft – unser Angebot ist unterwegs zu Ihnen.@else– eine Reservierung ist damit noch nicht verbunden.@endif @if ($booking->isHoldActive())bis <strong>{{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr</strong> für Sie vorgemerkt.@elseif ($booking->status === \App\Enums\BookingStatus::OfferSent)bereits geprüft – unser Angebot ist unterwegs zu Ihnen.@elseif ($booking->information_version > 0)geprüft – unsere unverbindliche Auskunft ist unterwegs zu Ihnen. Reserviert ist der Zeitraum damit noch nicht.@else– eine Reservierung ist damit noch nicht verbunden.@endif
</p> </p>
<p class="mt-2 text-emerald-900">Eine Bestätigung mit allen Details haben wir an {{ $booking->guest->email }} gesendet.</p> <p class="mt-2 text-emerald-900">Eine Bestätigung mit allen Details haben wir an {{ $booking->guest->email }} gesendet.</p>
</div> </div>
@@ -219,7 +219,11 @@ class="mt-5 w-full rounded-xl bg-accent px-4 py-3 font-semibold text-accent-ink
<span wire:loading.remove wire:target="submit">Unverbindlich anfragen</span> <span wire:loading.remove wire:target="submit">Unverbindlich anfragen</span>
<span wire:loading wire:target="submit">Wird gesendet …</span> <span wire:loading wire:target="submit">Wird gesendet …</span>
</button> </button>
@if ($this->reservesDates)
<p class="mt-2 text-center text-xs text-muted">Kostenlos und unverbindlich. Wir halten den Termin für Sie frei und senden Ihnen ein Angebot per E-Mail – verbindlich wird die Buchung erst, wenn Sie es annehmen.</p> <p class="mt-2 text-center text-xs text-muted">Kostenlos und unverbindlich. Wir halten den Termin für Sie frei und senden Ihnen ein Angebot per E-Mail – verbindlich wird die Buchung erst, wenn Sie es annehmen.</p>
@else
<p class="mt-2 text-center text-xs text-muted">Kostenlos und unverbindlich. Sie erhalten eine Auskunft zu Preis und Verfügbarkeit per E-Mail und können daraus die Buchung anfragen – verbindlich wird sie erst mit unserer Bestätigung.</p>
@endif
</form> </form>
</section> </section>
</div> </div>
@@ -3,7 +3,9 @@
Guten Tag {{ $booking->guest->full_name }}, Guten Tag {{ $booking->guest->full_name }},
@if ($booking->accepted_at) @if ($booking->accepted_at && ($booking->acceptance['via'] ?? null) === 'booking_wish')
vielen Dank für Ihren Buchungswunsch vom {{ $booking->accepted_at->format('d.m.Y') }}. Wir haben Verfügbarkeit und Preis erneut geprüft und bestätigen Ihre Buchung der **{{ $booking->property->name }}** hiermit verbindlich.
@elseif ($booking->accepted_at)
vielen Dank – Sie haben unser Angebot am {{ $booking->accepted_at->format('d.m.Y') }} um {{ $booking->accepted_at->format('H:i') }} Uhr angenommen. Damit ist Ihre Buchung der **{{ $booking->property->name }}** verbindlich. vielen Dank – Sie haben unser Angebot am {{ $booking->accepted_at->format('d.m.Y') }} um {{ $booking->accepted_at->format('H:i') }} Uhr angenommen. Damit ist Ihre Buchung der **{{ $booking->property->name }}** verbindlich.
@else @else
wir freuen uns, Ihre Buchung der **{{ $booking->property->name }}** verbindlich zu bestätigen. wir freuen uns, Ihre Buchung der **{{ $booking->property->name }}** verbindlich zu bestätigen.
@@ -0,0 +1,32 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null">
@if ($outcome === 'pending')
# Ihr Buchungswunsch ist eingegangen
Guten Tag {{ $booking->guest->full_name }},
vielen Dank – Ihr Buchungswunsch für die **{{ $booking->property->name }}** vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} ist bei uns 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, die Sie mit dem Mietvertrag per E-Mail erhalten.
@else
# Ihr Buchungswunsch {{ $booking->reference }}
Guten Tag {{ $booking->guest->full_name }},
vielen Dank für Ihren Buchungswunsch für die **{{ $booking->property->name }}**.
@if ($outcome === 'unavailable')
Leider ist der Zeitraum vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} inzwischen vergeben.
@else
Leider können wir Ihnen den Zeitraum vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} nicht bestätigen.
@endif
Es ist keine Buchung zustande gekommen, und es entstehen Ihnen keine Kosten.
Vielleicht passt ein anderer Termin? Die freien Zeiträume finden Sie jederzeit in unserem Belegungskalender.
<x-mail::button :url="route('booking.create')">
Freie Termine ansehen
</x-mail::button>
@endif
Herzliche Grüße<br>
{{ config('fewo.owner.name') }}
</x-mail::message>
@@ -0,0 +1,21 @@
<x-mail::message :message="$message ?? null">
# Buchungswunsch {{ $booking->reference }}
{{ $booking->guestName() }} hat aus der Auskunft die Buchung angefragt: {{ $booking->property->name }}, {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}, {{ $booking->guests }} Personen.
@if ($outcome === 'confirmed')
Alles war in Ordnung (Zeitraum frei, Kalender aktuell, Preis unverändert). Die Buchung ist **automatisch verbindlich bestätigt**; der Gast hat die Bestätigung mit dem Mietvertrag erhalten.
@elseif ($outcome === 'unavailable')
Der Zeitraum war inzwischen vergeben. **Es ist keine Buchung entstanden**; der Gast hat eine freundliche Absage erhalten.
@else
**Bitte bestätigen oder absagen.** Bis dahin ist nichts verbindlich und der Zeitraum nicht reserviert.
@foreach ((array) ($booking->wish['findings'] ?? []) as $finding)
- {{ $finding }}
@endforeach
@endif
<x-mail::button :url="$caseUrl">
Vorgang öffnen
</x-mail::button>
</x-mail::message>
@@ -0,0 +1,33 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null">
# Unverbindliche Auskunft für die {{ $booking->property->name }}
Guten Tag {{ $booking->guest->full_name }},
vielen Dank für Ihre Anfrage. Hier unsere **unverbindliche Auskunft** – noch **keine Buchung und keine Reservierung**:
**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br>
**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br>
**Personen:** {{ $booking->guests }}<br>
**Anfragenummer:** {{ $booking->reference }}
@include('mail.partials.quote')
@if ($booking->offer_message)
{{ $booking->offer_message }}
@endif
Preis und Verfügbarkeit gelten für den Stand vom **{{ $booking->information_sent_at?->format('d.m.Y, H:i') }} Uhr**. Der Zeitraum ist für Sie nicht reserviert und kann in der Zwischenzeit anderweitig vergeben werden.
Möchten Sie buchen? Dann fragen Sie die Buchung bis **{{ $booking->information_valid_until?->format('d.m.Y, H:i') }} Uhr** an:
<x-mail::button :url="$url">
Auskunft ansehen und Buchung anfragen
</x-mail::button>
Wir prüfen dann Verfügbarkeit und Preis erneut. **Verbindlich wird die Buchung erst mit unserer Buchungsbestätigung**; mit ihr erhalten Sie den Mietvertrag.
Bei Fragen antworten Sie einfach auf diese E-Mail oder rufen Sie uns an: {{ config('fewo.owner.phone') }}
Herzliche Grüße<br>
{{ config('fewo.owner.name') }}
</x-mail::message>
@@ -1,9 +1,17 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null"> <x-mail::message :site="$booking->website()" :message="$message ?? null">
@if ($booking->information_version > 0 && $booking->offer_version === 0)
# Auskunft abgelaufen
Zur unverbindlichen Auskunft **{{ $booking->reference }}** an {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) kam kein Buchungswunsch. Der Zeitraum war nicht reserviert; die Anfrage ist ohne Buchung beendet.
Sie können weiterhin eine neue Auskunft senden.
@else
# {{ $booking->offer_version > 0 ? 'Angebot abgelaufen' : 'Vormerkung abgelaufen' }} # {{ $booking->offer_version > 0 ? 'Angebot abgelaufen' : 'Vormerkung abgelaufen' }}
Die Anfrage **{{ $booking->reference }}** von {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) {{ $booking->offer_version > 0 ? 'wurde vom Gast nicht rechtzeitig angenommen' : 'wurde nicht rechtzeitig beantwortet' }}. Der Zeitraum ist im Kalender wieder frei. Die Anfrage **{{ $booking->reference }}** von {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) {{ $booking->offer_version > 0 ? 'wurde vom Gast nicht rechtzeitig angenommen' : 'wurde nicht rechtzeitig beantwortet' }}. Der Zeitraum ist im Kalender wieder frei.
Sie können weiterhin ein (neues) Angebot senden, sofern der Zeitraum noch frei ist. Sie können weiterhin ein (neues) Angebot senden, sofern der Zeitraum noch frei ist.
@endif
<x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])"> <x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])">
Anfrage öffnen Anfrage öffnen
@@ -14,7 +14,11 @@
@include('mail.partials.quote') @include('mail.partials.quote')
@if ($booking->hold_expires_at === null && ! $booking->process()->preReservation())
Wir prüfen Ihre Anfrage und senden Ihnen in Kürze eine **unverbindliche Auskunft** per E-Mail. Daraus können Sie die Buchung anfragen; verbindlich wird sie erst mit unserer Buchungsbestätigung.
@else
Wir prüfen Ihre Anfrage und senden Ihnen in Kürze **unser Angebot** per E-Mail. Verbindlich wird die Buchung erst, wenn Sie dieses Angebot annehmen. Wir prüfen Ihre Anfrage und senden Ihnen in Kürze **unser Angebot** per E-Mail. Verbindlich wird die Buchung erst, wenn Sie dieses Angebot annehmen.
@endif
@if ($booking->message) @if ($booking->message)
**Ihre Nachricht:**<br> **Ihre Nachricht:**<br>
+4
View File
@@ -2,6 +2,7 @@
use App\Http\Controllers\ChangeController; use App\Http\Controllers\ChangeController;
use App\Http\Controllers\ChannelController; use App\Http\Controllers\ChannelController;
use App\Http\Controllers\InformationController;
use App\Http\Controllers\MarketingConsentController; use App\Http\Controllers\MarketingConsentController;
use App\Http\Controllers\OfferController; use App\Http\Controllers\OfferController;
use App\Http\Controllers\PageController; use App\Http\Controllers\PageController;
@@ -27,6 +28,9 @@
Route::get('/angebot/aenderung/{change}', [ChangeController::class, 'show'])->name('changes.show')->middleware('throttle:30,1'); Route::get('/angebot/aenderung/{change}', [ChangeController::class, 'show'])->name('changes.show')->middleware('throttle:30,1');
Route::post('/angebot/aenderung/{change}/annehmen', [ChangeController::class, 'accept'])->name('changes.accept')->middleware('throttle:10,1'); Route::post('/angebot/aenderung/{change}/annehmen', [ChangeController::class, 'accept'])->name('changes.accept')->middleware('throttle:10,1');
Route::post('/angebot/aenderung/{change}/ablehnen', [ChangeController::class, 'decline'])->name('changes.decline')->middleware('throttle:10,1'); Route::post('/angebot/aenderung/{change}/ablehnen', [ChangeController::class, 'decline'])->name('changes.decline')->middleware('throttle:10,1');
// Information "unter Vorbehalt" of a request without a hold and the guest's booking wish (package 7).
Route::get('/angebot/auskunft/{booking}', [InformationController::class, 'show'])->name('information.show')->middleware('throttle:30,1');
Route::post('/angebot/auskunft/{booking}/buchung-anfragen', [InformationController::class, 'wish'])->name('information.wish')->middleware('throttle:10,1');
}); });
Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1');
+4 -2
View File
@@ -97,14 +97,16 @@ public function test_without_pre_reservation_a_request_blocks_nothing(): void
Mail::assertSent(ReservationReceived::class, fn (ReservationReceived $mail): bool => str_contains($mail->render(), 'nicht reserviert') && ! str_contains($mail->render(), 'vorgemerkt')); Mail::assertSent(ReservationReceived::class, fn (ReservationReceived $mail): bool => str_contains($mail->render(), 'nicht reserviert') && ! str_contains($mail->render(), 'vorgemerkt'));
} }
public function test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why(): void public function test_automatic_mode_without_pre_reservation_waits_for_the_released_information_text_and_says_why(): void
{ {
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]); Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]);
$booking = $this->request(); $booking = $this->request();
// Package 7: a request without a hold is answered with an information; its texts start as a working draft.
$this->assertSame(BookingStatus::Reserved, $booking->status); $this->assertSame(BookingStatus::Reserved, $booking->status);
$this->assertStringContainsString('vorreservierung', mb_strtolower($booking->internal_notes)); $this->assertSame(0, $booking->information_version);
$this->assertStringContainsString('auskunft unter vorbehalt', mb_strtolower($booking->internal_notes));
Mail::assertNotSent(OfferMade::class); Mail::assertNotSent(OfferMade::class);
Mail::assertSent(ReservationReceived::class, 1); Mail::assertSent(ReservationReceived::class, 1);
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->blockers !== []); Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->blockers !== []);
+1 -1
View File
@@ -107,7 +107,7 @@ public function test_a_booking_mail_becomes_a_case_and_the_later_calendar_entry_
// The portal collects the money: no payment tasks of our own; nothing went to the guest. // The portal collects the money: no payment tasks of our own; nothing went to the guest.
$this->assertFalse($case->fresh()->wantsPaymentTasks()); $this->assertFalse($case->fresh()->wantsPaymentTasks());
$this->assertSame('läuft über das Portal', collect(CaseActivities::for($case->fresh()))->firstWhere('key', 'payment')?->detail); $this->assertSame('zieht das Portal ein', collect(CaseActivities::for($case->fresh()))->firstWhere('key', 'payment')?->detail);
Mail::assertNotSent(BookingDocumentation::class); Mail::assertNotSent(BookingDocumentation::class);
Mail::assertNotSent(BookingConfirmed::class); Mail::assertNotSent(BookingConfirmed::class);
} }
@@ -0,0 +1,624 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\ExpireReservations;
use App\Actions\ProcessPortalMail;
use App\Actions\RecordPayment;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Channels\Mail\PortalMail;
use App\Documents\DocumentReleases;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CaseIntakeMode;
use App\Enums\CaseType;
use App\Enums\ChangeBasis;
use App\Enums\DocumentKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Enums\ProcessingMode;
use App\Filament\Pages\EffectiveSettings;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Mail\ArrivalInformation;
use App\Mail\BookingConfirmed;
use App\Mail\BookingWishAnswered;
use App\Mail\BookingWishNotice;
use App\Mail\InformationSent;
use App\Mail\OfferMade;
use App\Mail\ReviewRequest;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Extra;
use App\Models\InboxMessage;
use App\Models\Property;
use App\Models\Season;
use App\Models\User;
use App\Pricing\CaseMoney;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\CaseClosure;
use App\Process\WorkList;
use App\Support\Content;
use App\Support\Money;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;
use Tests\TestCase;
/**
* Business acceptance T16–T25 (docs/Prozessarchitektur/END_TO_END_ABNAHME.md): packages 7 and 9 played through the
* way the landlord and the guest work – the case page and its actions, the guest's links, the daily run – and checked
* by what they see: the case, its next step, the calendar, the tasks, the money and the mails. T23 (real SMTP) lives in
* {@see TestOperationSmtpAcceptanceTest}.
*/
class EndToEndStayAcceptanceTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private Channel $manualPortal;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
app(TenantContext::class)->set($this->property->tenant);
$this->manualPortal = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'booking_model' => 'inquiry', 'connector' => 'ical', 'import_enabled' => false, 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']);
Mail::fake();
Storage::fake('local');
Http::fake(fn () => Http::response('', 500));
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
/** T16 – hold 0: information "unter Vorbehalt", nothing reserved, the guest asks for the booking, the landlord confirms. */
public function test_t16_information_without_hold_and_booking_wish(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$booking = $this->request();
$this->assertNull($booking->hold_expires_at);
$this->assertSame(0, Booking::query()->occupying()->count(), 'the calendar stays free');
$this->assertSame('Unverbindliche Auskunft prüfen und senden', WorkList::items()[0]['title']);
$this->assertSame(DocumentKind::Information, DocumentKind::forCase($booking));
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])
->assertNotified('Auskunft gesendet');
$booking->refresh();
$this->assertSame([BookingStatus::Reserved, 1, 0, null], [$booking->status, $booking->information_version, $booking->offer_version, $booking->hold_expires_at]);
$this->assertSame(0, Booking::query()->occupying()->count(), 'still nothing reserved');
Mail::assertNotSent(OfferMade::class);
Mail::assertSent(InformationSent::class, fn (InformationSent $mail): bool => str_contains($mail->render(), 'keine Buchung und keine Reservierung') && ! str_contains($mail->render(), 'annehmen'));
$show = URL::temporarySignedRoute('information.show', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->get($show)->assertOk()->assertSee('Dies ist noch keine Buchung und keine Reservierung.')->assertSee('Buchung anfragen')->assertDontSee('Angebot annehmen');
$wish = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'noch nicht verbindlich'));
$this->post($wish, ['terms' => '1'])->assertRedirect()->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'bereits vor'));
$booking->refresh();
$this->assertSame(BookingStatus::Reserved, $booking->status, 'a wish is no booking');
$this->assertSame(0, Booking::query()->occupying()->count());
$this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->count(), 'one task however often the guest clicks');
Mail::assertSent(BookingWishAnswered::class, 1);
$this->assertSame('Buchungswunsch bestätigen?', WorkList::items()[0]['title']);
$this->assertSame('decideWish', CaseActivities::next($booking)?->action);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('decideWish', ['decision' => 'confirm'])
->assertNotified('Buchung bestätigt');
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertSame('booking_wish', $booking->acceptance['via']);
$this->assertSame('Ingrid', $booking->acceptance['confirmed_by']);
$this->assertNotNull($booking->contract_path);
Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => str_contains($mail->render(), 'Buchungswunsch'));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->exists(), 'the manual portal is blocked now');
$this->assertStringContainsString('Buchungswunsch', $booking->events()->where('type', 'wish')->reorder()->orderByDesc('id')->value('summary'));
}
/** T16 (old link, expiry): a replaced information no longer works; an unanswered one ends without booking. */
public function test_t16_old_links_and_unanswered_information(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$booking = $this->request();
$this->sendInformation($booking);
$this->sendInformation($booking->fresh());
$booking->refresh();
$this->assertSame(2, $booking->information_version);
$old = URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => 1]);
$this->post($old, ['terms' => '1'])->assertSessionHas('information.error', fn (string $text): bool => str_contains($text, 'nicht mehr aktuell'));
$this->assertNull($booking->fresh()->wish_at);
$this->travelTo($booking->information_valid_until->addMinute());
app(ExpireReservations::class)->handle();
$this->assertSame(BookingStatus::Expired, $booking->fresh()->status);
$this->flushSession();
$current = URL::temporarySignedRoute('information.show', now()->addDay(), ['booking' => $booking, 'v' => 2]);
$this->get($current)->assertOk()->assertSee('abgeschlossen');
}
/** T17 – the dates were given away between information and wish: no booking, a friendly answer, a note for the landlord. */
public function test_t17_booking_wish_after_the_dates_were_given_away(): void
{
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$first = $this->request();
$this->sendInformation($first);
$second = $this->request('zweite@example.org');
$this->sendInformation($second);
// Meanwhile the first guest books and a portal reports an occupation that touches the second guest's stay.
$this->wish($first->fresh());
Livewire::test(ViewBooking::class, ['record' => $first->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']);
$this->assertSame(BookingStatus::Confirmed, $first->fresh()->status);
$this->post(URL::temporarySignedRoute('information.wish', $second->fresh()->information_valid_until, ['booking' => $second, 'v' => 1]), ['terms' => '1'])
->assertSessionHas('information.success', fn (string $text): bool => str_contains($text, 'inzwischen vergeben'));
$second->refresh();
$this->assertSame(BookingStatus::Declined, $second->status);
$this->assertSame(1, Booking::query()->occupying()->count(), 'no double booking');
Mail::assertSent(BookingWishAnswered::class, fn (BookingWishAnswered $mail): bool => $mail->outcome === 'unavailable' && $mail->booking->is($second));
Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'unavailable');
$this->assertTrue(InboxMessage::query()->where('subject', 'like', '%Zeitraum inzwischen vergeben%')->exists());
// A portal occupation imported meanwhile has the same effect.
$third = $this->request('dritte@example.org', '2026-11-21', '2026-11-24');
$this->sendInformation($third);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'channel', 'channel_id' => $this->manualPortal->id, 'starts_on' => '2026-11-22', 'ends_on' => '2026-11-26']);
$this->wish($third->fresh());
$this->assertSame(BookingStatus::Declined, $third->fresh()->status);
}
/** T17 – price changed, calendar not current: even in automatic mode the wish waits for the landlord, with the reasons. */
public function test_t17_changed_price_and_stale_calendar_need_the_landlord(): void
{
$this->automaticWithoutHold();
$booking = $this->request();
$this->assertSame(1, $booking->fresh()->information_version, 'sent automatically');
Season::query()->whereDate('starts_on', '<=', '2026-11-07')->whereDate('ends_on', '>', '2026-11-07')->update(['nightly_rate' => 9900]);
Channel::factory()->for($this->property)->create(['name' => 'Kalenderportal', 'connector' => 'ical', 'import_enabled' => true, 'status' => 'active', 'settings' => ['import_url' => 'https://portal.example/cal.ics'], 'last_success_at' => now()->subDays(2)]);
$this->wish($booking->fresh());
$booking->refresh();
$this->assertSame(BookingStatus::Reserved, $booking->status);
$findings = implode(' ', $booking->wish['findings']);
$this->assertStringContainsString('Der Preis hat sich seit der Auskunft geändert', $findings);
$this->assertStringContainsString('Kalenderstand von Kalenderportal', $findings);
$task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->sole();
$this->assertStringContainsString('Preis', (string) $task->note);
// The landlord honours the price of the information (the guest was told it).
$told = $booking->total;
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('decideWish', ['decision' => 'confirm']);
$this->assertSame([BookingStatus::Confirmed, $told], [$booking->fresh()->status, $booking->fresh()->total]);
}
/** T18 – automatic and manual handling of a wish; two guests for the same dates never both get the booking. */
public function test_t18_automatic_wish_is_confirmed_at_once_and_the_competitor_gets_a_refusal(): void
{
$this->automaticWithoutHold();
$first = $this->request();
$second = $this->request('zweite@example.org');
Mail::assertSent(InformationSent::class, 2);
$this->wish($first->fresh());
$first->refresh();
$this->assertSame(BookingStatus::Confirmed, $first->status, 'confirmed automatically after the new check');
$this->assertSame('automatisch nach erneuter Prüfung', $first->acceptance['confirmed_by']);
Mail::assertSent(BookingConfirmed::class, 1);
Mail::assertSent(BookingWishNotice::class, fn (BookingWishNotice $mail): bool => $mail->outcome === 'confirmed');
$this->wish($second->fresh());
$this->assertSame(BookingStatus::Declined, $second->fresh()->status);
$this->assertSame(1, Booking::query()->occupying()->count());
Mail::assertSent(BookingConfirmed::class, 1);
}
/** T19 – A1 from the request to the closed stay: offer, payments, preparation, services, arrival, departure, closing. */
public function test_t19_complete_a1_process_until_the_stay_is_closed(): void
{
$this->property->update(['asks_arrival_time' => true, 'stay_tasks' => [
['title' => 'Schlüsselübergabe', 'when' => 'on_arrival', 'responsible' => 'Nachbarin Frau Kruse', 'applies_to' => ['rental']],
['title' => 'Endreinigung', 'when' => 'after_departure', 'responsible' => 'Reinigung Müller', 'applies_to' => ['rental', 'private']],
]]);
$booking = $this->request();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('sendOffer')->arguments([]), ['acknowledged' => true]);
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1']);
$booking->refresh();
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today());
app(RecordPayment::class)->handle($booking->fresh(), (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today());
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
// Five days before arrival: the arrival time is missing, the stay tasks are planned.
$this->travelTo(CarbonImmutable::parse('2026-11-02 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$tasks = BookingTask::query()->where('booking_id', $booking->id)->get();
$this->assertSame(1, $tasks->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'once, however often the run repeats');
$this->assertSame(['Endreinigung', 'Schlüsselübergabe'], $tasks->where('kind', BookingTaskKind::Service)->pluck('title')->sort()->values()->all());
$this->assertSame('Anreisedaten beim Gast erfragen', CaseActivities::next($booking->fresh())?->label);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('arrivalDetails', ['arrival_time' => 'gegen 16 Uhr', 'phone' => '0171 1234567', 'email' => 'gesa@example.org']);
$this->assertSame(BookingTaskStatus::Done, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->value('status'));
$this->travelTo(CarbonImmutable::parse('2026-11-04 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertSent(ArrivalInformation::class, 1);
// Arrival: the key handover is done.
$this->travelTo(CarbonImmutable::parse('2026-11-07 15:00'));
$handover = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Schlüsselübergabe')->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $handover->id, 'outcome' => 'done', 'note' => 'Schlüssel übergeben']);
// After the departure the cleaning is still open: the stay waits for it.
$this->travelTo(CarbonImmutable::parse('2026-11-11 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
$this->assertStringContainsString('Endreinigung', (string) collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'closure')?->detail);
$cleaning = BookingTask::query()->where('booking_id', $booking->id)->where('title', 'Endreinigung')->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('completeTask', ['task' => $cleaning->id, 'outcome' => 'handed_over', 'handed_to' => 'Reinigung Müller', 'note' => 'erledigt laut Rückmeldung']);
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertNotNull($booking->settled_at, 'fully paid: nothing open commercially');
$this->travelTo(CarbonImmutable::parse('2026-11-14 08:00'));
app(RequestReviews::class)->handle();
$activities = collect(CaseActivities::for($booking));
$this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'closure')->state);
$this->assertSame(ActivityState::Done, $activities->firstWhere('key', 'settlement')->state);
$this->assertStringContainsString('Übergeben an Reinigung Müller', (string) $activities->firstWhere('label', 'Endreinigung')?->detail);
Mail::assertSent(ReviewRequest::class, 1);
$this->assertSame([], collect(WorkList::items())->where('url', 'like', '%bookings/'.$booking->id.'%')->all());
}
/** T20 – A4: portal payment, stay, later payout; "paid according to the portal" never reads as money received. */
public function test_t20_complete_a4_process_with_portal_payment_and_later_payout(): void
{
$fewo = $this->fewo(['process_overrides' => ['booking' => ['payments' => 'portal', 'guest_messages' => 'portal']]]);
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-A4FLOW");
$booking = Booking::query()->sole();
$this->assertSame(CaseType::A4, $booking->case_type);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22',
'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69']],
'paid' => [['amount' => '979.51', 'paid_on' => '2026-10-21']]]);
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status, 'paid to the portal is not "Anzahlung erhalten" / "Bezahlt"');
$this->assertSame(0, CaseMoney::of($booking)->receivedOnAccount());
$history = $booking->events()->pluck('summary')->implode(' | ');
$this->assertStringContainsString('Laut FeWo-direkt hat der Gast '.Money::format(97951).' an das Portal gezahlt – noch kein Geld bei uns', $history);
$this->assertStringNotContainsString('Anzahlung eingegangen', $history);
$activities = collect(CaseActivities::for($booking));
$this->assertSame(ActivityState::External, $activities->firstWhere('key', 'arrival_info')->state);
$this->assertStringContainsString('(angekündigt)', $activities->firstWhere('key', 'arrival_info')->detail);
$this->assertSame(ActivityState::Waiting, $activities->firstWhere('key', 'payout')->state);
$this->travelTo(CarbonImmutable::parse('2026-12-04 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertNotSent(ArrivalInformation::class);
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])->count());
$this->travelTo(CarbonImmutable::parse('2026-12-15 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status, 'the outstanding payout does not hold the stay up');
$this->assertNull($booking->settled_at);
$payout = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PayoutCheck)->sole();
$this->assertSame('2026-12-28', $payout->due_on->toDateString());
$this->assertSame(ActivityState::Waiting, collect(CaseActivities::for($booking))->firstWhere('key', 'task_payout_check')->state, 'not due yet');
$this->assertContains('Die Auszahlung von FeWo-direkt ist noch nicht eingegangen.', CaseClosure::commercialPoints($booking));
$this->travelTo(CarbonImmutable::parse('2026-12-29 08:00'));
$this->assertSame('Auszahlung des Portals prüfen', collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id))['title'] ?? null);
app(RecordPayment::class)->handle($booking->fresh(), 89469, CarbonImmutable::today(), PaymentMethod::Transfer, kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$booking->refresh();
$this->assertSame(BookingTaskStatus::Done, $payout->fresh()->status);
$this->assertNotNull($booking->settled_at, 'commercially settled once the payout arrived');
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertSame($fewo->id, $booking->origin_channel_id);
}
/** T21 – A6 family stay: services prepared, no guest mails, closing without reminders; the agreed money settles it. */
public function test_t21_family_stay_with_preparation_and_closing(): void
{
$this->property->update(['tourist_tax_rate' => 250, 'stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental', 'private']]]]);
$linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 1800, 'pricing' => 'per_item', 'is_active' => true]);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::OWN_USE, 'internal_kind' => InternalKind::PrivateStay->value, 'occasion' => 'Besuch von Tochter Anna', 'property_id' => $this->property->id, 'guests' => 3, 'arrival' => '2026-11-14', 'departure' => '2026-11-19',
'stay_first_name' => 'Anna', 'stay_last_name' => 'Stommer', 'stay_email' => 'anna@example.org', 'rent' => '0', 'tourist_tax_persons' => 2,
'items' => [['extra_id' => $linen->id, 'quantity' => 3]]])
->call('create')->assertHasNoFormErrors();
$visit = Booking::query()->sole();
$this->travelTo(CarbonImmutable::parse('2026-11-10 08:00'));
app(SendBookingReminders::class)->handle();
$titles = BookingTask::query()->where('booking_id', $visit->id)->pluck('title')->sort()->values()->all();
$this->assertSame(['Bereitstellen: 3 × Wäschepaket', 'Endreinigung'], $titles);
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('kind', BookingTaskKind::ArrivalDetails)->count(), 'no arrival details for family');
$this->travelTo(CarbonImmutable::parse('2026-11-20 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertSame(BookingStatus::Confirmed, $visit->fresh()->status, 'the stay waits for its open tasks');
foreach (BookingTask::query()->where('booking_id', $visit->id)->get() as $task) {
Livewire::test(ViewBooking::class, ['record' => $visit->getRouteKey()])->callAction('completeTask', ['task' => $task->id, 'outcome' => 'done']);
}
app(SendBookingReminders::class)->handle();
app(RequestReviews::class)->handle();
$visit->refresh();
$this->assertSame(BookingStatus::Completed, $visit->status);
$this->assertNull($visit->settled_at);
$this->assertSame(['Vereinbarte Zahlung noch offen: '.Money::format(7900).' (ohne Erinnerungen).'], CaseClosure::commercialPoints($visit));
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->where('status', BookingTaskStatus::Open)->count(), 'no reminders of any kind');
app(RecordPayment::class)->handle($visit, 7900, CarbonImmutable::today(), PaymentMethod::Cash);
$this->assertNotNull($visit->fresh()->settled_at);
Mail::assertNotSent(ArrivalInformation::class);
Mail::assertNotSent(ReviewRequest::class);
}
/** T22 – the stay is closed while money is still open; the claim stays visible and the commercial closing waits. */
public function test_t22_stay_closed_while_commercial_points_are_open(): void
{
$booking = $this->confirmedOwnBooking();
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today());
$this->travelTo(CarbonImmutable::parse('2026-11-12 08:00'));
app(SendBookingReminders::class)->handle();
app(SendBookingReminders::class)->handle();
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status, 'open money does not hold the stay up');
$this->assertNull($booking->settled_at);
$this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->whereIn('kind', [BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim])->count(), 'exactly one follow-up for the open amount');
$this->assertNotNull(collect(WorkList::items())->first(fn (array $item): bool => str_contains($item['url'], '/'.$booking->id)), 'the follow-up stays in the work list');
$this->assertStringContainsString('Noch offen vom Gast', implode(' ', CaseClosure::commercialPoints($booking)));
$this->assertSame('Aufenthalt abgeschlossen, kaufmännisch noch offen', explode(' · ', CaseActivities::situation($booking))[1]);
app(RecordPayment::class)->handle($booking, (int) $booking->total - (int) $booking->deposit, CarbonImmutable::today());
$booking->refresh();
$this->assertNotNull($booking->settled_at);
$this->assertSame(BookingStatus::Completed, $booking->status, 'a late payment does not reopen the stay');
// A contradicting payout statement is settled by the landlord with a reason.
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-DIFF01");
$portal = Booking::query()->where('portal_reference', 'HA-DIFF01')->sole();
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22',
'amounts' => [['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69'], ['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Erwartet', 'amount' => '900.20']]]);
$this->travelTo(CarbonImmutable::parse('2026-12-15 08:00'));
app(SendBookingReminders::class)->handle();
app(RecordPayment::class)->handle($portal->fresh(), 89469, CarbonImmutable::today(), kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$portal->refresh();
$this->assertSame(BookingStatus::Completed, $portal->status);
$this->assertNull($portal->settled_at, 'the 5,51 € difference is not settled by the system');
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert']);
$portal->refresh();
$this->assertSame(['Ingrid', 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'], [$portal->settled_by, $portal->settled_note]);
}
/** T24 – landlord, property, portal and case settings decide the whole run. */
public function test_t24_settings_of_every_level_are_effective_in_the_whole_run(): void
{
$this->releaseTexts();
DocumentReleases::set(DocumentKind::Information, true, 'Test');
// Landlord: automatic, requests reserve. Portal Ostseeklar (requests): no reservation, manual. Property: arrival information 5 days ahead.
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => true]]);
$this->manualPortal->update(['process_overrides' => ['inquiry' => ['pre_reservation' => false, 'processing' => 'manual']]]);
$this->property->update(['process_overrides' => ['arrival_info_days_before' => 5], 'asks_arrival_time' => true]);
$direct = $this->request();
$this->assertSame(BookingStatus::OfferSent, $direct->fresh()->status, 'landlord level: automatic offer with hold');
$this->assertNotNull($direct->fresh()->hold_expires_at);
$viaPortal = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-21'), CarbonImmutable::parse('2026-11-24'), 2), ['first_name' => 'Pia', 'last_name' => 'Portal', 'email' => 'pia@example.org'], originChannel: $this->manualPortal->fresh());
$this->assertSame([0, 0, null], [$viaPortal->fresh()->information_version, $viaPortal->fresh()->offer_version, $viaPortal->fresh()->hold_expires_at], 'portal level: no hold, manual');
$this->assertSame('sendInformation', CaseActivities::next($viaPortal->fresh())?->action);
Livewire::test(ViewBooking::class, ['record' => $viaPortal->getRouteKey()])->callAction('automation', ['mode' => ProcessingMode::Automatic->value]);
$this->assertSame(1, $viaPortal->fresh()->information_version, 'case level: switched to automatic, the information goes out');
$this->wish($viaPortal->fresh());
$this->assertSame(BookingStatus::Confirmed, $viaPortal->fresh()->status, 'and the wish is confirmed automatically');
// Property level: arrival details are asked for 5 + 2 days ahead, the arrival information 5 days ahead.
$this->travelTo(CarbonImmutable::parse('2026-11-14 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertTrue(BookingTask::query()->where('booking_id', $viaPortal->id)->where('kind', BookingTaskKind::ArrivalDetails)->exists());
Mail::assertNotSent(ArrivalInformation::class);
$this->travelTo(CarbonImmutable::parse('2026-11-16 08:00'));
app(SendBookingReminders::class)->handle();
Mail::assertSent(ArrivalInformation::class, fn (ArrivalInformation $mail): bool => $mail->booking->is($viaPortal));
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(EffectiveSettings::class)->set('bookingId', $viaPortal->id)->assertSee('für diesen Vorgang umgestellt')->assertSee('Abweichung des Portals');
}
/** T25 – change of a binding portal booking: the portal's new price, the calendar and the portal tasks follow. */
public function test_t25_change_of_a_binding_portal_booking(): void
{
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-CHANGE");
$booking = Booking::query()->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22']);
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-14')->exists());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-12-07', 'departure' => '2026-12-16', 'guests' => 2, 'portal_total' => '1199.00', 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Portal->value, 'reason' => 'Verlängerung über FeWo-direkt'])
->assertNotified('Änderung gespeichert');
$booking->refresh();
$this->assertSame(['2026-12-16', 119900, 'portal'], [$booking->departure->toDateString(), $booking->total, $booking->quote['source'] ?? null], 'the portal price counts, nothing is recalculated');
$this->assertSame(CaseType::A4, $booking->case_type);
$this->assertSame(0, CaseMoney::of($booking)->openForUs(), 'the portal still collects');
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-12-16')->exists(), 'portal task for the new dates');
$this->assertSame(ChangeBasis::Portal, $booking->changes()->sole()->basis);
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::RefundCheck)->count());
}
/** Special cases: unknown guest contact of a portal booking, unknown portal price, a cancellation shortly before arrival. */
public function test_special_cases_of_preparation_and_closing(): void
{
$this->property->update(['stay_tasks' => [['title' => 'Endreinigung', 'when' => 'after_departure', 'applies_to' => ['rental']]]]);
$this->fewo();
$this->portalMail("Anreise: 30.10.2026\nAbreise: 02.11.2026\nBuchungsnummer: HA-NOMAIL");
$portal = Booking::query()->sole();
$this->travelTo(CarbonImmutable::parse('2026-10-26 08:00'));
app(SendBookingReminders::class)->handle();
$details = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::ArrivalDetails)->sole();
$this->assertStringContainsString('im Portal FeWo-direkt nachsehen', (string) $details->note, 'contact of a portal guest may have to come from the portal');
$this->travelTo(CarbonImmutable::parse('2026-11-03 08:00'));
$cleaning = BookingTask::query()->where('booking_id', $portal->id)->where('kind', BookingTaskKind::Service)->sole();
$cleaning->complete('Ingrid');
app(SendBookingReminders::class)->handle();
$portal->refresh();
$this->assertSame(BookingStatus::Completed, $portal->status);
$this->assertSame(BookingTaskStatus::Dismissed, $details->fresh()->status, 'arrival details are moot after the departure');
$this->assertContains('Der Gesamtpreis laut FeWo-direkt fehlt.', CaseClosure::commercialPoints($portal), 'an unknown portal price is no invented 0');
// Cancellation two days before arrival: preparation is dropped, costs keep the case open commercially.
$own = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-05'), CarbonImmutable::parse('2026-11-08'), 2), ['first_name' => 'Kurt', 'last_name' => 'Kurzfristig', 'email' => 'kurt@example.org'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('confirm', ['notify' => false]);
app(SendBookingReminders::class)->handle();
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->exists());
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Krankheit', 'notify' => false, 'costs_task' => true]);
$own->refresh();
$this->assertSame(BookingStatus::Cancelled, $own->status);
$this->assertSame(BookingTaskStatus::Dismissed, BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::Service)->value('status'));
$this->assertNull($own->settled_at, 'the cancellation fee is still to be settled');
BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::CancellationFee)->sole()->complete('Ingrid', 'Keine Kosten berechnet (Kulanz).');
$this->assertNotNull($own->fresh()->settled_at);
}
/** Special case: an issue during the stay holds the closing up, a follow-up (damage) does not. */
public function test_issues_hold_the_stay_up_and_follow_ups_do_not(): void
{
$booking = $this->confirmedOwnBooking();
$this->travelTo(CarbonImmutable::parse('2026-11-08 10:00'));
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::Issue->value, 'title' => 'Kaffeemaschine defekt', 'responsible' => 'Ingrid']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('addTask', ['kind' => BookingTaskKind::FollowUp->value, 'title' => 'Fleck im Teppich – Reinigung abrechnen']);
$this->assertSame(2, BookingTask::query()->where('booking_id', $booking->id)->whereIn('kind', [BookingTaskKind::Issue, BookingTaskKind::FollowUp])->count());
$this->travelTo(CarbonImmutable::parse('2026-11-11 08:00'));
app(SendBookingReminders::class)->handle();
$this->assertNotSame(BookingStatus::Completed, $booking->fresh()->status, 'the open issue holds the stay up');
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('closeStay', ['note' => 'Kaffeemaschine ersetzt']);
$booking->refresh();
$this->assertSame(BookingStatus::Completed, $booking->status);
$this->assertSame(BookingTaskStatus::Open, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::FollowUp)->value('status'), 'the follow-up stays on the closed case');
$this->assertSame('Kaffeemaschine ersetzt', BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::Issue)->value('note'));
}
/** Section 5: stored statuses are not silently reinterpreted; the command shows and corrects them on request. */
public function test_existing_payment_statuses_are_only_corrected_on_request(): void
{
$this->fewo();
$this->portalMail("Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-OLDPAY");
$booking = Booking::query()->sole();
$booking->update(['total' => 97951, 'deposit' => 30000]);
// As the old rule left it: "paid according to the portal" had moved the status.
$booking->payments()->create(['amount' => 39061, 'paid_on' => '2026-10-20', 'method' => PaymentMethod::Transfer, 'kind' => PaymentKind::GuestViaPortal]);
$booking->update(['status' => BookingStatus::DepositPaid]);
$this->artisan('cases:recheck-payment-status')->expectsOutputToContain('Vorschau')->assertSuccessful();
$this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status, 'nothing changed by the preview');
$this->artisan('cases:recheck-payment-status', ['--apply' => true])->expectsOutputToContain('korrigiert')->assertSuccessful();
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
$this->assertStringContainsString('laut Portal bezahlt', (string) $booking->events()->where('type', 'status')->reorder()->orderByDesc('id')->value('reason'));
}
private function request(string $email = 'gesa@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
{
return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email]);
}
private function sendInformation(Booking $booking): void
{
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])
->assertNotified('Auskunft gesendet');
}
private function wish(Booking $booking): void
{
$this->post(URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => $booking->information_version]), ['terms' => '1'])->assertRedirect();
}
private function automaticWithoutHold(): void
{
$this->releaseTexts();
DocumentReleases::set(DocumentKind::Information, true, 'Test');
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]);
}
private function confirmedOwnBooking(): Booking
{
$booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('confirm', ['notify' => false]);
return $booking->fresh();
}
/**
* @param array<string, mixed> $attributes
*/
private function fewo(array $attributes = []): Channel
{
return Channel::query()->where('name', 'FeWo-direkt')->first() ?? Channel::factory()->for($this->property)->create([
'name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'case_intake' => CaseIntakeMode::Create,
'settings' => ['email_senders' => 'fewo-direkt.de'], 'process_overrides' => ['booking' => ['payments' => 'portal']], ...$attributes,
]);
}
private function portalMail(string $text): void
{
app(ProcessPortalMail::class)->handle(new PortalMail(uniqid('msg-'), 'noreply@fewo-direkt.de', 'Neue Buchung', $text, CarbonImmutable::now()));
}
private function releaseTexts(): void
{
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']);
DocumentReleases::set(DocumentKind::ExternalRecord, false, 'Test');
}
}
@@ -0,0 +1,189 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\SendBookingReminders;
use App\Documents\DocumentReleases;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Listeners\EnforceMailTestMode;
use App\Mail\BookingWishNotice;
use App\Mail\InformationSent;
use App\Models\Booking;
use App\Models\Property;
use App\Models\User;
use App\Pricing\StayRequest;
use App\Support\Content;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;
use Tests\TestCase;
/**
* T23 – test operation against a real, isolated SMTP receiver (tests/Support/smtp-sink.php): every message of packages
* 7 and 9 that really goes over the wire – automatic, manual, scheduled, queued, with Cc and Bcc – reaches only the test
* address; the original recipients never appear in the SMTP envelope, and the case history does not call a redirected
* message a delivery to the guest.
*/
class TestOperationSmtpAcceptanceTest extends TestCase
{
use RefreshDatabase;
private const TEST_ADDRESS = 'testpostfach@example.com';
private const GUEST = 'gesa@gast.example';
/** @var resource|null */
private $sink = null;
private string $capture;
protected function setUp(): void
{
parent::setUp();
$port = $this->freePort();
$this->capture = storage_path('framework/testing/smtp-sink-'.getmypid().'.jsonl');
@mkdir(dirname($this->capture), 0777, true);
@unlink($this->capture);
@unlink($this->capture.'.stop');
$this->sink = proc_open([PHP_BINARY, base_path('tests/Support/smtp-sink.php'), (string) $port, $this->capture, '120'], [], $pipes);
$this->waitFor(fn (): bool => file_exists($this->capture.'.ready'));
config([
'mail.default' => 'smtp',
'mail.mailers.smtp' => ['transport' => 'smtp', 'scheme' => 'smtp', 'host' => '127.0.0.1', 'port' => $port, 'username' => null, 'password' => null, 'timeout' => 5, 'local_domain' => 'localhost', 'auto_tls' => false],
'fewo.mail_redirect_to' => null,
'queue.default' => 'database',
]);
// The real mail manager behind the test-operation gate, not the fake.
$manager = new MailManager(app());
app()->instance('mail.manager', $manager);
Mail::swap($manager);
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
app(TenantContext::class)->set(Property::sole()->tenant);
Storage::fake('local');
Http::fake(fn () => Http::response('', 500));
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
protected function tearDown(): void
{
if ($this->sink !== null) {
touch($this->capture.'.stop');
$this->waitFor(fn (): bool => ! file_exists($this->capture.'.ready'));
proc_close($this->sink);
}
@unlink($this->capture);
@unlink($this->capture.'.stop');
parent::tearDown();
}
public function test_t23_every_message_goes_only_to_the_test_address_over_real_smtp(): void
{
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
DocumentReleases::set(DocumentKind::Information, true, 'Test');
Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => self::TEST_ADDRESS, 'notification_emails' => 'vermieterin@example.org',
'bank_iban' => 'DE02120300000000202051', 'process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]);
app(TenantContext::class)->set(Settings::tenant()->fresh());
$property = Property::sole();
// Automatic: request → information; guest: booking wish → confirmation; scheduled: arrival information.
$booking = app(CreateReservation::class)->handle($property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => self::GUEST]);
$booking->refresh();
$this->post(URL::temporarySignedRoute('information.wish', $booking->information_valid_until, ['booking' => $booking, 'v' => $booking->information_version]), ['terms' => '1'])->assertRedirect();
$this->assertTrue($booking->fresh()->isBinding());
$this->travelTo(CarbonImmutable::parse('2026-11-04 08:00'));
app(SendBookingReminders::class)->handle();
// Manual: the landlord resends the information of a second request; with Cc and Bcc to outside addresses.
$second = app(CreateReservation::class)->handle($property, new StayRequest(CarbonImmutable::parse('2026-11-21'), CarbonImmutable::parse('2026-11-24'), 2), ['first_name' => 'Ole', 'last_name' => 'Zweit', 'email' => 'ole@gast.example']);
Livewire::test(ViewBooking::class, ['record' => $second->getRouteKey()])->callAction(TestAction::make('sendInformation')->arguments([]), ['acknowledged' => true])->assertNotified('Auskunft gesendet');
Mail::to('ole@gast.example')->cc('cc@aussen.example')->bcc('bcc@aussen.example')->send(new BookingWishNotice($second->fresh(), 'pending'));
// Queued while the landlord was live – sent after switching back to test operation: the gate decides at sending time.
Settings::tenant()->update(['operating_mode' => Settings::MODE_LIVE]);
Mail::to('ole@gast.example')->queue(new InformationSent($second->fresh(), 'https://example.test'));
$this->assertSame(1, DB::table('jobs')->count(), 'the message waits in the queue');
Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST]);
$this->artisan('queue:work', ['--once' => true, '--stop-when-empty' => true]);
$messages = $this->captured();
$this->assertGreaterThanOrEqual(8, count($messages), 'information, notices, wish, confirmation, arrival information, manual and queued mails');
foreach ($messages as $message) {
$this->assertSame([self::TEST_ADDRESS], $message['to'], 'SMTP envelope of: '.$message['subject']);
$this->assertStringNotContainsString('gast.example>', $message['headers_to']);
}
$all = implode("\n", array_column($messages, 'envelope'));
foreach ([self::GUEST, 'ole@gast.example', 'cc@aussen.example', 'bcc@aussen.example', 'vermieterin@example.org'] as $original) {
$this->assertStringNotContainsString($original, $all, $original.' never in an SMTP envelope');
}
$this->assertTrue(collect($messages)->contains(fn (array $message): bool => str_contains($message['data'], EnforceMailTestMode::ORIGINAL_RECIPIENTS_HEADER.': '.self::GUEST)), 'the original recipient is documented in a header');
$this->assertTrue(collect($messages)->contains(fn (array $message): bool => str_contains($message['subject'], 'Unverbindliche Auskunft')));
// The history says where the mails really went.
$history = Booking::query()->find($booking->id)->events()->pluck('summary')->implode(' | ');
$this->assertStringContainsString('im Testbetrieb an die Testadresse (nicht an den Gast)', $history);
$this->assertStringContainsString('Testbetrieb: nur an die Testadresse, nicht an den Gast', $history);
$this->assertStringNotContainsString('E-Mail an den Gast:', $history);
}
/**
* @return list<array{to: list<string>, subject: string, headers_to: string, envelope: string, data: string}>
*/
private function captured(): array
{
$this->waitFor(fn (): bool => file_exists($this->capture));
$messages = [];
foreach (file($this->capture, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
$entry = json_decode($line, true);
$data = (string) $entry['data'];
$headers = substr($data, 0, (int) strpos($data, "\r\n\r\n"));
preg_match('/^Subject: (.*)$/mi', $headers, $subject);
preg_match('/^To: (.*)$/mi', $headers, $to);
$messages[] = [
'to' => $entry['to'],
'subject' => mb_decode_mimeheader(trim($subject[1] ?? '')),
'headers_to' => $to[1] ?? '',
'envelope' => $entry['from'].' -> '.implode(',', $entry['to']),
'data' => $data,
];
}
return $messages;
}
private function freePort(): int
{
$socket = stream_socket_server('tcp://127.0.0.1:0');
$name = stream_socket_get_name($socket, false);
fclose($socket);
return (int) substr((string) $name, strrpos((string) $name, ':') + 1);
}
private function waitFor(callable $condition): void
{
$until = microtime(true) + 10;
while (! $condition() && microtime(true) < $until) {
usleep(50000);
}
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
/**
* An isolated SMTP test receiver for the acceptance test of the test operation (T23): accepts every message on
* 127.0.0.1:<port>, delivers nothing anywhere and writes one JSON line per message (envelope sender, envelope
* recipients, raw data) to <file>. It stops when <file>.stop exists or after <seconds> (default 120).
*
* Usage: php tests/Support/smtp-sink.php <port> <file> [seconds]
*/
$port = (int) ($argv[1] ?? 2525);
$file = (string) ($argv[2] ?? sys_get_temp_dir().'/smtp-sink.jsonl');
$until = time() + (int) ($argv[3] ?? 120);
$server = stream_socket_server('tcp://127.0.0.1:'.$port, $errorCode, $errorMessage);
if ($server === false) {
fwrite(STDERR, "SMTP sink: {$errorMessage}\n");
exit(1);
}
stream_set_blocking($server, false);
file_put_contents($file.'.ready', (string) getmypid());
/** @var array<int, array{socket: resource, buffer: string, from: ?string, to: list<string>, data: ?string}> $clients */
$clients = [];
$send = function ($socket, string $line): void {
@fwrite($socket, $line."\r\n");
};
while (time() < $until && ! file_exists($file.'.stop')) {
$read = [$server];
foreach ($clients as $entry) {
$read[] = $entry['socket'];
}
$write = $except = null;
if (@stream_select($read, $write, $except, 0, 200000) === false) {
break;
}
foreach ($read as $socket) {
if ($socket === $server) {
$connection = @stream_socket_accept($server, 0);
if ($connection !== false) {
stream_set_blocking($connection, false);
$clients[(int) $connection] = ['socket' => $connection, 'buffer' => '', 'from' => null, 'to' => [], 'data' => null];
$send($connection, '220 fewo-smtp-sink ESMTP');
}
continue;
}
$id = (int) $socket;
$chunk = @fread($socket, 65536);
if ($chunk === '' || $chunk === false) {
if (feof($socket)) {
fclose($socket);
unset($clients[$id]);
}
continue;
}
$clients[$id]['buffer'] .= $chunk;
while (true) {
$client = &$clients[$id];
if ($client['data'] !== null) {
$end = strpos($client['buffer'], "\r\n.\r\n");
if ($end === false) {
break;
}
$client['data'] .= substr($client['buffer'], 0, $end);
$client['buffer'] = substr($client['buffer'], $end + 5);
file_put_contents($file, json_encode(['from' => $client['from'], 'to' => $client['to'], 'data' => $client['data']])."\n", FILE_APPEND | LOCK_EX);
$client['from'] = null;
$client['to'] = [];
$client['data'] = null;
$send($socket, '250 OK: queued in the sink');
continue;
}
$position = strpos($client['buffer'], "\r\n");
if ($position === false) {
break;
}
$line = substr($client['buffer'], 0, $position);
$client['buffer'] = substr($client['buffer'], $position + 2);
$command = strtoupper(substr($line, 0, 4));
match (true) {
$command === 'EHLO' => $send($socket, "250-fewo-smtp-sink\r\n250 8BITMIME"),
$command === 'HELO' => $send($socket, '250 fewo-smtp-sink'),
$command === 'MAIL' => [$client['from'] = trim(substr($line, 10), ' <>'), $send($socket, '250 OK')],
$command === 'RCPT' => [$client['to'][] = trim(substr($line, 8), ' <>'), $send($socket, '250 OK')],
$command === 'DATA' => [$client['data'] = '', $send($socket, '354 End data with <CR><LF>.<CR><LF>')],
$command === 'RSET' => [$client['from'] = null, $client['to'] = [], $send($socket, '250 OK')],
$command === 'NOOP' => $send($socket, '250 OK'),
$command === 'QUIT' => [$send($socket, '221 Bye'), fclose($socket), $clients[$id] = null],
default => $send($socket, '502 Command not implemented'),
};
unset($client);
if ($clients[$id] === null) {
unset($clients[$id]);
break;
}
}
unset($client);
}
}
foreach ($clients as $entry) {
@fclose($entry['socket']);
}
fclose($server);
@unlink($file.'.ready');