Vorgangskern und geführte Vorgangsbearbeitung (Pakete 1 und 2, Prozessarchitektur v0.10)

- Buchung ist der einheitliche Vorgang: Eingangsart, Vorgangsart A1–A6, eingefrorenes
  Abwicklungsprofil, gespeicherter Verlauf (booking_events); Gast, Personen und Beträge
  dürfen unbekannt sein, Platzhalter-Gäste werden migriert und nicht mehr angelegt
- Einstellungen in Ebenen: Vermieterstandard (So arbeite ich), Abweichung der Wohnung
  (Experte), Abweichung je Portal und Eingangsart; ersetzt booking_model als Steuergröße
- Ein Weg für extern verbindliche Buchungen (TakeOverExternalBooking) statt
  RecordPortalBooking und "Akte anlegen"; Portalpreis als belegte Gesamtposition
- Startseite "Zu erledigen", neue Vorgangsseite mit nächstem Schritt, Automatik-Schalter,
  "Beenden" mit Storno statt Statusumschaltung; Status von Hand nur im Expertenmodus
- Migration übernimmt bisheriges Verhalten unverändert (abweichende Wohnungswerte bleiben
  als Abweichung), Bericht: php artisan process:settings-report

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-01 16:25:46 +01:00
1 parent 9005c12164
commit 3a728c3255
78 files changed
+4296 -1180

No files matched your search

+5 -5
View File
@@ -5,7 +5,7 @@
use App\Availability\AvailabilityChecker;
use App\Availability\CalendarClearance;
use App\Enums\BookingStatus;
use App\Enums\OfferMode;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Pricing\QuoteException;
@@ -30,7 +30,7 @@ public function __construct(
public function applies(Booking $booking): bool
{
return $booking->property->offer_mode === OfferMode::Automatic;
return $booking->processingMode() === ProcessingMode::Automatic;
}
/**
@@ -41,8 +41,8 @@ public function blockers(Booking $booking): array
$property = $booking->property;
$reasons = [];
if (! $property->pre_reservation_enabled) {
$reasons[] = 'Die Vorreservierung ist für diese Wohnung ausgeschaltet; ohne Sperre im Kalender wird kein Angebot automatisch erteilt.';
if (! $booking->process()->preReservation()) {
$reasons[] = 'Anfragen reservieren den Zeitraum nicht (Einstellung „Vorreservierung“); ohne Sperre im Kalender wird kein Angebot automatisch erteilt.';
}
if ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive()) {
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
@@ -69,7 +69,7 @@ public function handle(Booking $booking): array
{
$booking->loadMissing(['property', 'guest']);
if ($booking->property->pre_reservation_enabled) {
if ($booking->process()->preReservation()) {
$this->clearance->refresh($booking->property);
}
+12 -3
View File
@@ -30,13 +30,13 @@ class CancelBooking
*
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung'): bool
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord'): bool
{
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
}
DB::transaction(function () use ($booking, $costsTask, $by): void {
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
@@ -44,7 +44,16 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
}
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, 'landlord');
app(RecordCancellation::class)->handle($booking, $initiatedBy);
if ($booking->caseType()->isExternallyBinding()) {
// The contract was made on the portal: the cancellation has to happen (or be checked) there as well.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => 'Stornierung auch im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ veranlassen bzw. prüfen, ob sie dort wirksam ist.',
]);
}
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
+2 -2
View File
@@ -96,13 +96,13 @@ public function deliver(Booking $booking, bool $notifyGuest = true): bool
}
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->saveQuietly();
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save();
return true;
} catch (Throwable $exception) {
// Only class and booking id are logged: mail errors can contain the recipient's address.
Log::warning('Buchungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$booking->forceFill(['confirmation_failed_at' => now()])->saveQuietly();
$booking->forceFill(['confirmation_failed_at' => now()])->save();
$this->inbox->post(
InboxMessageKind::ConfirmationFailed,
'booking-'.$booking->id,
+17 -7
View File
@@ -4,15 +4,18 @@
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Exceptions\ReservationException;
use App\Mail\NewReservation;
use App\Mail\ReservationReceived;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
@@ -23,7 +26,7 @@
use Throwable;
/**
* Turns a guest request into a reservation that holds the dates for the property's hold time,
* Turns a guest request into a case (intake "request") that holds the dates for the hold time of the process settings,
* and sends the quote to the guest and a notification to the landlord.
*/
class CreateReservation
@@ -40,7 +43,7 @@ public function __construct(
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = [], ?Channel $originChannel = null): Booking
{
$tenant = $property->tenant;
@@ -50,7 +53,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution, $originChannel),
);
}
@@ -58,9 +61,13 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution, ?Channel $originChannel): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
if ($originChannel !== null && $originChannel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution, $originChannel): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
@@ -70,11 +77,14 @@ private function create(Property $property, StayRequest $stay, array $guestData,
$quote = $this->calculator->calculate($property, $stay);
[$guest, $differences] = $this->guestFor($guestData);
$profile = app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
'intake' => IntakeKind::Inquiry,
'origin_channel_id' => $originChannel?->id,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
@@ -85,7 +95,7 @@ private function create(Property $property, StayRequest $stay, array $guestData,
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => $property->pre_reservation_enabled ? now()->addHours($property->hold_hours) : null,
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
'message' => $message,
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
]);
@@ -165,7 +175,7 @@ private function sendMails(Booking $booking): void
}
try {
if (! $offerSent) {
if (! $offerSent && filled($booking->guest?->email)) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
}
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
+17 -68
View File
@@ -2,90 +2,39 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\OccupationKind;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PortalPrice;
use App\Pricing\StayRequest;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* Opens the booking file for a reservation that arrived through a portal calendar. The calendar only says "these
* nights are taken"; the file gives the reservation its workflow (contact data, contract, payments, arrival,
* cancellation) like every other booking. The imported calendar entry stays as the portal's mirror of the booking
* (it keeps its calendar source and UID, but the booking now leads the calendar), the dates stay occupied throughout.
*
* Unknown facts stay unknown: the guest is a placeholder without contact data, the price is our own calculation (or
* empty) until the portal price is entered.
* Takes over a reservation found in a portal calendar as a case ({@see TakeOverExternalBooking}). The calendar only
* says "these nights are taken"; the case gives the reservation its handling. The calendar entry stays as the portal's
* mirror of the case. A first name from the calendar is no guest identity – it is kept as a note, not as a guest.
*/
class OpenPortalFile
{
public function __construct(private PortalPrice $price) {}
public function __construct(private TakeOverExternalBooking $takeOver) {}
/**
* @throws ReservationException
*/
public function handle(BlockedPeriod $block): Booking
{
return DB::transaction(function () use ($block): Booking {
Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail();
$block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail();
if ($block->channel === null) {
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
}
if (! in_array($block->source, ['channel', 'email'], true) || $block->channel_id === null) {
throw new ReservationException('Eine Akte gibt es nur für Reservierungen aus einem Portalkalender.');
}
if ($block->occupationKind() === OccupationKind::Block) {
throw new ReservationException('Eine Sperrzeit ist keine Reservierung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
}
if ($block->is_representation && $block->linked_booking_id !== null) {
return Booking::query()->findOrFail($block->linked_booking_id);
}
if ($block->is_representation) {
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Die Akte gehört an die führende Belegung.');
}
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
$name = trim((string) ($fields['guest_first_name'] ?? ''));
$property = $block->property;
$channel = $block->channel;
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
$guest = $block->guest ?? Guest::query()->create([
'first_name' => filled($fields['guest_first_name'] ?? null) ? (string) $fields['guest_first_name'] : 'Gast',
'last_name' => '('.$channel->name.')',
'email' => '',
'tenant_id' => app(TenantContext::class)->id(),
]);
$stay = new StayRequest(CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), min(2, $property->max_guests));
$booking = $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => 'portal',
'origin_channel_id' => $block->origin_channel_id ?? $channel->id,
'portal_reference' => $fields['booking_reference'] ?? null,
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
'guests' => $stay->guests,
'hold_expires_at' => null,
'internal_notes' => 'Akte aus dem Portalkalender „'.$channel->name.'“ angelegt. Personenzahl und Preis sind nicht bekannt – bitte den Portalpreis erfassen.',
...$this->price->unknownColumns($property, $stay),
]);
$block->forceFill([
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest->id,
'review_note' => 'Akte angelegt; die Buchung führt diese Belegung.',
])->save();
app(ConfirmBooking::class)->bind($booking);
app(ReconcileChannelRepresentations::class)->handle($property);
return $booking->refresh();
});
return $this->takeOver->handle(
$block->property,
$block->channel,
CarbonImmutable::parse($block->starts_on),
CarbonImmutable::parse($block->ends_on),
['notes' => 'Aus dem Portalkalender „'.$block->channel->name.'“ übernommen.'.($name !== '' ? ' Name laut Kalender: '.$name.'.' : '')],
$block,
);
}
}
+21 -4
View File
@@ -3,9 +3,12 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Support\BookingProgress;
use App\Models\Guest;
use App\Process\CaseAutomation;
use Illuminate\Support\Arr;
/**
@@ -38,9 +41,17 @@ public function handle(Booking $booking, array $contact, string $process = self:
throw new ReservationException('Für den automatischen Ablauf wird die E-Mail-Adresse des Gastes benötigt.');
}
$booking->guest->update(array_filter($contact, fn ($value) => $value !== null));
if ($booking->guest === null) {
if (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null)) {
throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.');
}
$guest = Guest::query()->create([...array_filter($contact, fn ($value) => $value !== null), 'email' => $contact['email'] ?? '']);
$booking->update(['guest_id' => $guest->id]);
} else {
$booking->guest->update(array_filter($contact, fn ($value) => $value !== null));
}
if ($guestConfirmed) {
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->saveQuietly();
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->save();
}
$booking->refresh()->load('guest');
@@ -48,13 +59,19 @@ public function handle(Booking $booking, array $contact, string $process = self:
return 'Kontaktdaten gespeichert';
}
$booking->update(['processing_mode' => ProcessingMode::Automatic]);
if (in_array($booking->status, BookingStatus::occupying(), true)) {
$missing = app(CaseAutomation::class)->documentBlockers($booking);
if ($missing !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen können noch nicht automatisch versendet werden: '.implode(' ', $missing));
}
$this->confirm->deliver($booking);
return 'Kontaktdaten gespeichert, Vertrag gesendet';
}
if (BookingProgress::kind($booking) === BookingProgress::PORTAL_BOOKING) {
if ($booking->intake === IntakeKind::Booking) {
$this->confirm->handle($booking);
return 'Kontaktdaten gespeichert, Buchung bestätigt und Vertrag gesendet';
-77
View File
@@ -1,77 +0,0 @@
<?php
namespace App\Actions;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\PortalPrice;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Illuminate\Support\Facades\DB;
/**
* Records a booking that a portal already made binding (e.g. a direct booking on FeWo-direkt) – usually without
* the guest's contact data. The booking keeps the portal as its origin channel and may carry the portal's price and
* reference. The landlord decides how the contract process continues:
*
* - {@see self::CONFIRM}: the booking becomes binding right away (the dates are occupied), the contract follows
* once the contact data is known ({@see ProvideGuestContact}) – no contract is generated before that;
* - {@see self::CONTRACT}: binding and contract mail at once (needs the guest's e-mail address);
* - {@see self::RECORD}: only recorded as a request, everything else is done by hand.
*/
class RecordPortalBooking
{
public const CONFIRM = 'confirm';
public const CONTRACT = 'contract';
public const RECORD = 'record';
public function __construct(
private CreateReservation $create,
private ConfirmBooking $confirm,
private PortalPrice $price,
) {}
/**
* @param array<string, ?string> $guestData first_name and last_name are required, everything else optional
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, Channel $channel, StayRequest $stay, array $guestData, string $process = self::CONFIRM, ?string $portalReference = null, ?int $portalTotal = null, ?string $notes = null, bool $guestConfirmed = false): Booking
{
if ($channel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
if ($process === self::CONTRACT && blank($guestData['email'] ?? null)) {
throw new ReservationException('Für den sofortigen Vertragsversand wird die E-Mail-Adresse des Gastes benötigt.');
}
$booking = $this->create->handle($property, $stay, $guestData, source: 'portal', sendMails: false);
$changes = ['origin_channel_id' => $channel->id, 'portal_reference' => filled($portalReference) ? trim($portalReference) : null, 'internal_notes' => filled($notes) ? trim($notes) : $booking->internal_notes];
if ($guestConfirmed) {
$changes['guest_confirmed_at'] = now();
}
if ($portalTotal !== null) {
$changes += $this->price->columns($property, $stay, $portalTotal);
}
$booking->update($changes);
if ($process === self::RECORD) {
return $booking->refresh();
}
if ($process === self::CONTRACT) {
$this->confirm->handle($booking, notifyGuest: true);
} else {
DB::transaction(fn () => $this->confirm->bind($booking));
}
return $booking->refresh();
}
}
+3 -1
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\Responsibility;
use App\Mail\ReviewRequest;
use App\Models\Booking;
use Illuminate\Support\Facades\Mail;
@@ -25,7 +26,8 @@ public function handle(): int
->whereDoesntHave('review')
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->with('guest')
->get();
->get()
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord);
foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
+3 -1
View File
@@ -5,6 +5,7 @@
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Mail\ArrivalInformation;
use App\Models\Booking;
use App\Models\BookingTask;
@@ -60,7 +61,8 @@ public function handle(): array
->whereNull('arrival_info_sent_at')
->whereDate('arrival', '>=', $today)
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->property->arrival_info_days_before)));
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore())));
foreach ($arrivals as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
$booking->update(['arrival_info_sent_at' => now()]);
+1 -1
View File
@@ -93,7 +93,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->property->hold_hours),
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? null,
+9 -1
View File
@@ -9,6 +9,7 @@
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Process\CaseLog;
use Illuminate\Support\Facades\DB;
/**
@@ -33,6 +34,10 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
throw new ReservationException('Auf diesen Status kann nicht von Hand gewechselt werden. Stornieren und Ablehnen haben eigene Aktionen.');
}
if ($status === BookingStatus::Reserved && in_array($booking->status, BookingStatus::occupying(), true)) {
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden. Soll sie enden, bitte „Beenden“ wählen – dann wird sie ordentlich storniert.');
}
if (blank(trim($reason))) {
throw new ReservationException('Bitte einen Grund für die Statusänderung angeben.');
}
@@ -44,6 +49,9 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
if ($from === $status) {
throw new ReservationException('Die Buchung hat diesen Status bereits.');
}
if ($status === BookingStatus::Reserved && in_array($from, BookingStatus::occupying(), true)) {
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden.');
}
$becomesBinding = in_array($status, BookingStatus::occupying(), true) && ! in_array($from, BookingStatus::occupying(), true);
if ($becomesBinding && ! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
@@ -59,7 +67,7 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
}
$line = now()->format('d.m.Y H:i').' '.$by.': Status von „'.$from->getLabel().'“ auf „'.$status->getLabel().'“ gesetzt – '.trim($reason);
$booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]);
CaseLog::context(fn () => $booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]), actor: $by, reason: 'Von Hand gesetzt: '.trim($reason));
// A booking taken back into the process no longer needs the cancellation follow-up.
if ($becomesBinding) {
+146
View File
@@ -0,0 +1,146 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\OccupationKind;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PortalPrice;
use App\Process\CaseAutomation;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Takes over a booking that a portal already made binding (case types A3–A5): one case with the portal as origin
* channel (owner), its reference and the facts the portal delivered – nothing more. There is no offer and no second
* acceptance; the agreed portal price is taken over as it is; guest, number of guests and price may be unknown and
* stay unknown until somebody enters them. The case is binding at once and occupies the dates.
*
* Used for the manual entry ("Buchung von einem Portal") and for a reservation found in a portal calendar – then the
* calendar entry stays as the portal's mirror of the case.
*/
class TakeOverExternalBooking
{
public function __construct(private ConfirmBooking $confirm, private PortalPrice $price) {}
/**
* @param array{guest?: ?array<string, ?string>, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool} $facts
*
* @throws ReservationException
*/
public function handle(Property $property, Channel $channel, CarbonImmutable $arrival, CarbonImmutable $departure, array $facts = [], ?BlockedPeriod $evidence = null): Booking
{
if ($channel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Die Abreise muss nach der Anreise liegen.');
}
$booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $facts, $evidence): Booking {
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if ($evidence !== null) {
$evidence = BlockedPeriod::query()->whereKey($evidence->id)->lockForUpdate()->firstOrFail();
$existing = $this->checkEvidence($evidence);
if ($existing !== null) {
return $existing;
}
}
$guests = isset($facts['guests']) && (int) $facts['guests'] > 0 ? (int) $facts['guests'] : null;
$guest = $evidence?->guest ?? $this->guestFrom((array) ($facts['guest'] ?? []));
$portalTotal = isset($facts['portal_total']) && $facts['portal_total'] !== '' ? (int) $facts['portal_total'] : null;
$reference = filled($facts['portal_reference'] ?? null) ? trim((string) $facts['portal_reference']) : ($evidence?->ical_interpretation['fields']['booking_reference'] ?? null);
$booking = $property->bookings()->create([
'guest_id' => $guest?->id,
'status' => BookingStatus::Reserved,
'source' => 'portal',
'intake' => IntakeKind::Booking,
'origin_channel_id' => $evidence?->origin_channel_id ?? $channel->id,
'portal_reference' => $reference,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $guests,
'hold_expires_at' => null,
'guest_confirmed_at' => ($facts['guest_confirmed'] ?? false) ? now() : null,
'internal_notes' => filled($facts['notes'] ?? null) ? trim((string) $facts['notes']) : null,
...$this->price->columns($property, $arrival, $departure, $guests, $portalTotal, $channel->name),
]);
if ($evidence !== null) {
$evidence->forceFill([
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest?->id,
'review_note' => 'Als Vorgang übernommen; der Vorgang führt diese Belegung.',
])->save();
}
$this->confirm->bind($booking);
if ($evidence !== null) {
app(ReconcileChannelRepresentations::class)->handle($property);
}
return $booking->refresh();
});
app(CaseAutomation::class)->advance($booking);
return $booking->refresh();
}
/**
* A portal calendar entry can become a case once: returns the case it already belongs to, or throws when the entry
* is no reservation of a portal.
*
* @throws ReservationException
*/
private function checkEvidence(BlockedPeriod $evidence): ?Booking
{
if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) {
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
}
if ($evidence->occupationKind() === OccupationKind::Block) {
throw new ReservationException('Eine Sperrzeit ist keine Buchung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
}
if ($evidence->is_representation && $evidence->linked_booking_id !== null) {
return Booking::query()->findOrFail($evidence->linked_booking_id);
}
if ($evidence->is_representation) {
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Der Vorgang gehört an die führende Belegung.');
}
return null;
}
/**
* The guest the portal named – only with a real name. A known e-mail address finds the existing guest without
* overwriting his data; nothing is invented.
*
* @param array<string, ?string> $data
*/
private function guestFrom(array $data): ?Guest
{
$data = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']));
if (blank($data['first_name'] ?? null) || blank($data['last_name'] ?? null)) {
return null;
}
$email = filled($data['email'] ?? null) ? mb_strtolower($data['email']) : null;
if ($email !== null && ($known = Guest::query()->where('email', $email)->whereNull('anonymized_at')->first()) !== null) {
return $known;
}
return Guest::query()->create([...array_filter($data, fn ($value) => $value !== null), 'email' => $email ?? '']);
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ public function conflictsFor(BlockedPeriod $block): array
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guestName()}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
$blocks = $property->blockedPeriods()
->occupying()
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('process:settings-report')]
#[Description('Show every landlord’s process defaults and all deviations of properties and channels (read only)')]
class ProcessSettingsReport extends Command
{
public function handle(TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant): void {
$this->line('');
$this->info($tenant->name);
$defaults = (array) ($tenant->process_defaults ?? []);
foreach (ProcessSetting::cases() as $setting) {
if (! $setting->isLandlordSetting()) {
continue;
}
$value = $setting->normalize($defaults[$setting->value] ?? null);
$this->line(' Standard · '.$setting->question().' '.$setting->describe($value ?? $setting->default()).($value === null ? ' (Grundeinstellung)' : ''));
}
$rows = [];
foreach (Property::query()->orderBy('name')->get() as $property) {
foreach ((array) ($property->process_overrides ?? []) as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting?->normalize($value) !== null) {
$rows[] = ['Wohnung '.$property->name, $setting->question(), $setting->describe($setting->normalize($value))];
}
}
}
foreach (Channel::query()->with('property')->orderBy('name')->get() as $channel) {
foreach ((array) ($channel->process_overrides ?? []) as $intake => $values) {
foreach ((array) $values as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting?->normalize($value) !== null) {
$rows[] = ['Portal '.$channel->name.' ('.$channel->property?->name.', '.(IntakeKind::tryFrom((string) $intake)?->getLabel() ?? $intake).')', $setting->question(), $setting->describe($setting->normalize($value))];
}
}
}
}
$rows === [] ? $this->line(' Keine Abweichungen.') : $this->table(['Wo', 'Einstellung', 'Wert'], $rows);
});
return self::SUCCESS;
}
}
@@ -4,7 +4,6 @@
use App\Actions\AutoOffer;
use App\Enums\BookingStatus;
use App\Enums\OfferMode;
use App\Models\Booking;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
@@ -27,9 +26,9 @@ public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
->where('status', BookingStatus::Reserved)
->where('offer_version', 0)
->where('hold_expires_at', '>', now())
->whereHas('property', fn ($query) => $query->where('offer_mode', OfferMode::Automatic)->where('pre_reservation_enabled', true))
->with(['property', 'guest'])
->get();
->with(['property', 'guest', 'importChannel', 'originChannel'])
->get()
->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && $booking->process()->preReservation());
$sent = 0;
foreach ($pending as $booking) {
+4 -8
View File
@@ -2,10 +2,10 @@
namespace App\Documents;
use App\Enums\ChannelBookingModel;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Process\ProcessSettings;
use App\Support\Content;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Illuminate\Support\HtmlString;
@@ -56,16 +56,12 @@ public static function capture(?ContractTemplate $template = null, ?Booking $boo
}
/**
* The contract template for a booking: chosen explicitly, else the portal's (for bookings that are binding at the
* portal its reservation template, otherwise its offer template), else the property's.
* The contract template for a case: chosen explicitly, else the one of its process settings – the channel's
* template for the case's intake kind (request or binding booking), else the property's, else the landlord's.
*/
public static function templateFor(Booking $booking, int|string|null $explicitId = null): ?ContractTemplate
{
$channel = $booking->importChannel ?? $booking->originChannel;
$portalId = $channel === null ? null : ($channel->booking_model === ChannelBookingModel::PortalBooking
? ($channel->contract_template_reservation_id ?? $channel->contract_template_id)
: $channel->contract_template_id);
$id = filled($explicitId) ? (int) $explicitId : ($portalId ?? $booking->property->contract_template_id);
$id = filled($explicitId) ? (int) $explicitId : app(ProcessSettings::class)->forBooking($booking)->contractTemplateId();
return $id ? ContractTemplate::query()->find($id) : null;
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* Where an activity of a case stands (docs/Prozessarchitektur/Querschnitt/Gates_und_Nachweise.md: done by us, done
* externally, not applicable, open, contradictory) – plus "waiting" for somebody else and "later" for what is not due.
*/
enum ActivityState: string implements HasColor, HasLabel
{
case Done = 'done';
case External = 'external';
case Open = 'open';
case Problem = 'problem';
case Waiting = 'waiting';
case Later = 'later';
case NotApplicable = 'not_applicable';
public function getLabel(): string
{
return match ($this) {
self::Done => 'erledigt',
self::External => 'übernimmt das Portal',
self::Open => 'zu tun',
self::Problem => 'Problem',
self::Waiting => 'wartet',
self::Later => 'später',
self::NotApplicable => 'entfällt',
};
}
public function getColor(): string
{
return match ($this) {
self::Done, self::External => 'success',
self::Open => 'warning',
self::Problem => 'danger',
self::Waiting => 'info',
self::Later, self::NotApplicable => 'gray',
};
}
public function icon(): string
{
return match ($this) {
self::Done, self::External => '✓',
self::Open => '●',
self::Problem => '!',
self::Waiting => '…',
self::Later => '○',
self::NotApplicable => '–',
};
}
/**
* Whether the landlord has to act.
*/
public function needsAction(): bool
{
return $this === self::Open || $this === self::Problem;
}
}
+5 -8
View File
@@ -2,14 +2,12 @@
namespace App\Enums;
use App\Filament\Pages\Dashboard;
use App\Filament\Pages\OccupancyCalendar;
use App\Filament\Pages\PricesAndOffers;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\BookingTasks\BookingTaskResource;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Filament\Resources\Guests\GuestResource;
use App\Filament\Resources\InboxMessages\InboxMessageResource;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
@@ -22,16 +20,15 @@ enum AdminMode: string implements HasDescription, HasLabel
case Expert = 'expert';
/**
* Menu entries of the simple mode: the few things needed every day: calendar, bookings with their file, tasks, mailbox, guests and prices.
* Menu entries of the simple mode: the start page with everything to do, calendar, cases, guests, blocked periods
* and prices. Tasks, portal tasks and the mailbox are part of the start page's work list.
*
* @var list<class-string>
*/
public const SIMPLE_NAVIGATION = [
Dashboard::class,
OccupancyCalendar::class,
BookingResource::class,
BookingTaskResource::class,
ChannelTaskResource::class,
InboxMessageResource::class,
GuestResource::class,
BlockedPeriodResource::class,
PricesAndOffers::class,
@@ -48,7 +45,7 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Simple => 'Das Tägliche: Postfach, Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
self::Simple => 'Das Tägliche: Start mit allem, was zu tun ist, Kalender, Vorgänge, Gäste, Sperrzeiten, Preise',
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
};
}
+4 -2
View File
@@ -16,6 +16,7 @@ enum BookingTaskKind: string implements HasLabel
case BalanceReminder = 'balance_reminder';
case CancellationRequest = 'cancellation_request';
case CancellationFee = 'cancellation_fee';
case PortalCancellation = 'portal_cancellation';
public function getLabel(): string
{
@@ -25,12 +26,13 @@ public function getLabel(): string
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
self::CancellationRequest => 'Stornierungswunsch des Gastes',
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
};
}
public function isPayment(): bool
{
return ! in_array($this, [self::CancellationRequest, self::CancellationFee], true);
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation], true);
}
/**
@@ -44,7 +46,7 @@ public function reminder(): ?array
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
self::CancellationRequest, self::CancellationFee => null,
self::CancellationRequest, self::CancellationFee, self::PortalCancellation => null,
};
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* The business constellation of a case (docs/Prozessarchitektur/01_Buchungsarchetypen.md). It follows from the way
* the case came in and who handles what – not from the channel's name alone.
*/
enum CaseType: string implements HasDescription, HasLabel
{
/** Own website or own direct way (phone, e-mail): request, own offer, acceptance. */
case A1 = 'a1';
/** Non-binding request passed on by an intermediary; own offer like A1. */
case A2 = 'a2';
/** Binding external booking, everything else is handled by the landlord. */
case A3 = 'a3';
/** Binding external booking with split handling (e.g. the portal collects the payments). */
case A4 = 'a4';
/** Binding external booking the portal handles almost completely. */
case A5 = 'a5';
/** Own use, private stay, maintenance or another block. */
case A6 = 'a6';
public function getLabel(): string
{
return match ($this) {
self::A1 => 'Eigene Anfrage',
self::A2 => 'Anfrage über ein Portal',
self::A3 => 'Portalbuchung, Abwicklung bei uns',
self::A4 => 'Portalbuchung, Zahlung über das Portal',
self::A5 => 'Portalbuchung, Abwicklung durch das Portal',
self::A6 => 'Eigene Nutzung / Sperre',
};
}
public function getDescription(): string
{
return match ($this) {
self::A1 => 'Anfrage → Angebot → Annahme durch den Gast',
self::A2 => 'Anfrage aus einem Portal, Angebot und Vertrag von uns',
self::A3 => 'Beim Portal schon verbindlich; Unterlagen, Zahlung und Gastkontakt übernehmen wir',
self::A4 => 'Beim Portal schon verbindlich; Unterlagen von uns, das Geld zieht das Portal ein',
self::A5 => 'Beim Portal schon verbindlich; das Portal erledigt Vertrag und Zahlung',
self::A6 => 'Eigenbelegung, private Überlassung, Wartung oder sonstige Sperre',
};
}
public function isExternallyBinding(): bool
{
return in_array($this, [self::A3, self::A4, self::A5], true);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How a case arrived – the "Eingangsart". Settings of a channel may differ per intake kind, because one portal can
* deliver both mere requests and bookings that are already binding.
*/
enum IntakeKind: string implements HasLabel
{
/** A request that is not binding yet (own website, phone, a portal passing on a request). */
case Inquiry = 'inquiry';
/** A booking that is already binding when it reaches us (made on a portal). */
case Booking = 'booking';
/** An internal occasion: own use, private stay, maintenance, block. */
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Inquiry => 'Anfrage',
self::Booking => 'Verbindliche Buchung',
self::Internal => 'Eigene Nutzung / Sperre',
};
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Enums;
/**
* The settings that shape how a case is handled. Each one has a built-in default; the landlord sets his own default,
* a property (expert area) and a channel per intake kind may deviate. A value that is not set inherits – a deliberately
* set 0, "no" or "manual" is a value of its own.
*/
enum ProcessSetting: string
{
case Processing = 'processing';
case PreReservation = 'pre_reservation';
case HoldHours = 'hold_hours';
case Documents = 'documents';
case Payments = 'payments';
case GuestMessages = 'guest_messages';
case ArrivalInfoDaysBefore = 'arrival_info_days_before';
case ContractTemplate = 'contract_template_id';
/**
* Built-in default (the behaviour before any landlord setting existed).
*/
public function default(): string|int|bool|null
{
return match ($this) {
self::Processing => ProcessingMode::Manual->value,
self::PreReservation => true,
self::HoldHours => 48,
self::Documents, self::Payments, self::GuestMessages => Responsibility::Landlord->value,
self::ArrivalInfoDaysBefore => 3,
self::ContractTemplate => null,
};
}
/**
* The question shown to the landlord, in plain words.
*/
public function question(): string
{
return match ($this) {
self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?',
self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?',
self::HoldHours => 'Wie lange gilt ein Angebot (und bleibt der Zeitraum reserviert)?',
self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?',
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::ArrivalInfoDaysBefore => 'Wann gehen die Anreise-Informationen an den Gast?',
self::ContractTemplate => 'Welche Vertragsvorlage wird verwendet?',
};
}
/**
* Intake kinds for which a channel may deviate (empty: landlord and property level only).
*
* @return list<IntakeKind>
*/
public function channelIntakes(): array
{
return match ($this) {
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate => [IntakeKind::Inquiry, IntakeKind::Booking],
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
self::Documents => [IntakeKind::Booking],
self::ArrivalInfoDaysBefore => [],
};
}
/**
* Whether the landlord sets this on his general settings page (the template is chosen per property or channel).
*/
public function isLandlordSetting(): bool
{
return $this !== self::ContractTemplate;
}
/**
* Normalises a stored or submitted value; null means "not set".
*/
public function normalize(mixed $value): string|int|bool|null
{
if ($value === null || $value === '') {
return null;
}
return match ($this) {
self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value,
self::Documents, self::Payments, self::GuestMessages => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value,
self::PreReservation => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
};
}
/**
* The value in plain words, for showing where a value comes from.
*/
public function describe(string|int|bool|null $value): string
{
return match ($this) {
self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–',
self::Documents, self::Payments, self::GuestMessages => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–',
self::PreReservation => $value ? 'ja' : 'nein',
self::HoldHours => $value.' Stunden',
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
self::ContractTemplate => $value === null ? 'Texte der Webseite' : 'Vorlage Nr. '.$value,
};
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Whether the system carries a case on by itself as far as the data allows, or prepares each step and waits for
* the landlord's release.
*/
enum ProcessingMode: string implements HasLabel
{
case Automatic = 'automatic';
case Manual = 'manual';
public function getLabel(): string
{
return match ($this) {
self::Automatic => 'Automatisch weiterbearbeiten',
self::Manual => 'Jeden Schritt selbst freigeben',
};
}
public static function fromOfferMode(OfferMode $mode): self
{
return $mode === OfferMode::Automatic ? self::Automatic : self::Manual;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Who takes care of a part of the handling: the landlord (with this system) or the portal.
*/
enum Responsibility: string implements HasLabel
{
case Landlord = 'landlord';
case Portal = 'portal';
public function getLabel(): string
{
return match ($this) {
self::Landlord => 'Wir',
self::Portal => 'Das Portal',
};
}
}
@@ -0,0 +1,77 @@
<?php
namespace App\Filament\Forms;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\ContractTemplate;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
/**
* Form fields of the process settings, asked as plain questions. On a deviation level (property, channel) an empty
* field means "as the level above" and the placeholder says which value that is; on the landlord level an empty field
* means the built-in default.
*/
class ProcessSettingFields
{
/**
* @param list<ProcessSetting> $settings
* @param callable(ProcessSetting): string $inherited plain-words value used when the field stays empty
* @return list<Field>
*/
public static function make(string $prefix, array $settings, callable $inherited): array
{
return array_map(fn (ProcessSetting $setting): Field => self::field($prefix.$setting->value, $setting, $inherited($setting)), $settings);
}
public static function field(string $name, ProcessSetting $setting, string $inheritedLabel): Field
{
$placeholder = 'wie Standard: '.$inheritedLabel;
return (match ($setting) {
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.'),
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::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options(Responsibility::class)->placeholder($placeholder),
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
ProcessSetting::ContractTemplate => Select::make($name)
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder($placeholder),
})->label($setting->question());
}
/**
* Normalised values of submitted fields; empty fields are dropped (not set = inherit).
*
* @param array<string, mixed> $data
* @param list<ProcessSetting> $settings
* @return array<string, string|int|bool>
*/
public static function values(array $data, array $settings): array
{
$values = [];
foreach ($settings as $setting) {
$value = $setting->normalize($data[$setting->value] ?? null);
if ($value !== null) {
$values[$setting->value] = $value;
}
}
return $values;
}
/**
* Stored values as form state (booleans as the select keys).
*
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
public static function state(array $values): array
{
return array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, $values);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Pages;
use App\Filament\Concerns\FollowsAdminMode;
use BackedEnum;
use Filament\Pages\Dashboard as BaseDashboard;
use Filament\Support\Icons\Heroicon;
/**
* The start page: first "Zu erledigen", then the coming stays and key figures.
*/
class Dashboard extends BaseDashboard
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHome;
protected static ?string $navigationLabel = 'Start';
protected static ?string $title = 'Start';
}
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Filament\Pages;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\ProcessSettingFields;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Support\Settings;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* "So arbeite ich": the landlord's own defaults for handling cases. A portal (Kanäle › Portal) and – in the expert
* area – a property may deviate; everything not set there follows these defaults.
*/
class HandlingSettings extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsVertical;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'So arbeite ich';
protected static ?string $title = 'So arbeite ich';
protected static ?string $slug = 'abwicklung';
protected static ?int $navigationSort = 2;
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin);
}
/**
* @return list<ProcessSetting>
*/
public static function settings(): array
{
return array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => $setting->isLandlordSetting()));
}
public function mount(): void
{
$this->form->fill(ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? [])));
}
public function form(Schema $schema): Schema
{
return $schema
->statePath('data')
->components([
Section::make('Ihre Standardeinstellungen')
->description('Gilt für alle Wohnungen und Portale, solange dort nichts anderes eingestellt ist. Neue Einstellungen gelten für neue Vorgänge; laufende Vorgänge behalten ihre Regeln.')
->columns(2)
->schema(ProcessSettingFields::make('', self::settings(), fn (ProcessSetting $setting): string => 'Grundeinstellung ('.$setting->describe($setting->default()).')')),
Section::make('Abweichungen')
->description('Wo Portale oder Wohnungen anders arbeiten. Ändern unter Portale bzw. Wohnungen (Expertenansicht).')
->collapsed()
->schema([Text::make(fn (): HtmlString => $this->deviations())]),
]);
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
]);
}
public function save(): void
{
$this->tenant()->update(['process_defaults' => ProcessSettingFields::values($this->form->getState(), self::settings())]);
Notification::make()->title('Gespeichert')->body('Gilt für neue Vorgänge.')->success()->send();
}
/**
* Every deviation of a property or a channel, in plain words.
*/
private function deviations(): HtmlString
{
$lines = [];
foreach (Property::query()->orderBy('name')->get() as $property) {
foreach ((array) ($property->process_overrides ?? []) as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting !== null && $setting->normalize($value) !== null) {
$lines[] = e($property->name).': '.e($setting->question()).' → <strong>'.e($setting->describe($setting->normalize($value))).'</strong>';
}
}
}
foreach (Channel::query()->with('property')->orderBy('name')->get() as $channel) {
foreach ((array) ($channel->process_overrides ?? []) as $intake => $values) {
foreach ((array) $values as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting !== null && $setting->normalize($value) !== null) {
$lines[] = e($channel->name.' ('.$channel->property?->name.', '.(IntakeKind::tryFrom((string) $intake)?->getLabel() ?? $intake).')').': '.e($setting->question()).' → <strong>'.e($setting->describe($setting->normalize($value))).'</strong>';
}
}
}
}
return new HtmlString($lines === [] ? 'Keine – überall gelten Ihre Standardeinstellungen.' : '<ul class="list-disc ps-5 space-y-1"><li>'.implode('</li><li>', $lines).'</li></ul>');
}
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
}
@@ -32,9 +32,9 @@ class BookingResource extends Resource
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Buchung';
protected static ?string $modelLabel = 'Vorgang';
protected static ?string $pluralModelLabel = 'Anfragen & Buchungen';
protected static ?string $pluralModelLabel = 'Vorgänge';
protected static ?string $recordTitleAttribute = 'reference';
@@ -4,9 +4,12 @@
use App\Actions\ConfirmBooking;
use App\Actions\CreateReservation;
use App\Actions\RecordPortalBooking;
use App\Actions\TakeOverExternalBooking;
use App\Exceptions\ReservationException;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\QuoteException;
@@ -17,61 +20,68 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
/**
* Entry of a new case that did not come through the website: a request (A1/A2) goes the same way as a website request,
* a booking already binding on a portal (A3–A5) is taken over as it is.
*/
class CreateBooking extends CreateRecord
{
protected static string $resource = BookingResource::class;
protected static ?string $title = 'Buchung erfassen';
protected static ?string $title = 'Neu eintragen';
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
try {
$property = Property::findOrFail($data['property_id']);
$stay = new StayRequest(
CarbonImmutable::parse($data['arrival']),
CarbonImmutable::parse($data['departure']),
(int) $data['guests'],
promoCode: $data['promo_code'] ?: null,
);
$guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']);
if (filled($data['channel_id'] ?? null)) {
$booking = app(RecordPortalBooking::class)->handle(
$property,
Channel::query()->findOrFail($data['channel_id']),
$stay,
$guest,
$data['portal_process'] ?? RecordPortalBooking::CONFIRM,
$data['portal_reference'] ?? null,
filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
$data['internal_notes'] ?: null,
(bool) ($data['guest_confirmed'] ?? false),
);
return $booking;
}
$booking = app(CreateReservation::class)->handle($property, $stay, $guest, source: 'manual', sendMails: $data['send_mails']);
if ($data['confirm_immediately']) {
app(ConfirmBooking::class)->handle($booking, notifyGuest: $data['send_mails']);
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Buchung nicht möglich')->body($exception->getMessage())->danger()->send();
if (($data['kind'] ?? null) === BookingForm::OWN_USE) {
$this->redirect(BlockedPeriodResource::getUrl());
$this->halt();
}
$booking->update(['internal_notes' => $data['internal_notes'] ?: null]);
try {
$property = Property::query()->findOrFail($data['property_id']);
$channel = filled($data['channel_id'] ?? null) ? Channel::query()->findOrFail($data['channel_id']) : null;
$arrival = CarbonImmutable::parse($data['arrival']);
$departure = CarbonImmutable::parse($data['departure']);
$guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']);
if ($data['kind'] === BookingForm::EXTERNAL) {
return app(TakeOverExternalBooking::class)->handle($property, $channel, $arrival, $departure, [
'guest' => $guest,
'guests' => filled($data['guests'] ?? null) ? (int) $data['guests'] : null,
'portal_reference' => $data['portal_reference'] ?? null,
'portal_total' => filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
'notes' => $data['internal_notes'] ?? null,
'guest_confirmed' => (bool) ($data['guest_confirmed'] ?? false),
]);
}
$stay = new StayRequest($arrival, $departure, (int) $data['guests'], promoCode: filled($data['promo_code'] ?? null) ? $data['promo_code'] : null);
$sendMails = (bool) ($data['send_mails'] ?? false);
$booking = app(CreateReservation::class)->handle($property, $stay, $guest, source: 'manual', sendMails: $sendMails && ! ($data['confirm_immediately'] ?? false), originChannel: $channel);
if ($data['confirm_immediately'] ?? false) {
app(ConfirmBooking::class)->handle($booking, notifyGuest: $sendMails && filled($booking->guest?->email));
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
$this->halt();
}
if (filled($data['internal_notes'] ?? null)) {
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '').$data['internal_notes'])]);
}
return $booking;
}
protected function getRedirectUrl(): string
{
return BookingResource::getUrl('view', ['record' => $this->getRecord()]);
/** @var Booking $record */
$record = $this->getRecord();
return BookingResource::getUrl('view', ['record' => $record]);
}
}
@@ -10,18 +10,26 @@
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Models\User;
use App\Pricing\PortalPrice;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Support\BookingProgress;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
@@ -40,85 +48,133 @@
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\Support\Htmlable;
use Throwable;
/**
* The case page. At the top only what matters now: the next step as one large button, "Beenden" and the switch between
* automatic and manual handling. Everything else that is possible right now sits under "Weitere Möglichkeiten";
* technical functions only in the expert view. Ending a case always takes the proper way – a binding booking is
* cancelled with its consequences, it cannot be "set back" by a status change.
*
* @property Booking $record
*/
class ViewBooking extends ViewRecord
{
protected static string $resource = BookingResource::class;
/** Actions for the expert view only. */
private const EXPERT = ['offerLink', 'contractText', 'setStatus'];
public function getTitle(): string
{
return "{$this->record->reference} · {$this->record->guest->full_name}";
return "{$this->record->reference} · {$this->record->guestName()}";
}
public function getSubheading(): string|Htmlable|null
{
return CaseActivities::situation($this->record);
}
protected function getHeaderActions(): array
{
return [
$actions = collect([
$this->sendOfferAction(),
$this->provideContactAction(),
$this->requestContactAction(),
AssignGuestAction::make(),
Action::make('sendOffer')
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden')
->icon(Heroicon::OutlinedPaperAirplane)
->color('success')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->modalHeading('Angebot an den Gast senden')
->modalDescription('Der Gast erhält das Angebot mit Vertragsentwurf per E-Mail und kann es über einen Link annehmen oder ablehnen. Erst mit seiner Annahme ist die Buchung verbindlich.')
->modalSubmitActionLabel('Angebot senden')
->modalWidth('3xl')
->fillForm(fn (): array => [
'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->property->hold_hours)->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
'guest' => $this->record->guest->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']),
])
->schema([
$this->confirmAction(),
$this->resendConfirmationAction(),
$this->portalPriceAction(),
$this->extendHoldAction(),
$this->servicesAction(),
$this->offerPdfAction(),
$this->contractAction(),
$this->offerLinkAction(),
$this->contractTextAction(),
$this->notesAction(),
$this->archiveAction(),
$this->setStatusAction(),
])->keyBy(fn (Action $action): string => $action->getName());
$next = CaseActivities::next($this->record)?->action;
$primary = $next !== null && $actions->has($next) ? $actions->pull($next)->color('primary')->size('lg')->icon(Heroicon::OutlinedArrowRightCircle) : null;
$expert = $actions->only(self::EXPERT)->values()->all();
$more = $actions->except(self::EXPERT)->values()->all();
return array_values(array_filter([
$primary,
$this->automationAction(),
$this->endAction(),
ActionGroup::make($more)->label('Weitere Möglichkeiten')->icon(Heroicon::OutlinedEllipsisHorizontal)->button()->color('gray'),
$this->isExpert() ? ActionGroup::make($expert)->label('Experte')->icon(Heroicon::OutlinedWrenchScrewdriver)->button()->color('gray') : null,
]));
}
private function isExpert(): bool
{
$user = auth()->user();
return $user instanceof User && $user->adminMode() === AdminMode::Expert;
}
private function sendOfferAction(): Action
{
return Action::make('sendOffer')
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking)
->modalHeading('Angebot an den Gast')
->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Angaben; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.')
->modalSubmitActionLabel('Senden')
->modalWidth('3xl')
->fillForm(fn (): array => [
'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,
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']) ?? [],
])
->schema([
Section::make('So geht das Angebot hinaus')->schema([
Text::make(fn (Get $get): string => $this->offerPricePreview($get)),
Text::make(fn (): string => 'Gast: '.$this->record->guestName().' · '.($this->record->guest?->email ?: 'keine E-Mail-Adresse')),
Text::make(fn (): string => 'Vertragsvorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite')),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
]),
Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast')->collapsed()->schema([
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')->helperText('Sonderkondition aus den Angeboten')->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('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),
Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(),
]),
Section::make('Vertragsvorlage und Anlagen')->schema([
Section::make('Vorlage und Anlagen')->schema([
Select::make('contract_template_id')
->label('Andere Vorlage für dieses Angebot')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('wie eingestellt'),
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all())
->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [])
->helperText('Vorausgewählt: Anlagen der Vorlage, deren Bedingung zu dieser Buchung passt (z. B. gebuchtes Wäschepaket). Sie können Anlagen hinzufügen oder entfernen.'),
Select::make('contract_template_id')
->label('Vorlage für dieses Angebot')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('Standard (Portal / Wohnung / Webseite)')
->helperText('Die Texte werden beim Versand fest im Angebot abgelegt.'),
->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []),
]),
Section::make('Gültigkeit & Nachricht')->columns(2)->schema([
DateTimePicker::make('valid_until')
->label('Angebot gültig bis')
->helperText(fn (): string => 'Standard: '.$this->record->property->hold_hours.' Stunden (Einstellung der Wohnung). Bis dahin bleibt der Zeitraum reserviert.')
->seconds(false)
->after('now')
->required(),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
]),
Section::make('Gast – so erscheint er im Mietvertrag')->columns(2)->collapsed()->schema([
DateTimePicker::make('valid_until')
->label('Angebot gültig bis')
->helperText(fn (): string => 'Eingestellt: '.$this->record->process()->holdHours().' Stunden. Bis dahin bleibt der Zeitraum reserviert.')
->seconds(false)
->after('now')
->required(),
Section::make('Gast – so erscheint er im Vertrag')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
@@ -126,246 +182,346 @@ protected function getHeaderActions(): array
TextInput::make('guest.city')->label('Ort')->maxLength(100),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50),
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(
fn () => $send->handle($this->record, $this->offerChanges($data)),
'Angebot gesendet',
)),
Action::make('provideContact')
->label('Kontaktdaten eintragen')
->icon(Heroicon::OutlinedUserPlus)
->color(fn (): string => blank($this->record->guest?->email) ? 'warning' : 'gray')
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Kontaktdaten des Gastes')
->modalDescription('Kontaktdaten aus Portalnachricht, E-Mail oder Telefonat. Danach kann der Vertragsprozess automatisch weiterlaufen oder von Hand fortgeführt werden.')
->modalWidth('3xl')
->fillForm(fn (): array => ['guest' => $this->record->guest->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']), 'process' => ProvideGuestContact::MANUAL, 'guest_confirmed' => $this->record->guest_confirmed_at !== null])
->schema([
Section::make('Gast')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
TextInput::make('guest.email')->label('E-Mail')->email()->maxLength(255),
TextInput::make('guest.phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
TextInput::make('guest.city')->label('Ort')->maxLength(100),
]),
Section::make('Wie geht es weiter?')->schema([
Radio::make('process')->hiddenLabel()->options([
ProvideGuestContact::MANUAL => 'Nur speichern – den Vertragsprozess führe ich von Hand weiter',
ProvideGuestContact::AUTOMATIC => 'Automatisch weiter: Portal-Buchung → Bestätigung und Vertrag per E-Mail, Anfrage → Angebot per E-Mail',
])->required(),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung per E-Mail bestätigt'),
]),
])
->action(function (array $data, ProvideGuestContact $provide): void {
try {
$message = $provide->handle($this->record, $data['guest'], $data['process'], (bool) $data['guest_confirmed']);
} catch (ReservationException|QuoteException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Angebot gesendet'));
}
private function provideContactAction(): Action
{
return Action::make('provideContact')
->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen')
->icon(Heroicon::OutlinedUserPlus)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Kontaktdaten des Gastes')
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.')
->modalWidth('3xl')
->fillForm(fn (): array => [
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']) ?? [],
'process' => $this->record->processingMode() === ProcessingMode::Automatic ? ProvideGuestContact::AUTOMATIC : ProvideGuestContact::MANUAL,
'guest_confirmed' => $this->record->guest_confirmed_at !== null,
])
->schema([
Section::make('Gast')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
TextInput::make('guest.email')->label('E-Mail')->email()->maxLength(255),
TextInput::make('guest.phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
TextInput::make('guest.city')->label('Ort')->maxLength(100),
]),
Section::make('Wie geht es danach weiter?')->schema([
Radio::make('process')->hiddenLabel()->options([
ProvideGuestContact::AUTOMATIC => 'Automatisch weitermachen – das System sendet als Nächstes Angebot bzw. Unterlagen',
ProvideGuestContact::MANUAL => 'Nur speichern – den nächsten Schritt gebe ich selbst frei',
])->required(),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung per E-Mail bestätigt'),
]),
])
->action(function (array $data, ProvideGuestContact $provide): void {
try {
$message = $provide->handle($this->record, $data['guest'], $data['process'], (bool) $data['guest_confirmed']);
} catch (ReservationException|QuoteException $exception) {
$this->record->refresh();
Notification::make()->title($message)->success()->send();
}),
Action::make('requestContact')
->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->color('gray')
->visible(fn (): bool => blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Gast um Kontaktdaten bitten')
->modalDescription('Der Text lässt sich im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). Mit „Als angefragt vermerken“ merkt sich die Buchungsakte, dass die Kontaktdaten erfragt wurden.')
->modalSubmitActionLabel('Als angefragt vermerken')
->fillForm(fn (): array => ['text' => $this->contactRequestText()])
->schema([
Textarea::make('text')->label('Nachricht an den Gast')->rows(10)->extraInputAttributes(['readonly' => true, 'onclick' => 'this.select()']),
])
->action(function (): void {
$this->record->forceFill(['contact_requested_at' => now()])->saveQuietly();
Notification::make()->title('Als angefragt vermerkt')->success()->send();
}),
Action::make('offerLink')
->label('Angebotslink')
->icon(Heroicon::OutlinedLink)
->color('gray')
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
->modalHeading('Link zum Angebot')
->modalDescription('Derselbe Link wie in der Angebots-E-Mail – z. B. zum Weitergeben per Messenger. Gültig bis zum Ende der Angebotsfrist.')
->schema([
TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable(),
])
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen'),
Action::make('offerPdf')
->label('Angebot (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->color('gray')
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf")),
Action::make('confirm')
->label('Direkt bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->color('gray')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Buchung direkt bestätigen')
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung bereits anders verbindlich vereinbart wurde (z. B. telefonisch). Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
->schema([
Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(true),
])
->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(
fn () => $confirm->handle($this->record, $data['notify']),
'Buchung bestätigt',
)),
Action::make('decline')
->label('Ablehnen')
->icon(Heroicon::OutlinedXCircle)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Anfrage ablehnen')
->schema([
Toggle::make('notify')->label('Absage an den Gast senden')->default(true),
])
->action(fn (array $data, DeclineBooking $decline) => $this->runWorkflow(
fn () => $decline->handle($this->record, $data['notify']),
'Anfrage abgelehnt',
)),
Action::make('extendHold')
->label('Vormerkung verlängern')
->icon(Heroicon::OutlinedClock)
->color('gray')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
->schema([
TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required(),
])
->action(function (array $data): void {
$from = $this->record->hold_expires_at?->isFuture() ? $this->record->hold_expires_at : now()->toImmutable();
$this->record->update(['hold_expires_at' => $from->addHours((int) $data['hours'])]);
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
}),
Action::make('resendConfirmation')
->label(fn (): string => $this->record->confirmation_failed_at !== null ? 'Bestätigung erneut senden (Versand fehlgeschlagen)' : 'Bestätigung erneut senden')
->icon(Heroicon::OutlinedEnvelope)
->color(fn (): string => $this->record->confirmation_failed_at !== null ? 'danger' : 'gray')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
->requiresConfirmation()
->modalDescription('Die Buchungsbestätigung mit dem Mietvertrag wird noch einmal an den Gast gesendet.')
->action(function (ConfirmBooking $confirm): void {
$sent = $confirm->resend($this->record->fresh());
$notification = Notification::make()->title($sent ? 'Bestätigung gesendet' : 'Versand fehlgeschlagen');
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send();
}),
Action::make('services')
->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle)
->color('gray')
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (kostenpflichtig oder kostenlos), z. B. aus einer Portalbuchung oder per E-Mail erfragt. Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis der Buchung wird dadurch nicht verändert.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([
Repeater::make('items')
->label('Leistungen')
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->orderBy('name')->get()->mapWithKeys(fn (Extra $extra): array => [$extra->id => $extra->name.($extra->price > 0 ? ' ('.Money::format($extra->price).')' : ' (kostenlos)')])->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
])
->columns(2)
->addActionLabel('Leistung hinzufügen'),
])
->action(function (array $data): void {
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) $item['quantity']);
}
$this->record->update(['extras' => $extras]);
Notification::make()->title('Zusatzleistungen gespeichert')->success()->send();
}),
Action::make('contractText')
->label('Vertragstext ansehen')
->icon(Heroicon::OutlinedDocumentMagnifyingGlass)
->color('gray')
->visible(fn (): bool => $this->record->offer_terms !== null)
->modalHeading(fn (): string => 'Vertrag '.$this->record->reference)
->modalContent(fn () => view('filament.booking-contract', ['booking' => $this->record]))
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->modalWidth('4xl'),
Action::make('contract')
->label('Mietvertrag')
->icon(Heroicon::OutlinedDocumentText)
->color('gray')
->visible(fn (): bool => $this->record->contract_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")),
ActionGroup::make([
Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->fillForm(fn (): array => ['internal_notes' => $this->record->internal_notes])
return;
}
$this->record->refresh();
Notification::make()->title($message)->success()->send();
});
}
private function requestContactAction(): Action
{
return Action::make('requestContact')
->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->visible(fn (): bool => blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Gast um Kontaktdaten bitten')
->modalDescription('Den Text im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). „Als angefragt vermerken“ hält fest, dass die Daten erfragt sind.')
->modalSubmitActionLabel('Als angefragt vermerken')
->fillForm(fn (): array => ['text' => $this->contactRequestText()])
->schema([Textarea::make('text')->label('Nachricht an den Gast')->rows(10)->extraInputAttributes(['readonly' => true, 'onclick' => 'this.select()'])])
->action(function (): void {
$this->record->forceFill(['contact_requested_at' => now()])->save();
Notification::make()->title('Als angefragt vermerkt')->success()->send();
});
}
private function confirmAction(): Action
{
return Action::make('confirm')
->label('Direkt verbindlich bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Buchung direkt bestätigen')
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung schon anders verbindlich vereinbart wurde (z. B. am Telefon). Der Zeitraum wird fest belegt.')
->schema([Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(fn (): bool => filled($this->record->guest?->email))])
->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(fn () => $confirm->handle($this->record, $data['notify']), 'Buchung bestätigt'));
}
private function resendConfirmationAction(): Action
{
return Action::make('resendConfirmation')
->label(fn (): string => match (true) {
$this->record->confirmation_failed_at !== null && $this->record->confirmation_sent_at === null => 'Unterlagen erneut senden (Versand fehlgeschlagen)',
$this->record->confirmation_sent_at === null => 'Unterlagen an den Gast senden',
default => 'Bestätigung erneut senden',
})
->icon(Heroicon::OutlinedEnvelope)
->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email))
->requiresConfirmation()
->modalDescription(fn (): string => 'Der Gast erhält die Buchungsbestätigung mit dem Vertrag (Vorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite').').')
->action(function (ConfirmBooking $confirm): void {
$missing = app(CaseAutomation::class)->documentBlockers($this->record);
if ($missing !== []) {
Notification::make()->title('Noch nicht möglich')->body(implode(' ', $missing))->warning()->send();
return;
}
$sent = $confirm->resend($this->record->fresh());
$this->record->refresh();
$notification = Notification::make()->title($sent ? 'Unterlagen gesendet' : 'Versand fehlgeschlagen');
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send();
});
}
private function portalPriceAction(): Action
{
return Action::make('portalPrice')
->label('Gesamtpreis laut Portal eintragen')
->icon(Heroicon::OutlinedCurrencyEuro)
->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true))
->modalDescription('Der Betrag, den der Gast beim Portal gebucht hat (Gesamtpreis). Er wird so übernommen und nicht in eigene Positionen zerlegt.')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests])
->schema([
EuroInput::make('portal_total')->label('Gesamtpreis laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
])
->action(function (array $data, PortalPrice $price): void {
$guests = filled($data['guests'] ?? null) ? (int) $data['guests'] : $this->record->guests;
$this->record->update(['guests' => $guests, ...$price->columns($this->record->property, $this->record->arrival, $this->record->departure, $guests, (int) $data['portal_total'], $this->record->processChannel()?->name)]);
CaseLog::record($this->record, 'price', 'Gesamtpreis laut Portal eingetragen: '.Money::format((int) $data['portal_total']));
$blockers = app(CaseAutomation::class)->advance($this->record->fresh());
$this->record->refresh();
Notification::make()->title('Preis gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
});
}
private function extendHoldAction(): Action
{
return Action::make('extendHold')
->label('Reservierung verlängern')
->icon(Heroicon::OutlinedClock)
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
->schema([TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required()])
->action(function (array $data): void {
$from = $this->record->hold_expires_at?->isFuture() ? $this->record->hold_expires_at : now()->toImmutable();
$this->record->update(['hold_expires_at' => $from->addHours((int) $data['hours'])]);
Notification::make()->title('Reserviert bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
});
}
private function servicesAction(): Action
{
return Action::make('services')
->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (z. B. aus einer Portalbuchung). Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis ändert sich dadurch nicht.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([
Repeater::make('items')
->label('Leistungen')
->schema([
Textarea::make('internal_notes')->label('Interne Notizen')->rows(6),
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->orderBy('name')->get()->mapWithKeys(fn (Extra $extra): array => [$extra->id => $extra->name.($extra->price > 0 ? ' ('.Money::format($extra->price).')' : ' (kostenlos)')])->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
])
->action(fn (array $data) => $this->record->update($data)),
Action::make('setStatus')
->label('Status von Hand ändern')
->icon(Heroicon::OutlinedAdjustmentsHorizontal)
->visible(fn (): bool => BookingProgress::kind($this->record) !== BookingProgress::OWN && $this->record->status !== BookingStatus::Declined)
->modalHeading('Status von Hand ändern')
->modalDescription('Für Buchungen, die das System nicht selbst weiterführt. Es werden keine E-Mails versendet. Wird die Buchung wieder verbindlich, prüft das System den Kalender. Stornieren und Ablehnen haben eigene Aktionen.')
->schema([
Select::make('status')->label('Neuer Status')->options(collect(SetBookingStatus::TARGETS)->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all())->required(),
Textarea::make('reason')->label('Grund / Anlass')->helperText('Wird in den internen Notizen festgehalten.')->required()->rows(2),
])
->action(function (array $data, SetBookingStatus $setStatus): void {
try {
$setStatus->handle($this->record, BookingStatus::from($data['status']), $data['reason'], auth()->user()->name);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
->columns(2)
->addActionLabel('Leistung hinzufügen'),
])
->action(function (array $data): void {
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) $item['quantity']);
}
$this->record->update(['extras' => $extras]);
CaseLog::record($this->record, 'services', 'Zusatzleistungen erfasst');
Notification::make()->title('Zusatzleistungen gespeichert')->success()->send();
});
}
return;
}
private function offerPdfAction(): Action
{
return Action::make('offerPdf')
->label('Angebot (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf"));
}
$this->record->refresh();
Notification::make()->title('Status geändert')->success()->send();
}),
Action::make('archive')
->label(fn (): string => $this->record->archived_at ? 'Aus dem Archiv holen' : 'Archivieren')
->icon(Heroicon::OutlinedArchiveBox)
->visible(fn (): bool => $this->record->archived_at !== null || $this->record->canBeArchived())
->modalDescription(fn (): string => $this->record->archived_at ? 'Die Buchung erscheint wieder in der Liste.' : 'Die Buchung verschwindet aus der Standardliste. Verlauf, E-Mails, Zahlungen und Dokumente bleiben vollständig erhalten.')
->requiresConfirmation()
->action(function (): void {
$this->record->update(['archived_at' => $this->record->archived_at ? null : now()]);
Notification::make()->title($this->record->archived_at ? 'Archiviert' : 'Wieder aktiv')->success()->send();
}),
Action::make('cancel')
->label('Stornieren')
->icon(Heroicon::OutlinedNoSymbol)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
->modalHeading('Buchung stornieren')
->modalDescription('Der Zeitraum wird wieder freigegeben. Gast und Vermieter erhalten eine Stornierungs-E-Mail; die Stornokosten bleiben als Aufgabe offen.')
->schema([
Toggle::make('notify_guest')->label('Gast per E-Mail informieren')->default(true),
Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true),
])
->action(function (array $data, CancelBooking $cancel): void {
try {
$informed = $cancel->handle($this->record, (bool) $data['notify_guest'], (bool) $data['costs_task'], auth()->user()->name);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
private function contractAction(): Action
{
return Action::make('contract')
->label('Mietvertrag (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->visible(fn (): bool => $this->record->contract_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf"));
}
return;
}
private function offerLinkAction(): Action
{
return Action::make('offerLink')
->label('Angebotslink')
->icon(Heroicon::OutlinedLink)
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
->modalHeading('Link zum Angebot')
->modalDescription('Derselbe Link wie in der Angebots-E-Mail. Gültig bis zum Ende der Angebotsfrist.')
->schema([TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable()])
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen');
}
$notification = Notification::make()->title('Buchung storniert');
($informed ? $notification->success() : $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte den Gast selbst informieren.'))->send();
}),
]),
];
private function contractTextAction(): Action
{
return Action::make('contractText')
->label('Vertragstext ansehen')
->icon(Heroicon::OutlinedDocumentMagnifyingGlass)
->visible(fn (): bool => $this->record->offer_terms !== null)
->modalHeading(fn (): string => 'Vertrag '.$this->record->reference)
->modalContent(fn () => view('filament.booking-contract', ['booking' => $this->record]))
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->modalWidth('4xl');
}
private function notesAction(): Action
{
return Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->fillForm(fn (): array => ['internal_notes' => $this->record->internal_notes])
->schema([Textarea::make('internal_notes')->label('Interne Notizen')->rows(6)])
->action(fn (array $data) => $this->record->update($data));
}
private function archiveAction(): Action
{
return Action::make('archive')
->label(fn (): string => $this->record->archived_at ? 'Aus dem Archiv holen' : 'Archivieren')
->icon(Heroicon::OutlinedArchiveBox)
->visible(fn (): bool => $this->record->archived_at !== null || $this->record->canBeArchived())
->modalDescription(fn (): string => $this->record->archived_at ? 'Der Vorgang erscheint wieder in der Liste.' : 'Der Vorgang verschwindet aus der Standardliste. Verlauf, E-Mails, Zahlungen und Dokumente bleiben erhalten.')
->requiresConfirmation()
->action(function (): void {
$this->record->update(['archived_at' => $this->record->archived_at ? null : now()]);
Notification::make()->title($this->record->archived_at ? 'Archiviert' : 'Wieder aktiv')->success()->send();
});
}
private function setStatusAction(): Action
{
return Action::make('setStatus')
->label('Status von Hand ändern')
->icon(Heroicon::OutlinedAdjustmentsHorizontal)
->visible(fn (): bool => $this->record->source !== 'website' && $this->record->status !== BookingStatus::Declined)
->modalHeading('Status von Hand ändern (Experte)')
->modalDescription('Nur für Korrekturen. Es werden keine E-Mails versendet; der Grund steht im Verlauf. Eine verbindliche Buchung kann so nicht beendet oder zur Anfrage gemacht werden – dafür gibt es „Beenden“.')
->schema([
Select::make('status')->label('Neuer Status')->options(collect(SetBookingStatus::TARGETS)->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all())->required(),
Textarea::make('reason')->label('Grund')->required()->rows(2),
])
->action(function (array $data, SetBookingStatus $setStatus): void {
try {
$setStatus->handle($this->record, BookingStatus::from($data['status']), $data['reason'], auth()->user()->name);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
Notification::make()->title('Status geändert')->success()->send();
});
}
/**
* Automatic or manual handling of this case.
*/
private function automationAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null;
}
$automatic = $this->record->processingMode() === ProcessingMode::Automatic;
return Action::make('automation')
->label($automatic ? 'Läuft automatisch' : 'Sie geben frei')
->icon($automatic ? Heroicon::OutlinedBolt : Heroicon::OutlinedHandRaised)
->color('gray')
->tooltip($automatic ? 'Das System macht selbst weiter, sobald alle Angaben da sind.' : 'Das System bereitet alles vor; Sie geben jeden Schritt frei.')
->modalHeading('Wie soll dieser Vorgang weiterlaufen?')
->modalDescription('Gilt nur für diesen Vorgang. Ihre allgemeine Einstellung finden Sie unter „So arbeite ich“.')
->fillForm(fn (): array => ['mode' => $this->record->processingMode()->value])
->schema([Radio::make('mode')->hiddenLabel()->options(ProcessingMode::class)->required()])
->action(function (array $data): void {
$this->record->update(['processing_mode' => $data['mode'] instanceof ProcessingMode ? $data['mode'] : ProcessingMode::from($data['mode'])]);
$blockers = app(CaseAutomation::class)->advance($this->record->fresh());
$this->record->refresh();
Notification::make()->title($this->record->processingMode()->getLabel())->body($blockers === [] ? null : 'Wartet auf: '.implode(' ', $blockers))->success()->send();
});
}
/**
* Ending a case: a request ends without booking; a binding booking is cancelled with its consequences (and on the
* portal as well when the contract was made there). There is no way around it by changing the status.
*/
private function endAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null;
}
$binding = $this->record->isBinding();
$hasEmail = filled($this->record->guest?->email);
return Action::make('end')
->label($binding ? 'Stornieren …' : 'Beenden …')
->icon(Heroicon::OutlinedStopCircle)
->color('danger')
->outlined()
->modalHeading($binding ? 'Gebuchten Vorgang stornieren' : 'Vorgang ohne Buchung beenden')
->modalDescription($binding
? 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel bleiben als Aufgabe offen.'.($this->record->caseType()->isExternallyBinding() ? ' Gebucht wurde beim Portal – dafür entsteht zusätzlich die Aufgabe, die Stornierung dort zu veranlassen bzw. zu prüfen.' : '')
: 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.')
->modalSubmitActionLabel($binding ? 'Stornieren' : 'Beenden')
->schema(array_values(array_filter([
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options(['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
Textarea::make('reason')->label('Grund')->required()->rows(2),
Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
])))
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $hasEmail): void {
$notify = $hasEmail && (bool) ($data['notify'] ?? false);
try {
$informed = CaseLog::context(fn () => $binding
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'])
: $decline->handle($this->record, $notify), reason: trim((string) $data['reason']));
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
$notification = Notification::make()->title($binding ? 'Buchung storniert' : 'Vorgang beendet');
($informed === false ? $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte selbst informieren.') : $notification->success())->send();
});
}
/**
@@ -375,8 +531,9 @@ private function contactRequestText(): string
{
$booking = $this->record;
$landlord = config('fewo.owner.name') ?: config('app.name');
$greeting = $booking->guest ? "Guten Tag {$booking->guest->first_name} {$booking->guest->last_name}," : 'Guten Tag,';
return "Guten Tag {$booking->guest->first_name} {$booking->guest->last_name},\n\n"
return "{$greeting}\n\n"
."vielen Dank für Ihre Buchung der {$booking->property->name} vom {$booking->arrival->format('d.m.Y')} bis {$booking->departure->format('d.m.Y')}. "
."Für den Mietvertrag benötigen wir noch Ihre Kontaktdaten: vollständige Anschrift (Straße, PLZ, Ort), eine E-Mail-Adresse und eine Telefonnummer.\n\n"
."Sobald wir die Angaben haben, senden wir Ihnen den Vertrag mit allen Informationen zu.\n\n"
@@ -414,7 +571,7 @@ private function offerPricePreview(Get $get): string
$adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0;
$promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : '';
return 'Gesamtpreis im Angebot: '.Money::format($quote->total() + $adjustment).' (bisher '.Money::format($this->record->total).')'.$promo;
return 'Preis im Angebot: '.Money::format($quote->total() + $adjustment).' für '.$stay->arrival->format('d.m.').'–'.$stay->departure->format('d.m.Y').', '.$stay->guests.' Personen'.$promo;
}
private function runWorkflow(callable $workflow, string $successTitle): void
@@ -427,6 +584,7 @@ private function runWorkflow(callable $workflow, string $successTitle): void
return;
}
$this->record->refresh();
Notification::make()->title($successTitle)->success()->send();
}
}
@@ -2,8 +2,8 @@
namespace App\Filament\Resources\Bookings\Schemas;
use App\Actions\RecordPortalBooking;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Models\Channel;
use App\Models\Property;
use App\Support\CurrentProperty;
@@ -14,21 +14,49 @@
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/**
* Manual entry of a booking received by phone or e-mail, or made binding by a portal (e.g. FeWo-direkt, usually
* without the guest's contact data). The price is calculated automatically; a portal price can be entered.
* "Neu": one entry for everything that arrives outside the website. The first question is what it is – a request,
* a booking already binding on a portal, or own use / a block – and only the fields that matter for that answer follow.
* Nothing has to be invented: unknown guest data, number of guests or portal price stay empty.
*/
class BookingForm
{
public const INQUIRY = 'inquiry';
public const EXTERNAL = 'external';
public const OWN_USE = 'own_use';
public static function configure(Schema $schema): Schema
{
$is = fn (string $kind): \Closure => fn (Get $get): bool => $get('kind') === $kind;
$isCase = fn (Get $get): bool => in_array($get('kind'), [self::INQUIRY, self::EXTERNAL], true);
return $schema
->components([
Section::make('Aufenthalt')
Section::make('Was möchten Sie eintragen?')
->schema([
Radio::make('kind')
->hiddenLabel()
->options([
self::INQUIRY => 'Eine Anfrage – per Telefon, E-Mail oder Nachricht über ein Portal',
self::EXTERNAL => 'Eine Buchung, die bei einem Portal schon fest gebucht ist',
self::OWN_USE => 'Eigene Nutzung oder eine Sperre (z. B. Wartung)',
])
->default(self::INQUIRY)
->required()
->live(),
Text::make(new HtmlString('Eigene Nutzung und Sperren tragen Sie bis auf Weiteres unter <a class="underline" href="'.e(BlockedPeriodResource::getUrl()).'">Sperrzeiten</a> ein.'))
->visible($is(self::OWN_USE)),
]),
Section::make('Zeitraum')
->columns(2)
->visible($isCase)
->schema([
Select::make('property_id')
->label('Wohnung')
@@ -40,58 +68,55 @@ public static function configure(Schema $schema): Schema
->label('Personen')
->integer()
->minValue(1)
->default(2)
->required(),
DatePicker::make('arrival')
->label('Anreise')
->required(),
DatePicker::make('departure')
->label('Abreise')
->after('arrival')
->required(),
TextInput::make('promo_code')
->label('Aktionscode'),
->helperText(fn (Get $get): ?string => $get('kind') === self::EXTERNAL ? 'Leer lassen, wenn nicht bekannt.' : null)
->required($is(self::INQUIRY)),
DatePicker::make('arrival')->label('Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required(),
]),
Section::make('Buchungsweg')
->description('Telefon oder E-Mail: nichts auswählen. Hat ein Portal die Buchung bereits verbindlich gemacht (z. B. FeWo-direkt), das Portal wählen – dann genügen Name und Zeitraum, die Kontaktdaten können später nachgetragen werden.')
Section::make('Portal')
->columns(2)
->visible($isCase)
->schema([
Select::make('channel_id')
->label('Über Portal')
->placeholder('Direkt / telefonisch / per E-Mail')
->label(fn (Get $get): string => $get('kind') === self::EXTERNAL ? 'Gebucht über' : 'Über ein Portal (optional)')
->placeholder('Direkt – kein Portal')
->options(fn (Get $get): array => Channel::query()->where('property_id', $get('property_id'))->orderBy('name')->pluck('name', 'id')->all())
->live(),
TextInput::make('portal_reference')->label('Referenz im Portal (Buchungsnummer)')->maxLength(100)->visible(fn (Get $get): bool => filled($get('channel_id'))),
EuroInput::make('portal_total')->label('Preis laut Portal (Gesamtpreis, optional)')->helperText('Weicht er von unserer Berechnung ab, wird die Differenz als Zeile „Abweichung Portalpreis“ geführt.')->visible(fn (Get $get): bool => filled($get('channel_id'))),
->required($is(self::EXTERNAL)),
TextInput::make('portal_reference')->label('Buchungsnummer im Portal')->maxLength(100)->visible($is(self::EXTERNAL)),
EuroInput::make('portal_total')
->label('Gesamtpreis laut Portal')
->helperText('Der Betrag, den der Gast beim Portal gebucht hat. Leer lassen, wenn noch nicht bekannt – er wird nicht geschätzt.')
->visible($is(self::EXTERNAL)),
]),
Section::make('Gast')
->description(fn (Get $get): ?string => filled($get('channel_id')) ? 'Bei Portalbuchungen ohne Kontaktdaten genügt der Name – E-Mail und Adresse können später ergänzt werden.' : null)
->description('Nur eintragen, was bekannt ist. Fehlendes wird später ergänzt; das System erinnert daran.')
->columns(2)
->visible($isCase)
->schema([
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required()->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->required(fn (Get $get): bool => blank($get('channel_id')))->maxLength(255),
TextInput::make('first_name')->label('Vorname')->required($is(self::INQUIRY))->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required($is(self::INQUIRY))->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->maxLength(255),
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('street')->label('Straße')->maxLength(255),
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
TextInput::make('city')->label('Ort')->maxLength(255),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible($is(self::EXTERNAL)),
]),
Section::make('Abschluss')
Section::make('Wie geht es weiter?')
->visible($is(self::INQUIRY))
->schema([
Textarea::make('internal_notes')->label('Interne Notiz'),
Toggle::make('confirm_immediately')->label('Sofort verbindlich bestätigen')->default(true)->visible(fn (Get $get): bool => blank($get('channel_id'))),
Toggle::make('send_mails')->label('E-Mails an den Gast senden')->default(false)->visible(fn (Get $get): bool => blank($get('channel_id'))),
Radio::make('portal_process')
->label('Wie geht der Vertragsprozess weiter?')
->options([
RecordPortalBooking::CONFIRM => 'Buchung bestätigen (Zeitraum belegen), Vertrag später – sobald die Kontaktdaten da sind',
RecordPortalBooking::CONTRACT => 'Buchung bestätigen und Vertrag jetzt per E-Mail senden (E-Mail-Adresse nötig)',
RecordPortalBooking::RECORD => 'Nur als Anfrage erfassen – alles Weitere von Hand',
])
->default(RecordPortalBooking::CONFIRM)
->required(fn (Get $get): bool => filled($get('channel_id')))
->visible(fn (Get $get): bool => filled($get('channel_id'))),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible(fn (Get $get): bool => filled($get('channel_id'))),
Toggle::make('confirm_immediately')
->label('Die Buchung ist mit dem Gast schon fest vereinbart – gleich verbindlich eintragen')
->helperText('Aus: Das System bereitet das Angebot vor; je nach Einstellung geht es automatisch hinaus oder wartet auf Ihre Freigabe.')
->default(false),
Toggle::make('send_mails')->label('Dem Gast E-Mails senden (Eingangsbestätigung bzw. Buchungsbestätigung)')->default(true),
TextInput::make('promo_code')->label('Aktionscode')->maxLength(50),
]),
Section::make('Notiz')
->visible($isCase)
->collapsed()
->schema([
Textarea::make('internal_notes')->hiddenLabel()->placeholder('Interne Notiz (nur für Sie sichtbar)'),
]),
]);
}
@@ -3,8 +3,16 @@
namespace App\Filament\Resources\Bookings\Schemas;
use App\Documents\OfferTerms;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Support\BookingProgress;
use App\Models\User;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\ProcessProfile;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Infolists\Components\RepeatableEntry;
@@ -15,189 +23,194 @@
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/**
* The case page: first where it stands and what is next, then the activities and the history, then the facts (guest,
* stay, price and payments, documents). Technical details are shown in the expert view only.
*/
class BookingInfolist
{
/**
* The process as a checklist: every milestone with its state and the activities that belong to it. Open
* activities name the action on this page that does them.
*/
private static function timeline(Booking $booking): HtmlString
{
$badge = [
'done' => ['✓', '#16a34a', 'erledigt'],
'current' => ['●', '#d97706', 'jetzt'],
'todo' => ['○', '#9ca3af', 'später'],
'skipped' => ['–', '#9ca3af', 'entfällt'],
];
$rows = collect(BookingProgress::steps($booking))->map(function (array $step) use ($badge): string {
[$icon, $color, $word] = $badge[$step['state']];
$activities = collect($step['activities'])->map(fn (array $activity): string => '<li style="margin:.15rem 0;'.($activity['done'] ? 'color:#15803d' : '').'">'.($activity['done'] ? '✓ ' : '○ ').e($activity['label']).($activity['action'] && $step['state'] !== 'skipped' ? ' <span style="color:#b45309">→ Aktion „'.e($activity['action']).'“</span>' : '').'</li>')->implode('');
return '<div style="display:flex;gap:.75rem;padding:.55rem 0;border-bottom:1px solid rgba(128,128,128,.25)">'
.'<div style="width:1.6rem;text-align:center;font-weight:700;color:'.$color.'" title="'.$word.'">'.$icon.'</div>'
.'<div style="flex:1"><div style="'.($step['state'] === 'current' ? 'font-weight:700' : '').($step['state'] === 'skipped' ? ';color:#9ca3af' : '').'">'.e($step['label']).($step['detail'] ? ' <span style="font-weight:400;color:#6b7280">· '.e($step['detail']).'</span>' : '').'</div>'
.($activities !== '' ? '<ul style="list-style:none;padding:0;margin:.2rem 0 0;font-size:.85rem">'.$activities.'</ul>' : '').'</div></div>';
})->implode('');
return new HtmlString('<div>'.$rows.'</div>');
}
/**
* What has happened so far, oldest first.
*/
private static function chronicle(Booking $booking): HtmlString
{
$rows = collect(BookingProgress::history($booking))->map(fn (array $event): string => '<li style="margin:.2rem 0"><span style="color:#6b7280">'.$event['at']->format('d.m.Y H:i').'</span> · '.e($event['label']).'</li>')->implode('');
return new HtmlString('<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
}
/**
* The standard process that applies to this booking: which template (with cancellation rule and annexes) comes from
* the portal and booking type, and whether payments become tasks.
*/
private static function setup(Booking $booking): string
{
$channel = $booking->importChannel ?? $booking->originChannel;
$template = OfferTerms::templateFor($booking);
$policy = $template?->cancellationPolicy;
$annexes = $template?->annexesFor($booking)->map(fn ($annex) => $annex->name)->implode(', ');
return collect([
$channel ? 'Portal: '.$channel->name : 'Eigene Buchung (Webseite / manuell)',
'Vertragsvorlage: '.($template ? $template->label() : 'Texte der Webseite'),
'Stornoregel: '.($policy ? $policy->name : 'keine hinterlegt'),
'Anlagen: '.($annexes ?: 'keine'),
'Zahlungsaufgaben: '.($booking->wantsPaymentTasks() ? 'ja' : 'nein (läuft über das Portal)'),
])->implode(' · ');
}
public static function configure(Schema $schema): Schema
{
return $schema
->columns(3)
->components([
Section::make('Vorgang')
Section::make('Als Nächstes')
->columnSpanFull()
->schema([
TextEntry::make('process')->label('Art des Vorgangs')->state(fn (Booking $record): string => BookingProgress::kindLabel($record)),
TextEntry::make('next')
->label(fn (Booking $record): string => 'Nächster Schritt: '.BookingProgress::next($record)['title'])
->state(fn (Booking $record): string => BookingProgress::next($record)['text'])
->color(fn (Booking $record): string => BookingProgress::next($record)['color'])
->weight('bold'),
TextEntry::make('setup')
->label('Standardprozess (aus Portal und Buchungstyp)')
->state(fn (Booking $record): string => self::setup($record))
->columnSpanFull(),
TextEntry::make('steps')
->label('Ablauf: Meilensteine und Aktivitäten')
->state(fn (Booking $record): HtmlString => self::timeline($record))
->html()
->columnSpanFull(),
TextEntry::make('chronicle')
->label('Bisheriger Verlauf')
->state(fn (Booking $record): HtmlString => self::chronicle($record))
->html()
->columnSpanFull(),
->hiddenLabel()
->state(fn (Booking $record): HtmlString => self::nextStep($record))
->html(),
]),
Grid::make(1)
->columnSpan(2)
->schema([
Section::make('Vertrag')
->columns(2)
->schema([
TextEntry::make('contract_template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) ? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].')' : ($record->offer_terms ? 'Texte der Webseite (Stand '.CarbonImmutable::parse($record->offer_terms['captured_at'])->format('d.m.Y').')' : 'Noch kein Angebot / Vertrag')),
TextEntry::make('contract_state')->label('Dokumente')->state(fn (Booking $record): string => collect([
$record->offer_path ? 'Angebot (PDF) Version '.$record->offer_version : null,
$record->contract_path ? 'Mietvertrag (PDF, unveränderlich, Prüfsumme '.substr((string) $record->contract_pdf_sha256, 0, 10).')' : null,
])->filter()->implode(' · ') ?: 'Noch kein Dokument – der Vertrag entsteht mit dem Angebot bzw. der Bestätigung'),
TextEntry::make('contract_mail')->label('Zustellung')->state(fn (Booking $record): string => $record->confirmation_sent_at ? 'Bestätigung mit Vertrag gesendet am '.$record->confirmation_sent_at->format('d.m.Y, H:i') : ($record->confirmation_failed_at ? 'Versand fehlgeschlagen' : 'Noch nicht gesendet'))->columnSpanFull(),
]),
Section::make('Aufenthalt')
->columns(3)
->schema([
TextEntry::make('property.name')->label('Wohnung'),
TextEntry::make('arrival')->label('Anreise')->date('l, d.m.Y'),
TextEntry::make('departure')->label('Abreise')->date('l, d.m.Y'),
TextEntry::make('nights')->label('Nächte')->state(fn (Booking $record): int => $record->nights()),
TextEntry::make('guests')->label('Personen'),
TextEntry::make('promo_code')->label('Aktionscode')->placeholder('–'),
]),
Section::make('Preis')
Section::make('Ablauf')
->description('Was erledigt ist, was wartet und was noch kommt.')
->schema([TextEntry::make('activities')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::activities($record))->html()]),
Section::make('Preis und Zahlungen')
->schema([
TextEntry::make('price_unknown')
->hiddenLabel()
->state('Der Gesamtpreis ist noch nicht bekannt.')
->color('warning')
->visible(fn (Booking $record): bool => $record->total === null),
RepeatableEntry::make('quote.lines')
->hiddenLabel()
->table([
TableColumn::make('Leistung'),
TableColumn::make('Betrag')->alignEnd(),
])
->visible(fn (Booking $record): bool => filled($record->quote['lines'] ?? null))
->table([TableColumn::make('Leistung'), TableColumn::make('Betrag')->alignEnd()])
->schema([
TextEntry::make('label'),
TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(),
]),
Grid::make(4)->schema([
Grid::make(4)->visible(fn (Booking $record): bool => $record->total !== null)->schema([
TextEntry::make('total')->label('Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->weight('bold'),
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'),
TextEntry::make('open')->label('Offen')
->state(fn (Booking $record): string => $record->process()->payments() === Responsibility::Portal ? 'über das Portal' : Money::format($record->openAmount()))
->color(fn (Booking $record): string => $record->process()->payments() === Responsibility::Landlord && $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y')->placeholder('–'),
]),
]),
Section::make('Verlauf')
->collapsible()
->schema([TextEntry::make('history')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::history($record))->html()]),
Section::make('Nachricht des Gastes')
->visible(fn (Booking $record): bool => filled($record->message))
->schema([
TextEntry::make('message')->hiddenLabel(),
]),
->schema([TextEntry::make('message')->hiddenLabel()]),
]),
Grid::make(1)
->columnSpan(1)
->schema([
Section::make('Status')
->schema([
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('hold_expires_at')->label('Vorgemerkt bis')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->hold_expires_at !== null),
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
TextEntry::make('processing')
->label('Bearbeitung / Vorreservierung')
->state(fn (Booking $record): string => $record->property->offer_mode->value === 'automatic' ? 'Automatisch' : 'Manuell')
->visible(fn (Booking $record): bool => $record->isDirect()),
TextEntry::make('offer')
->label('Angebot')
->state(fn (Booking $record): string => 'Version '.$record->offer_version.', gesendet '.$record->offer_sent_at?->format('d.m.Y, H:i').' · Prüfsumme '.substr((string) $record->offer_hash, 0, 12).(isset($record->offer_terms['template']) ? ' · Vorlage '.$record->offer_terms['template']['name'].' v'.$record->offer_terms['template']['version'] : ''))
->visible(fn (Booking $record): bool => $record->offer_version > 0),
TextEntry::make('accepted_at')->label('Angenommen am')->dateTime('d.m.Y, H:i:s')->visible(fn (Booking $record): bool => $record->accepted_at !== null),
TextEntry::make('confirmation')
->label('Bestätigungs-E-Mail')
->state(fn (Booking $record): string => $record->confirmation_sent_at !== null ? 'Gesendet '.$record->confirmation_sent_at->format('d.m.Y, H:i') : 'Nicht zugestellt – bitte „Bestätigung erneut senden“')
->color(fn (Booking $record): string => $record->confirmation_sent_at !== null ? 'success' : 'danger')
->visible(fn (Booking $record): bool => $record->confirmation_sent_at !== null || $record->confirmation_failed_at !== null),
TextEntry::make('source')->label('Buchungskanal / Quelle')->state(fn (Booking $record): string => $record->bookingChannelLabel()),
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
TextEntry::make('utm')
->label('Kampagne (UTM)')
->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)
->visible(fn (Booking $record): bool => filled($record->utm_source)),
]),
Section::make('Gast')
->schema([
TextEntry::make('guest.full_name')->label('Name'),
TextEntry::make('guest.email')->label('E-Mail')->placeholder('Unbekannt')->copyable(),
TextEntry::make('guest_name')->label('Name')->state(fn (Booking $record): string => $record->guestName())
->color(fn (Booking $record): ?string => $record->guest === null ? 'warning' : null),
TextEntry::make('guest.email')->label('E-Mail')->placeholder('noch nicht bekannt')->copyable(),
TextEntry::make('guest.phone')->label('Telefon')->placeholder('–'),
TextEntry::make('guest_address')
->label('Adresse')
->state(fn (Booking $record): ?string => collect([$record->guest->street, trim("{$record->guest->postal_code} {$record->guest->city}")])->filter()->implode(', ') ?: null)
->state(fn (Booking $record): ?string => $record->guest === null ? null : (collect([$record->guest->street, trim("{$record->guest->postal_code} {$record->guest->city}")])->filter()->implode(', ') ?: null))
->placeholder('–'),
]),
Section::make('Interne Notizen')
Section::make('Aufenthalt')
->schema([
TextEntry::make('internal_notes')->hiddenLabel()->placeholder('Keine Notizen'),
TextEntry::make('property.name')->label('Wohnung'),
TextEntry::make('period')->label('Zeitraum')->state(fn (Booking $record): string => $record->arrival->translatedFormat('D, d.m.Y').' – '.$record->departure->translatedFormat('D, d.m.Y').' ('.$record->nights().' Nächte)'),
TextEntry::make('guests')->label('Personen')->placeholder('noch nicht bekannt'),
TextEntry::make('channel')->label('Über')->state(fn (Booking $record): string => $record->bookingChannelLabel().($record->portal_reference ? ' · Nr. '.$record->portal_reference : '')),
]),
Section::make('Dokumente')
->schema([
TextEntry::make('documents')->hiddenLabel()->state(fn (Booking $record): string => collect([
$record->offer_path ? 'Angebot Version '.$record->offer_version : null,
$record->contract_path ? 'Mietvertrag' : null,
$record->confirmation_sent_at ? 'Bestätigung gesendet am '.$record->confirmation_sent_at->format('d.m.Y') : null,
])->filter()->implode(' · ') ?: 'Noch keine'),
TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template'])
? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].', festgeschrieben)'
: (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'),
]),
Section::make('Interne Notizen')
->collapsible()
->schema([TextEntry::make('internal_notes')->hiddenLabel()->placeholder('Keine Notizen')]),
]),
Section::make('Technische Angaben')
->description('Expertenansicht')
->columnSpanFull()
->collapsed()
->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert)
->columns(3)
->schema([
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
TextEntry::make('hold_expires_at')->label('Reserviert bis')->dateTime('d.m.Y, H:i')->placeholder('–'),
TextEntry::make('offer_hash')->label('Angebot (Prüfsumme)')->state(fn (Booking $record): ?string => $record->offer_version > 0 ? 'Version '.$record->offer_version.' · '.substr((string) $record->offer_hash, 0, 16) : null)->placeholder('–'),
TextEntry::make('contract_pdf_sha256')->label('Vertrag (Prüfsumme)')->formatStateUsing(fn (?string $state): string => substr((string) $state, 0, 16))->placeholder('–'),
TextEntry::make('accepted_at')->label('Angenommen am')->dateTime('d.m.Y, H:i:s')->placeholder('–'),
TextEntry::make('source')->label('Quelle'),
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
TextEntry::make('utm')->label('Kampagne (UTM)')->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)->placeholder('–'),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
]),
]);
}
/**
* The next step in large type, with what keeps an automatic case waiting.
*/
private static function nextStep(Booking $booking): HtmlString
{
$next = CaseActivities::next($booking);
$automatic = $booking->processingMode() === ProcessingMode::Automatic;
$waiting = collect(CaseActivities::for($booking))->first(fn ($activity): bool => $activity->state === ActivityState::Waiting);
$title = match (true) {
$next !== null => e($next->label),
$waiting !== null => 'Nichts zu tun – es wartet: '.e($waiting->label),
default => 'Nichts zu tun.',
};
$color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d');
$detail = $next?->detail ?? $waiting?->detail;
$mode = $automatic
? '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.';
return new HtmlString('<div style="font-size:1.35rem;font-weight:700;color:'.$color.'">'.$title.'</div>'
.($detail ? '<div style="margin-top:.2rem">'.e($detail).'</div>' : '')
.'<div style="margin-top:.5rem;color:#6b7280;font-size:.9rem">'.$mode.'</div>');
}
/**
* @return list<string>
*/
private static function blockers(Booking $booking): array
{
return $booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord
? app(CaseAutomation::class)->documentBlockers($booking)
: [];
}
private static function activities(Booking $booking): HtmlString
{
$colors = ['success' => '#15803d', 'warning' => '#b45309', 'danger' => '#dc2626', 'info' => '#2563eb', 'gray' => '#9ca3af'];
$rows = collect(CaseActivities::for($booking))
->reject(fn ($activity): bool => $activity->state === ActivityState::NotApplicable)
->map(function ($activity) use ($colors): string {
$color = $colors[$activity->state->getColor()];
$strong = $activity->state->needsAction() ? 'font-weight:700' : '';
return '<li style="display:flex;gap:.75rem;padding:.45rem 0;border-bottom:1px solid rgba(128,128,128,.2)">'
.'<span style="width:1.4rem;text-align:center;font-weight:700;color:'.$color.'">'.$activity->state->icon().'</span>'
.'<span style="flex:1;'.$strong.'">'.e($activity->label)
.($activity->detail ? ' <span style="font-weight:400;color:#6b7280">· '.e($activity->detail).'</span>' : '')
.($activity->url && $activity->state->needsAction() ? ' <a href="'.e($activity->url).'" style="color:#2563eb;text-decoration:underline">erledigen</a>' : '')
.'</span><span style="color:'.$color.';font-size:.85rem">'.e($activity->state->getLabel()).'</span></li>';
})->implode('');
return new HtmlString('<ul style="list-style:none;margin:0;padding:0">'.$rows.'</ul>');
}
private static function history(Booking $booking): HtmlString
{
$rows = $booking->events()->get()->map(fn ($event): string => '<li style="margin:.25rem 0"><span style="color:#6b7280">'.$event->occurred_at->format('d.m.Y H:i').'</span> · '.e($event->summary)
.($event->actor ? ' <span style="color:#6b7280">('.e($event->actor).')</span>' : '')
.($event->reason ? '<div style="color:#6b7280;margin-left:1rem">Grund: '.e($event->reason).'</div>' : '').'</li>')->implode('');
return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
}
private static function profile(Booking $booking): HtmlString
{
$profile = $booking->process();
$rows = collect(ProcessSetting::cases())
->reject(fn (ProcessSetting $setting): bool => in_array($setting, ProcessProfile::LIVE, true))
->map(fn (ProcessSetting $setting): string => '<li>'.e($setting->question()).' <strong>'.e($setting->describe($profile->value($setting))).'</strong> <span style="color:#6b7280">('.e(ProcessProfile::sourceLabel($profile->source($setting))).')</span></li>')
->implode('');
return new HtmlString('<ul style="list-style:disc;padding-left:1.2rem">'.$rows.'</ul><div style="color:#6b7280;font-size:.85rem">Festgelegt '.e(($profile->origin === 'migration' ? 'bei der Übernahme der bisherigen Daten' : 'beim Eingang').($profile->frozenAt ? ' am '.CarbonImmutable::parse($profile->frozenAt)->format('d.m.Y H:i') : '')).($booking->processing_mode ? ' · Bearbeitung für diesen Vorgang: '.e($booking->processing_mode->getLabel()) : '').'</div>');
}
}
@@ -21,7 +21,7 @@ class BookingsTable
public static function configure(Table $table, ?int $guestId = null): Table
{
return $table
->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. „Akte öffnen“ zeigt alles zu einem Vorgang: nächster Schritt, Vertrag, Zahlungen, Aufgaben und E-Mails. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.')
->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. „Öffnen“ zeigt alles zu einem Vorgang: nächster Schritt, Vertrag, Zahlungen, Aufgaben und E-Mails. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.')
->records(function (?string $search, ?string $sortColumn, ?string $sortDirection, array $filters, int $page, int|string $recordsPerPage) use ($guestId, $table): LengthAwarePaginator {
$propertyId = filled($filters['property']['value'] ?? null) ? (int) $filters['property']['value'] : null;
$records = app(OccupancyOverview::class)->records($propertyId, $guestId);
@@ -102,6 +102,6 @@ public static function configure(Table $table, ?int $guestId = null): Table
Filter::make('without_guest')->label('Gastzuordnung offen'),
])
->recordUrl(fn (array $record): string => $record['url'])
->recordActions([Action::make('view')->label(fn (array $record): string => $record['record_type'] === 'booking' ? 'Akte öffnen' : ($record['kind'] === 'block' ? 'Details' : 'Akte anlegen'))->icon('heroicon-o-folder-open')->button()->color('primary')->url(fn (array $record): string => $record['url'])]);
->recordActions([Action::make('view')->label(fn (array $record): string => $record['record_type'] === 'booking' ? 'Öffnen' : ($record['kind'] === 'block' ? 'Details' : 'Als Buchung übernehmen'))->icon('heroicon-o-folder-open')->button()->color('primary')->url(fn (array $record): string => $record['url'])]);
}
}
@@ -7,11 +7,13 @@
use App\Enums\ChannelEchoBehavior;
use App\Enums\ChannelExportMode;
use App\Enums\ChannelStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Filament\Forms\ProcessSettingFields;
use App\Models\Channel;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Support\CurrentProperty;
use App\Support\Settings;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
@@ -51,34 +53,9 @@ public static function configure(Schema $schema, bool $selectProperty = false):
->required()
->maxLength(100),
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
Select::make('booking_model')->label('Buchungsmodell')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
Select::make('booking_model')->label('Was kommt über dieses Portal?')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'),
Section::make('Standardprozess für Buchungen über dieses Portal')
->description('Hier legen Sie fest, was bei einer Buchung über dieses Portal gilt – getrennt nach Buchungstyp. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Vertragsanlagen mit (Menü Einrichtung › Vertragsvorlagen). Der Ablauf selbst (Kontaktdaten, Vertrag, Zahlung, Anreise) steht in der Akte jeder Buchung.')
->columns(2)
->columnSpanFull()
->schema([
Select::make('contract_template_id')
->label('Anfrage über dieses Portal: Vertragsvorlage')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('Standard der Wohnung')
->live()
->helperText(fn (Get $get): string => self::templateSummary($get('contract_template_id'), 'Wir antworten persönlich, Angebot und Vertrag kommen von uns. ')),
Select::make('contract_template_reservation_id')
->label('Buchung beim Portal verbindlich: Vertragsvorlage')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('wie bei Anfragen')
->live()
->helperText(fn (Get $get): string => self::templateSummary($get('contract_template_reservation_id') ?? $get('contract_template_id'), 'Das Portal hat die Buchung schon verbindlich gemacht, wir senden den Vertrag. ')),
Toggle::make('payment_tasks_inquiry')
->label('Anfrage über dieses Portal: Zahlungsaufgaben anlegen')
->helperText('Fällige Anzahlungen/Restzahlungen erscheinen als Aufgabe (Mails an Gäste gehen nie automatisch).')
->default(true),
Toggle::make('payment_tasks_reservation')
->label('Buchung beim Portal verbindlich: Zahlungsaufgaben anlegen')
->helperText('Aus, wenn das Portal das Geld einzieht und mahnt (z. B. FeWo-direkt Online-Buchung).')
->default(false),
]),
...self::processSections(),
Select::make('connector')
->label('Kalenderanbindung')
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.')
@@ -128,15 +105,35 @@ public static function configure(Schema $schema, bool $selectProperty = false):
/**
* What a contract template brings along, shown under the template choice.
*/
private static function templateSummary(mixed $templateId, string $intro): string
/**
* Deviations of this portal from the landlord's defaults, separately for requests and for bookings that are already
* binding when they arrive. Empty fields follow the defaults (System › So arbeite ich).
*
* @return list<Section>
*/
private static function processSections(): array
{
$template = filled($templateId) ? ContractTemplate::query()->with('cancellationPolicy')->find($templateId) : null;
if ($template === null) {
return $intro.'Ohne Auswahl gilt die Vorlage der Wohnung bzw. die Texte der Webseite.';
}
$defaults = (array) (Settings::tenant()?->process_defaults ?? []);
$inherited = function (ProcessSetting $setting) use ($defaults): string {
$value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default();
$annexes = ContractAnnex::query()->whereIn('id', (array) ($template->annex_ids ?? []))->orderBy('name')->pluck('name')->implode(', ');
return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value);
};
$settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array($intake, $setting->channelIntakes(), true)));
return $intro.'Die Vorlage bringt mit: Stornoregel '.($template->cancellationPolicy?->name ?? '– keine –').' · Anlagen: '.($annexes ?: 'keine').'.';
return [
Section::make('Anfragen über dieses Portal')
->description('Nur ausfüllen, was bei diesem Portal anders ist als in Ihren Standardeinstellungen.')
->columns(2)
->columnSpanFull()
->collapsible()
->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settingsFor(IntakeKind::Inquiry), $inherited)),
Section::make('Feste Buchungen über dieses Portal')
->description('Buchungen, die beim Portal schon verbindlich sind. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Anlagen mit.')
->columns(2)
->columnSpanFull()
->collapsible()
->schema(ProcessSettingFields::make('process_overrides.booking.', $settingsFor(IntakeKind::Booking), $inherited)),
];
}
}
@@ -80,7 +80,7 @@ public static function table(Table $table): Table
TextColumn::make('channel.name')->label('Importkanal'),
TextColumn::make('property.name')->label('Wohnung')->toggleable(),
TextColumn::make('needs_review')->label('Prüffall')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->description(fn (BlockedPeriod $record): ?string => $record->review_note),
])->recordActions([Action::make('fileLink')->label('Akte anlegen')->icon(Heroicon::OutlinedFolderPlus)->button()->color('primary')->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), static::showFileAction()->button(), ViewAction::make(), ActionGroup::make(static::occupationActions(withFile: false))->label('Weitere Aktionen')]);
])->recordActions([Action::make('fileLink')->label('Als Buchung übernehmen')->icon(Heroicon::OutlinedFolderPlus)->button()->color('primary')->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), static::showFileAction()->button(), ViewAction::make(), ActionGroup::make(static::occupationActions(withFile: false))->label('Weitere Aktionen')]);
}
public static function occupationActions(bool $withFile = true): array
@@ -94,16 +94,16 @@ public static function occupationActions(bool $withFile = true): array
}
/**
* Opens the booking file (workflow, contract, payments, tasks) for a reservation from a portal calendar.
* Takes a reservation from a portal calendar over as a case (no second, manual "file").
*/
public static function openFileAction(): Action
{
return Action::make('openFile')->label('Akte anlegen')->icon(Heroicon::OutlinedFolderPlus)->color('primary')
return Action::make('openFile')->label('Als Buchung übernehmen')->icon(Heroicon::OutlinedFolderPlus)->color('primary')
->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
->requiresConfirmation()
->modalHeading('Akte für diese Reservierung anlegen')
->modalDescription('Aus der Kalenderbelegung wird eine Buchung mit Ablauf: Kontaktdaten, Vertrag, Zahlungen, Anreise, Storno. Der Zeitraum bleibt durchgehend belegt. Gast, Personenzahl und Preis sind noch unbekannt und werden in der Akte ergänzt.')
->modalHeading('Reservierung als Buchung übernehmen')
->modalDescription('Aus der Kalenderbelegung wird ein Vorgang „Gebucht über das Portal“. Der Zeitraum bleibt durchgehend belegt. Gast, Personenzahl und Preis bleiben leer, bis sie bekannt sind – der Vorgang erinnert daran.')
->action(function (BlockedPeriod $record, OpenPortalFile $open) {
try {
$booking = $open->handle($record);
@@ -113,7 +113,7 @@ public static function openFileAction(): Action
return null;
}
Notification::make()->title('Akte angelegt')->success()->send();
Notification::make()->title('Als Buchung übernommen')->success()->send();
return redirect(BookingResource::getUrl('view', ['record' => $booking]));
});
@@ -121,7 +121,7 @@ public static function openFileAction(): Action
public static function showFileAction(): Action
{
return Action::make('showFile')->label('Akte öffnen')->icon(Heroicon::OutlinedFolderOpen)->color('primary')
return Action::make('showFile')->label('Vorgang öffnen')->icon(Heroicon::OutlinedFolderOpen)->color('primary')
->visible(fn (BlockedPeriod $record): bool => $record->linked_booking_id !== null)
->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : null);
}
@@ -2,13 +2,17 @@
namespace App\Filament\Resources\Properties\Schemas;
use App\Enums\AdminMode;
use App\Enums\CancellationMode;
use App\Enums\OfferMode;
use App\Enums\ProcessSetting;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Forms\ProcessSettingFields;
use App\Filament\Pages\HandlingSettings;
use App\ImageWorlds\ImageWorldRegistry;
use App\Models\ContractTemplate;
use App\Models\Site;
use Closure;
use App\Models\User;
use App\Support\Settings;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
@@ -111,14 +115,6 @@ public static function configure(Schema $schema): Schema
->minValue(0)
->suffix('Tage vor Anreise')
->default(28),
TextInput::make('hold_hours')
->label('Vorreservierung halten')
->helperText('So lange bleibt ein angefragter Zeitraum ohne Ihre Bestätigung blockiert.')
->required()
->integer()
->minValue(1)
->suffix('Stunden')
->default(48),
Select::make('cancellation_mode')
->label('Stornierungslink in der Buchungsbestätigung')
->options(CancellationMode::class)
@@ -144,32 +140,17 @@ public static function configure(Schema $schema): Schema
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('Texte der Webseite')
->helperText('Wird bei neuen Angeboten verwendet, sofern das Portal keine eigene Vorlage hat.'),
TextInput::make('arrival_info_days_before')
->label('Anreise-E-Mail senden')
->helperText('Automatische Mail mit den letzten Hinweisen (Texte unter Texte › Aufenthalt).')
->required()
->integer()
->minValue(1)
->maxValue(14)
->suffix('Tage vor Anreise')
->default(3),
Toggle::make('pre_reservation_enabled')
->label('Anfrage blockiert den Kalender (Vorreservierung)')
->helperText('Aus: eine bloße Anfrage sperrt keinen Zeitraum. Dann ist kein automatisches Angebot möglich.')
->default(true)
->live(),
Select::make('offer_mode')
->label('Bearbeitung von Anfragen')
->options(OfferMode::class)
->default(OfferMode::Manual)
->required()
->helperText('Automatisch: das Angebot geht sofort an den Gast, wenn die Kalenderprüfung bestanden ist (Kalenderstand aktuell, bei Portalen mit Sofortbuchung unser Feed nachweislich abgerufen). Sonst entscheiden Sie von Hand. Unabhängig vom Testbetrieb der E-Mails.')
->rules([fn (Get $get): Closure => function (string $attribute, mixed $value, Closure $fail) use ($get): void {
if (($value === OfferMode::Automatic->value || $value === OfferMode::Automatic) && ! $get('pre_reservation_enabled')) {
$fail('Automatische Angebote brauchen die Vorreservierung: ohne Sperre im Kalender kann ein verbindlich annehmbares Angebot nicht sicher erteilt werden.');
}
}]),
]),
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.')
->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert)
->collapsed()
->columns(2)
->schema(ProcessSettingFields::make('process_overrides.', HandlingSettings::settings(), function (ProcessSetting $setting): string {
$defaults = (array) (Settings::tenant()?->process_defaults ?? []);
return $setting->describe($setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default());
})),
]);
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ public function table(Table $table): Table
TextColumn::make('arrival')->label('Anreise')->date('D, d.m.')
->description(fn (Booking $record): ?string => $record->arrival->isToday() ? 'heute' : ($record->arrival->isPast() ? 'läuft' : null)),
TextColumn::make('departure')->label('Abreise')->date('D, d.m.'),
TextColumn::make('guest.last_name')->label('Gast')->formatStateUsing(fn (Booking $record): string => $record->guest->full_name),
TextColumn::make('guest.last_name')->label('Gast')->formatStateUsing(fn (Booking $record): string => $record->guestName()),
TextColumn::make('guests')->label('Pers.'),
TextColumn::make('status')->label('Status')->badge(),
TextColumn::make('open')->label('Offen')
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Filament\Widgets;
use App\Enums\UserRole;
use App\Process\WorkList;
use Filament\Widgets\Widget;
/**
* "Zu erledigen" at the top of the start page: one list of everything the landlord has to do.
*/
class WorkListWidget extends Widget
{
protected static ?int $sort = 0;
protected static bool $isLazy = false;
protected int|string|array $columnSpan = 'full';
protected string $view = 'filament.widgets.work-list';
public static function canView(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
}
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
return ['items' => WorkList::items()];
}
}
+3 -2
View File
@@ -7,6 +7,7 @@
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
@@ -50,7 +51,7 @@ public function accept(Request $request, Booking $booking, AcceptOffer $accept):
$request->validate(['terms' => ['accepted']], ['terms.accepted' => 'Bitte bestätigen Sie, dass Sie die Bedingungen gelesen haben.']);
return $this->answer($request, $booking, function (int $version) use ($accept, $booking): string {
$concluded = $accept->handle($booking, $version);
$concluded = CaseLog::context(fn (): bool => $accept->handle($booking, $version), actor: CaseLog::GUEST);
$booking->refresh();
if (! $concluded) {
@@ -66,7 +67,7 @@ public function accept(Request $request, Booking $booking, AcceptOffer $accept):
public function reject(Request $request, Booking $booking, RejectOffer $reject): RedirectResponse
{
return $this->answer($request, $booking, function (int $version) use ($reject, $booking): string {
$reject->handle($booking, $version);
CaseLog::context(fn () => $reject->handle($booking, $version), actor: CaseLog::GUEST);
return 'Schade – wir haben Ihre Absage erhalten und den Zeitraum wieder freigegeben. Vielleicht ein anderes Mal!';
});
@@ -8,6 +8,7 @@
use App\Enums\CancellationMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use App\Support\CancellationCost;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
@@ -37,7 +38,7 @@ public function showRelease(Booking $booking): View
public function release(Booking $booking, ReleaseReservation $release): RedirectResponse
{
try {
$release->handle($booking);
CaseLog::context(fn () => $release->handle($booking), actor: CaseLog::GUEST);
} catch (ReservationException $exception) {
return redirect()->to($this->signed('reservations.release', $booking, now()->addDays(2)))->with('self-service.error', $exception->getMessage());
}
@@ -67,7 +68,7 @@ public function cancel(Request $request, Booking $booking, CancelBookingByGuest
$back = fn (int $days): string => $this->signed('bookings.cancel', $booking, now()->addDays($days));
try {
$outcome = $cancel->handle($booking, $data['message'] ?? null);
$outcome = CaseLog::context(fn () => $cancel->handle($booking, $data['message'] ?? null), actor: CaseLog::GUEST);
} catch (ReservationException $exception) {
return redirect()->to($back(2))->with('self-service.error', $exception->getMessage());
}
+1 -1
View File
@@ -20,7 +20,7 @@ public function __construct(public Booking $booking, public bool $cancelled) {}
public function envelope(): Envelope
{
return new Envelope(subject: ($this->cancelled ? 'Storniert: ' : 'Stornierungswunsch: ').$this->booking->reference.' – '.$this->booking->guest->full_name);
return new Envelope(subject: ($this->cancelled ? 'Storniert: ' : 'Stornierungswunsch: ').$this->booking->reference.' – '.$this->booking->guestName());
}
public function content(): Content
+77 -18
View File
@@ -5,11 +5,17 @@
use App\Documents\OfferTerms;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\ChannelBookingModel;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\ReferralSource;
use App\Enums\Responsibility;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\HasChannelProvenance;
use App\Observers\BookingObserver;
use App\Process\CaseRecorder;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -24,8 +30,10 @@
use Illuminate\Support\HtmlString;
/**
* A reservation or booking. arrival is the first night, departure the day the guest leaves,
* so a departure and the next arrival on the same day do not collide.
* A case ("Vorgang", docs/Prozessarchitektur): one business occasion from its first arrival to its end – a request,
* a booking already binding on a portal, or an internal use. arrival is the first night, departure the day the guest
* leaves, so a departure and the next arrival on the same day do not collide. Guest, number of guests and amounts may
* be unknown (null) – unknown is never replaced by an invented value.
*/
#[ObservedBy(BookingObserver::class)]
#[Fillable([
@@ -33,6 +41,10 @@
'guest_id',
'status',
'source',
'intake',
'case_type',
'profile',
'processing_mode',
'import_channel_id',
'origin_channel_id',
'portal_reference',
@@ -94,9 +106,12 @@ public function isDirect(): bool
protected static function booted(): void
{
static::saving(fn (Booking $booking) => CaseRecorder::freeze($booking));
static::created(function (Booking $booking): void {
$booking->forceFill(['reference' => $booking->nextReference()])->saveQuietly();
CaseRecorder::created($booking);
});
static::updated(fn (Booking $booking) => CaseRecorder::updated($booking));
}
/**
@@ -134,6 +149,10 @@ protected function casts(): array
{
return [
'status' => BookingStatus::class,
'intake' => IntakeKind::class,
'case_type' => CaseType::class,
'profile' => 'array',
'processing_mode' => ProcessingMode::class,
'referral_source' => ReferralSource::class,
'arrival' => 'immutable_date',
'departure' => 'immutable_date',
@@ -189,6 +208,51 @@ public function importChannel(): BelongsTo
return $this->belongsTo(Channel::class, 'import_channel_id');
}
/** @return HasMany<BookingEvent, $this> */
public function events(): HasMany
{
return $this->hasMany(BookingEvent::class)->orderBy('occurred_at')->orderBy('id');
}
/**
* The channel whose settings apply: the one the case was imported from, else its origin channel (owner).
*/
public function processChannel(): ?Channel
{
return $this->importChannel ?? $this->originChannel;
}
/**
* The rules of this case as frozen when it came in (resolved now for a case that has none yet).
*/
public function process(): ProcessProfile
{
return filled($this->profile) ? ProcessProfile::fromArray($this->profile) : app(ProcessSettings::class)->forBooking($this);
}
public function caseType(): CaseType
{
return $this->case_type ?? $this->process()->caseType;
}
/**
* Automatic or manual: the decision taken on this case, else the setting frozen with its profile.
*/
public function processingMode(): ProcessingMode
{
return $this->processing_mode ?? $this->process()->processing();
}
public function isBinding(): bool
{
return in_array($this->status, BookingStatus::occupying(), true);
}
public function guestName(): string
{
return $this->guest?->full_name ?? 'Gast noch nicht bekannt';
}
/** @return HasMany<BlockedPeriod, $this> */
public function channelRepresentations(): HasMany
{
@@ -197,7 +261,7 @@ public function channelRepresentations(): HasMany
public function bookingChannelLabel(): string
{
return $this->originChannel?->name ?? $this->importChannel?->name ?? match ($this->source) {
return $this->originChannel?->name ?? $this->importChannel?->name ?? match ($this->source ?? 'website') {
'website' => 'Eigene Webseite',
'manual' => 'Manuell / direkt',
'phone' => 'Telefon',
@@ -275,14 +339,17 @@ public function paidAmount(): int
return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount'));
}
/**
* Amount still to be paid in cents; 0 while the price is unknown.
*/
public function openAmount(): int
{
return max(0, $this->total - $this->paidAmount());
return $this->total === null ? 0 : max(0, $this->total - $this->paidAmount());
}
public function openDeposit(): int
{
return max(0, $this->deposit - $this->paidAmount());
return $this->deposit === null ? 0 : max(0, $this->deposit - $this->paidAmount());
}
/**
@@ -290,24 +357,16 @@ public function openDeposit(): int
*/
public function requiresFullPayment(): bool
{
return $this->deposit_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on);
return $this->deposit_due_on !== null && $this->balance_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on);
}
/**
* Whether the landlord chases payments of this booking. Own bookings: always. Portal bookings: as configured
* per channel and kind – a reservation whose payment the portal collects (e.g. instant booking) needs no
* tasks, a mere inquiry passed on by the portal does.
* Whether the landlord chases payments of this case: only when the guest pays us (process profile – a portal that
* collects the money needs no tasks) and the price is known.
*/
public function wantsPaymentTasks(): bool
{
$channel = $this->importChannel ?? $this->originChannel;
if ($channel === null) {
return true;
}
return $channel->booking_model === ChannelBookingModel::PortalBooking
? $channel->payment_tasks_reservation
: $channel->payment_tasks_inquiry;
return $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0;
}
/**
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One entry in the stored history of a case: what happened, who did it, why and when. Entries are only added, never
* changed, so the history stays the same whatever happens to the case later.
*/
#[Fillable(['booking_id', 'type', 'summary', 'actor', 'reason', 'data', 'occurred_at'])]
class BookingEvent extends Model
{
use BelongsToTenant;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'data' => 'array',
'occurred_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Booking, $this>
*/
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
}
+14
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -17,6 +18,19 @@ class BookingMessage extends Model
use BelongsToTenant;
protected static function booted(): void
{
static::created(function (BookingMessage $message): void {
if ($message->booking !== null) {
CaseLog::record($message->booking, 'mail', 'E-Mail '.match ($message->audience) {
'guest' => 'an den Gast',
'landlord' => 'an uns',
default => '(Testbetrieb)',
}.': '.$message->subject, actor: CaseLog::SYSTEM, at: $message->sent_at);
}
});
}
/**
* Get the attributes that should be cast.
*
+15
View File
@@ -5,6 +5,7 @@
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
@@ -20,6 +21,20 @@ class BookingTask extends Model
{
use BelongsToTenant;
protected static function booted(): void
{
static::created(function (BookingTask $task): void {
if ($task->booking !== null) {
CaseLog::record($task->booking, 'task', 'Aufgabe: '.$task->kind->getLabel());
}
});
static::updated(function (BookingTask $task): void {
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);
}
});
}
/**
* Get the attributes that should be cast.
*
+2 -1
View File
@@ -26,7 +26,7 @@
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
* channel and every channel gets its own export feed without its own occupations.
*/
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id'])]
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides'])]
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])]
class Channel extends Model
{
@@ -62,6 +62,7 @@ protected function casts(): array
{
return [
'settings' => 'array',
'process_overrides' => 'array',
'ical_analysis' => 'encrypted:array',
'ical_analyzed_at' => 'immutable_datetime',
'ical_rules' => 'array',
+11
View File
@@ -4,6 +4,8 @@
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
use App\Support\Money;
use Database\Factories\PaymentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -19,6 +21,15 @@ class Payment extends Model
/** @use HasFactory<PaymentFactory> */
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
static::created(function (Payment $payment): void {
if ($payment->booking !== null) {
CaseLog::record($payment->booking, 'payment', ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').Money::format(abs($payment->amount)).' erfasst', data: ['payment_id' => $payment->id]);
}
});
}
/**
* Get the attributes that should be cast.
*
+2
View File
@@ -45,6 +45,7 @@
'min_stay_until_changeover',
'min_stay_absolute',
'is_active',
'process_overrides',
])]
class Property extends Model
{
@@ -82,6 +83,7 @@ protected function casts(): array
'cancellation_mode' => CancellationMode::class,
'free_cancellation_days' => 'integer',
'contract_data' => 'array',
'process_overrides' => 'array',
'min_stay_fill_gaps' => 'boolean',
'min_stay_until_changeover' => 'boolean',
'changeover_weekday' => 'integer',
+2
View File
@@ -28,6 +28,7 @@
'channel_stale_after_minutes', 'channel_task_reminder_after_minutes',
'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections',
'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on',
'process_defaults',
])]
class Tenant extends Model
{
@@ -74,6 +75,7 @@ protected function casts(): array
'digest_weekday' => 'integer',
'digest_hour' => 'integer',
'digest_sections' => 'array',
'process_defaults' => 'array',
'digest_when_empty' => 'boolean',
'digest_daily_sent_on' => 'immutable_date',
'digest_weekly_sent_on' => 'immutable_date',
+21 -48
View File
@@ -7,68 +7,41 @@
use Carbon\CarbonImmutable;
/**
* The price a portal charged for a stay as booking columns. Our own calculation is the basis; the difference to the
* portal price becomes an adjustment line, so the quote adds up to what the portal charged. When our price list does
* not cover the stay (or the stay breaks a rule the portal did not know), the portal price stands alone as one line.
* The price of a booking that was made binding on a portal, as booking columns. The total the guest agreed to on the
* portal is taken over as one line with its source – it is never split into our own price items, and our own price
* list never replaces it (docs/Prozessarchitektur/Querschnitt/Preise_und_Zahlungen.md). An unknown portal price stays
* unknown: no quote, no total, no payment plan.
*/
class PortalPrice
{
public const LABEL = 'Abweichung Portalpreis';
public function __construct(private PriceCalculator $calculator) {}
public const LABEL = 'Gesamtpreis laut Portal';
/**
* @return array<string, mixed> booking columns (quote, total, deposit, price_adjustment, ...)
* @return array{quote: ?array<string, mixed>, total: ?int, deposit: ?int, balance_due_on: ?string, price_adjustment: null, price_adjustment_label: null}
*/
public function columns(Property $property, StayRequest $stay, int $portalTotal): array
public function columns(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, ?int $portalTotal, ?string $channelName = null): array
{
try {
$quote = $this->calculator->calculate($property, $stay);
} catch (QuoteException) {
return $this->columnsOf($this->standalone($property, $stay, $portalTotal), null);
if ($portalTotal === null) {
return ['quote' => null, 'total' => null, 'deposit' => null, 'balance_due_on' => null, 'price_adjustment' => null, 'price_adjustment_label' => null];
}
$difference = max($portalTotal - $quote->total(), -$quote->rent());
if ($difference === 0) {
return $this->columnsOf($quote, null);
}
$label = self::LABEL.($channelName ? ' ('.$channelName.')' : '');
$quote = new PriceQuote(
$arrival,
$departure,
(int) $guests,
[new QuoteLine(QuoteLineType::Accommodation, $label, 1, $portalTotal, $portalTotal)],
$property->deposit_percent,
$arrival->subDays($property->balance_due_days_before_arrival),
);
return $this->columnsOf($quote->withLine(new QuoteLine(QuoteLineType::Adjustment, self::LABEL, 1, $difference, $difference)), $difference);
}
/**
* Quote for a stay without a known portal price: our calculation, or an empty quote when it is not possible.
*
* @return array<string, mixed>
*/
public function unknownColumns(Property $property, StayRequest $stay): array
{
try {
return $this->columnsOf($this->calculator->calculate($property, $stay), null);
} catch (QuoteException) {
return $this->columnsOf($this->standalone($property, $stay, 0), null);
}
}
private function standalone(Property $property, StayRequest $stay, int $total): PriceQuote
{
$lines = $total > 0 ? [new QuoteLine(QuoteLineType::Accommodation, 'Preis laut Portal', 1, $total, $total)] : [];
return new PriceQuote($stay->arrival, $stay->departure, $stay->guests, $lines, $property->deposit_percent, CarbonImmutable::instance($stay->arrival)->subDays($property->balance_due_days_before_arrival));
}
/**
* @return array<string, mixed>
*/
private function columnsOf(PriceQuote $quote, ?int $adjustment): array
{
return [
'quote' => $quote->toArray(),
'quote' => [...$quote->toArray(), 'source' => 'portal'],
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'price_adjustment' => $adjustment,
'price_adjustment_label' => $adjustment !== null ? self::LABEL : null,
'price_adjustment' => null,
'price_adjustment_label' => null,
];
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Process;
use App\Enums\ActivityState;
/**
* One activity of a case as the landlord sees it: what it is, where it stands and – when something is to be done – the
* action on the case page that does it (or a link elsewhere).
*/
final class Activity
{
public function __construct(
public readonly string $key,
public readonly string $label,
public readonly ActivityState $state,
public readonly ?string $detail = null,
public readonly ?string $action = null,
public readonly ?string $url = null,
) {}
}
+204
View File
@@ -0,0 +1,204 @@
<?php
namespace App\Process;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskStatus;
use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\ChannelTask;
use App\Support\Money;
use Carbon\CarbonImmutable;
/**
* The activities of a case derived from its process profile and its data (docs/Prozessarchitektur, P01–P05): which
* apply, which are done (by us or by the portal), what is waiting for somebody else and what the landlord has to do
* next. Nothing here is stored; the gates G1–G5 are these states, not an extra status machine.
*/
class CaseActivities
{
/** Activities that are listed on their own in the work list (they are not "the" next step of a case). */
private const LISTED_SEPARATELY = ['channel_block'];
/**
* @return list<Activity>
*/
public static function for(Booking $booking): array
{
$booking->loadMissing(['guest', 'property', 'payments']);
$profile = $booking->process();
$closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
$binding = $booking->isBinding();
$inquiry = $booking->intake !== IntakeKind::Booking;
$today = CarbonImmutable::today();
$later = fn (ActivityState $state): ActivityState => $closed && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
$activities = [];
$activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel());
$needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
if ($needsContact) {
$hasEmail = filled($booking->guest?->email);
$state = match (true) {
$hasEmail => ActivityState::Done,
$booking->contact_requested_at !== null => ActivityState::Waiting,
default => ActivityState::Open,
};
$activities[] = new Activity('contact', $booking->guest === null ? 'Name und Kontaktdaten des Gastes eintragen' : 'E-Mail-Adresse des Gastes eintragen', $later($state),
$hasEmail ? $booking->guestName() : ($booking->contact_requested_at ? 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlt noch'),
$hasEmail ? null : 'provideContact');
}
if ($inquiry) {
$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) {
$offerDone => ActivityState::Done,
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
default => ActivityState::Later,
}), $booking->offer_version > 0 ? 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y') : ($booking->hold_expires_at ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : null), $offerDone ? null : 'sendOffer');
$activities[] = new Activity('acceptance', 'Gast nimmt das Angebot an', $later(match (true) {
$binding => ActivityState::Done,
$booking->status === BookingStatus::OfferSent => ActivityState::Waiting,
default => ActivityState::Later,
}), match (true) {
$booking->accepted_at !== null => 'angenommen am '.$booking->accepted_at->format('d.m.Y'),
$binding => 'direkt bestätigt',
$booking->status === BookingStatus::OfferSent => 'Angebot gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr',
default => null,
});
} else {
$activities[] = new Activity('binding', 'Beim Portal fest gebucht', $binding || $closed ? ActivityState::External : ActivityState::Open, $booking->portal_reference ? 'Buchungsnummer '.$booking->portal_reference : null, $binding ? null : 'confirm');
$activities[] = new Activity('price', 'Gesamtpreis laut Portal eintragen', $later($booking->total === null ? ActivityState::Open : ActivityState::Done), $booking->total === null ? 'noch nicht bekannt' : Money::format($booking->total), $booking->total === null ? 'portalPrice' : null);
}
if ($profile->documents() === Responsibility::Portal) {
$activities[] = new Activity('documents', 'Buchungsunterlagen an den Gast', ActivityState::External);
} else {
$state = match (true) {
$booking->confirmation_sent_at !== null => ActivityState::Done,
! $binding => ActivityState::Later,
$booking->confirmation_failed_at !== null => ActivityState::Problem,
default => ActivityState::Open,
};
$missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : [];
$activities[] = new Activity('documents', $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden', $later($missing !== [] ? ActivityState::Waiting : $state),
match (true) {
$booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'),
$state === ActivityState::Problem => 'Versand fehlgeschlagen',
$missing !== [] => 'wartet: '.implode(' ', $missing),
default => null,
}, $binding && $missing === [] && $booking->confirmation_sent_at === null ? 'resendConfirmation' : null);
}
foreach (self::channelTasks($booking) as $task) {
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period(), url: ChannelTaskResource::getUrl());
}
if ($profile->payments() === Responsibility::Portal) {
$activities[] = new Activity('payment', 'Zahlung des Gastes', ActivityState::External, 'läuft über das Portal');
} elseif ($booking->total === null) {
$activities[] = new Activity('payment', 'Zahlungen überwachen', $later(ActivityState::Waiting), 'erst möglich, wenn der Preis bekannt ist');
} else {
$paid = $booking->paidAmount();
$activities[] = new Activity('deposit', 'Anzahlung erhalten', $later(match (true) {
$binding && $paid >= (int) $booking->deposit => ActivityState::Done,
$binding => ActivityState::Waiting,
default => ActivityState::Later,
}), Money::format((int) $booking->deposit).($booking->deposit_due_on ? ', fällig '.$booking->deposit_due_on->format('d.m.Y') : ''));
$activities[] = new Activity('balance', 'Restzahlung erhalten', $later(match (true) {
$binding && $paid >= $booking->total => ActivityState::Done,
$binding && $paid >= (int) $booking->deposit => ActivityState::Waiting,
default => ActivityState::Later,
}), 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) {
$activities[] = new Activity('task_'.$task->kind->value, $task->kind->getLabel(), ActivityState::Open, $task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : null, $task->kind->isPayment() ? null : 'end');
}
$arrived = $binding && $booking->arrival <= $today;
$left = $binding && $booking->departure <= $today;
$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 (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) {
$left => ActivityState::Done,
$arrived => ActivityState::Waiting,
default => ActivityState::Later,
}), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
if ($profile->guestMessages() === Responsibility::Landlord) {
$activities[] = new Activity('review', 'Bitte um eine Bewertung (automatisch)', $later($booking->review_requested_at !== null ? ActivityState::Done : ActivityState::Later));
}
return $activities;
}
/**
* What the landlord should do next on this case, or null when nothing is up to him.
*/
public static function next(Booking $booking): ?Activity
{
foreach (self::for($booking) as $activity) {
if ($activity->state->needsAction() && ! in_array($activity->key, self::LISTED_SEPARATELY, true)) {
return $activity;
}
}
return null;
}
/**
* The state of the case in one sentence of plain words.
*/
public static function situation(Booking $booking): string
{
$today = CarbonImmutable::today();
$channel = $booking->processChannel()?->name;
$kind = $booking->intake === IntakeKind::Booking ? 'Gebucht über '.($channel ?? 'ein Portal') : ($channel ? 'Anfrage über '.$channel : ($booking->source === 'website' ? 'Anfrage über die Webseite' : 'Anfrage'));
$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::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::DepositPaid => 'fest gebucht, Anzahlung erhalten',
BookingStatus::Paid => 'fest gebucht, bezahlt',
BookingStatus::Completed => 'abgeschlossen',
BookingStatus::Declined => 'ohne Buchung beendet',
BookingStatus::Expired => 'Frist abgelaufen, ohne Buchung beendet',
BookingStatus::Cancelled => 'storniert',
};
$when = match (true) {
! $booking->isBinding() => null,
$booking->departure <= $today => 'abgereist am '.$booking->departure->format('d.m.Y'),
$booking->arrival <= $today => 'Gast ist vor Ort bis '.$booking->departure->format('d.m.Y'),
default => 'Anreise in '.(int) $today->diffInDays($booking->arrival).' Tagen',
};
return implode(' · ', array_filter([$kind, $state, $when]));
}
/**
* Portal tasks for the dates of this case (block when it starts occupying, unblock when it ends).
*
* @return iterable<ChannelTask>
*/
private static function channelTasks(Booking $booking): iterable
{
return ChannelTask::query()
->with('channel')
->whereHas('channel', fn ($query) => $query->where('property_id', $booking->property_id))
->whereDate('starts_on', $booking->arrival)
->whereDate('ends_on', $booking->departure)
->where('status', '!=', ChannelTaskStatus::Dismissed)
->orderBy('id')
->get();
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Process;
use App\Actions\AutoOffer;
use App\Actions\ConfirmBooking;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Models\Booking;
use Throwable;
/**
* Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a booking that is
* binding on a portal once the guest's e-mail address and the price are known. Whatever stops it is returned in plain
* words; the case then shows it as a task. Never touches a case whose profile was taken over from the old data (the
* automation did not exist for those cases before).
*/
class CaseAutomation
{
public function __construct(private AutoOffer $autoOffer, private ConfirmBooking $confirm) {}
/**
* @return list<string> what keeps the case from going on automatically (empty: nothing to do or done)
*/
public function advance(Booking $booking): array
{
$booking->loadMissing(['guest', 'property']);
if ($booking->processingMode() !== ProcessingMode::Automatic) {
return [];
}
try {
return CaseLog::context(fn (): array => $this->step($booking), actor: CaseLog::SYSTEM.' (automatisch)');
} catch (Throwable $exception) {
report($exception);
return ['Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.'];
}
}
/**
* @return list<string>
*/
private function step(Booking $booking): array
{
if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->intake !== IntakeKind::Booking) {
return $this->autoOffer->handle($booking);
}
if ($booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord && $booking->process()->origin !== 'migration') {
$missing = $this->documentBlockers($booking);
if ($missing !== []) {
return $missing;
}
return $this->confirm->deliver($booking) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
}
return [];
}
/**
* What is missing before the documents of a binding case can go to the guest.
*
* @return list<string>
*/
public function documentBlockers(Booking $booking): array
{
return array_values(array_filter([
$booking->guest === null ? 'Name und Kontaktdaten des Gastes fehlen.' : null,
$booking->guest !== null && blank($booking->guest->email) ? 'Die E-Mail-Adresse des Gastes fehlt.' : null,
$booking->total === null ? 'Der Gesamtpreis (laut Portal) fehlt.' : null,
]));
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Process;
use App\Models\Booking;
use App\Models\BookingEvent;
use Carbon\CarbonInterface;
/**
* Writes the stored history of a case. Model hooks record the facts (status, documents, payments, mails); actions
* that know more (who acted on whose behalf, and why) wrap their work in {@see self::context()}.
*/
class CaseLog
{
public const SYSTEM = 'System';
public const GUEST = 'Gast';
private static ?string $actor = null;
private static ?string $reason = null;
/**
* Runs the callback with a named actor and/or reason for every entry written meanwhile.
*
* @template T
*
* @param callable(): T $callback
* @return T
*/
public static function context(callable $callback, ?string $actor = null, ?string $reason = null): mixed
{
[$previousActor, $previousReason] = [self::$actor, self::$reason];
self::$actor = $actor ?? $previousActor;
self::$reason = $reason ?? $previousReason;
try {
return $callback();
} finally {
[self::$actor, self::$reason] = [$previousActor, $previousReason];
}
}
/**
* @param array<string, mixed> $data
*/
public static function record(Booking $booking, string $type, string $summary, ?string $reason = null, array $data = [], ?string $actor = null, ?CarbonInterface $at = null): BookingEvent
{
$event = new BookingEvent([
'booking_id' => $booking->id,
'type' => $type,
'summary' => mb_substr($summary, 0, 500),
'actor' => $actor ?? self::actor(),
'reason' => $reason ?? self::$reason,
'data' => $data === [] ? null : $data,
'occurred_at' => $at ?? now(),
]);
$event->tenant_id = $booking->tenant_id;
$event->save();
return $event;
}
/**
* Who is acting right now: the named actor, the signed-in user or the system (scheduler, mail import).
*/
public static function actor(): string
{
return self::$actor ?? auth()->user()?->name ?? self::SYSTEM;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Process;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\Guest;
/**
* Model hooks of a case: freezes the process profile when the case comes in (and again when what defines it – intake
* kind, channel, property – changes) and writes the facts of every change into the stored history.
*/
class CaseRecorder
{
/** Attributes that decide which profile applies; changing one re-freezes the profile. */
private const DEFINING = ['intake', 'origin_channel_id', 'import_channel_id', 'property_id'];
public static function freeze(Booking $booking): void
{
if ($booking->isDirty('profile') && filled($booking->profile)) {
return;
}
$changed = $booking->exists && $booking->isDirty(self::DEFINING);
if (filled($booking->profile) && ! $changed) {
return;
}
$booking->intake ??= ProcessSettings::intakeFor($booking);
$profile = app(ProcessSettings::class)->forBooking($booking)->withOrigin($booking->exists ? 'changed' : 'intake');
$booking->profile = $profile->toArray();
$booking->case_type = $profile->caseType;
}
public static function created(Booking $booking): void
{
CaseLog::record($booking, 'created', 'Vorgang angelegt: '.$booking->caseType()->getLabel().' ('.$booking->bookingChannelLabel().')', data: [
'intake' => $booking->intake?->value,
'case_type' => $booking->case_type?->value,
]);
}
public static function updated(Booking $booking): void
{
$changes = $booking->getChanges();
$original = fn (string $key): mixed => $booking->getOriginal($key);
if (array_key_exists('profile', $changes) && $booking->wasChanged(self::DEFINING)) {
CaseLog::record($booking, 'profile', 'Abwicklung neu bestimmt: '.$booking->caseType()->getLabel());
}
if (array_key_exists('guest_id', $changes) && $booking->guest_id !== null) {
CaseLog::record($booking, 'guest', 'Gast zugeordnet: '.(Guest::query()->find($booking->guest_id)?->full_name ?? '–'));
}
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' : ''));
} 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)) {
CaseLog::record($booking, 'hold', 'Reservierung verlängert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr');
}
if (array_key_exists('status', $changes) && $original('status') !== $booking->status && ! ($booking->status === BookingStatus::OfferSent && array_key_exists('offer_version', $changes))) {
CaseLog::record($booking, 'status', self::statusSummary($booking, $original('status')), data: [
'from' => $original('status') instanceof BookingStatus ? $original('status')->value : $original('status'),
'to' => $booking->status->value,
]);
}
if (array_key_exists('arrival', $changes) || array_key_exists('departure', $changes)) {
CaseLog::record($booking, 'dates', 'Zeitraum: '.$booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
}
$facts = [
'contact_requested_at' => 'Gast um Kontaktdaten gebeten',
'guest_confirmed_at' => 'Gast hat die Buchung per E-Mail bestätigt',
'confirmation_sent_at' => 'Bestätigung mit Unterlagen an den Gast gesendet',
'confirmation_failed_at' => 'Versand der Bestätigung fehlgeschlagen',
'arrival_info_sent_at' => 'Anreise-Informationen gesendet',
'review_requested_at' => 'Gast um eine Bewertung gebeten',
];
foreach ($facts as $column => $summary) {
if (array_key_exists($column, $changes) && $booking->{$column} !== null) {
CaseLog::record($booking, 'fact', $summary);
}
}
if (array_key_exists('processing_mode', $changes)) {
CaseLog::record($booking, 'mode', 'Bearbeitung dieses Vorgangs: '.($booking->processing_mode?->getLabel() ?? 'wie eingestellt ('.$booking->process()->processing()->getLabel().')'));
}
if (array_key_exists('archived_at', $changes)) {
CaseLog::record($booking, 'archive', $booking->archived_at ? 'Archiviert' : 'Aus dem Archiv geholt');
}
}
private static function statusSummary(Booking $booking, mixed $from): string
{
$from = $from instanceof BookingStatus ? $from : BookingStatus::tryFrom((string) $from);
return match ($booking->status) {
BookingStatus::Confirmed => $booking->wasChanged('accepted_at') && $booking->accepted_at !== null
? 'Angebot vom Gast angenommen – Buchung verbindlich'
: ($booking->caseType()->isExternallyBinding() ? 'Beim Portal verbindlich gebucht – übernommen' : 'Buchung verbindlich bestätigt'),
BookingStatus::DepositPaid => 'Anzahlung eingegangen',
BookingStatus::Paid => 'Vollständig bezahlt',
BookingStatus::Completed => 'Aufenthalt abgeschlossen',
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::Cancelled => 'Storniert',
BookingStatus::Reserved => $from === null ? 'Anfrage vorgemerkt' : 'Wieder als Anfrage geführt (vorher: '.$from->getLabel().')',
BookingStatus::OfferSent => 'Angebot liegt beim Gast',
};
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace App\Process;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
/**
* The rules that apply to one case: its intake kind, case type and the effective value of every process setting
* together with the level it came from. Frozen on the case when it comes in, so later changes of the settings only
* affect new cases.
*/
final class ProcessProfile
{
public const SYSTEM = 'system';
public const TENANT = 'tenant';
public const PROPERTY = 'property';
public const CHANNEL = 'channel';
/** Settings resolved when they are used instead of being frozen (documents capture their own template). */
public const LIVE = [ProcessSetting::ContractTemplate];
/**
* @param array<string, string|int|bool|null> $values setting key => effective value
* @param array<string, string> $sources setting key => level the value came from
*/
public function __construct(
public readonly IntakeKind $intake,
public readonly CaseType $caseType,
public readonly array $values,
public readonly array $sources,
public readonly ?string $frozenAt = null,
public readonly string $origin = 'intake',
) {}
/**
* The case type of a constellation: internal occasions are A6; requests are A1 (own way) or A2 (intermediary);
* binding external bookings are A3–A5 by who handles documents and payments.
*/
public static function caseTypeFor(IntakeKind $intake, bool $viaChannel, Responsibility $documents, Responsibility $payments): CaseType
{
return match ($intake) {
IntakeKind::Internal => CaseType::A6,
IntakeKind::Inquiry => $viaChannel ? CaseType::A2 : CaseType::A1,
IntakeKind::Booking => match (true) {
$documents === Responsibility::Portal => CaseType::A5,
$payments === Responsibility::Portal => CaseType::A4,
default => CaseType::A3,
},
};
}
public function value(ProcessSetting $setting): string|int|bool|null
{
return array_key_exists($setting->value, $this->values) ? $this->values[$setting->value] : $setting->default();
}
public function source(ProcessSetting $setting): string
{
return $this->sources[$setting->value] ?? self::SYSTEM;
}
public function processing(): ProcessingMode
{
return ProcessingMode::tryFrom((string) $this->value(ProcessSetting::Processing)) ?? ProcessingMode::Manual;
}
public function preReservation(): bool
{
return (bool) $this->value(ProcessSetting::PreReservation);
}
public function holdHours(): int
{
return max(1, (int) $this->value(ProcessSetting::HoldHours));
}
public function documents(): Responsibility
{
return Responsibility::tryFrom((string) $this->value(ProcessSetting::Documents)) ?? Responsibility::Landlord;
}
public function payments(): Responsibility
{
return Responsibility::tryFrom((string) $this->value(ProcessSetting::Payments)) ?? Responsibility::Landlord;
}
public function guestMessages(): Responsibility
{
return Responsibility::tryFrom((string) $this->value(ProcessSetting::GuestMessages)) ?? Responsibility::Landlord;
}
public function arrivalInfoDaysBefore(): int
{
return max(1, (int) $this->value(ProcessSetting::ArrivalInfoDaysBefore));
}
public function contractTemplateId(): ?int
{
$value = $this->value(ProcessSetting::ContractTemplate);
return $value === null ? null : (int) $value;
}
/**
* Plain words for a level, for the "where does this come from" hint.
*/
public static function sourceLabel(string $source): string
{
return match ($source) {
self::TENANT => 'Ihre Standardeinstellung',
self::PROPERTY => 'Abweichung der Wohnung',
self::CHANNEL => 'Abweichung des Portals',
'migration' => 'aus dem bisherigen Stand übernommen',
default => 'Grundeinstellung',
};
}
/**
* The profile as it is frozen on the case (settings resolved live are left out).
*
* @return array{intake: string, case_type: string, values: array<string, string|int|bool|null>, sources: array<string, string>, frozen_at: string, origin: string}
*/
public function toArray(): array
{
$live = array_flip(array_map(fn (ProcessSetting $setting): string => $setting->value, self::LIVE));
return [
'intake' => $this->intake->value,
'case_type' => $this->caseType->value,
'values' => array_diff_key($this->values, $live),
'sources' => array_diff_key($this->sources, $live),
'frozen_at' => $this->frozenAt ?? now()->toIso8601String(),
'origin' => $this->origin,
];
}
/**
* @param array<string, mixed> $data
*/
public static function fromArray(array $data): self
{
return new self(
IntakeKind::tryFrom((string) ($data['intake'] ?? '')) ?? IntakeKind::Inquiry,
CaseType::tryFrom((string) ($data['case_type'] ?? '')) ?? CaseType::A1,
(array) ($data['values'] ?? []),
(array) ($data['sources'] ?? []),
isset($data['frozen_at']) ? (string) $data['frozen_at'] : null,
(string) ($data['origin'] ?? 'intake'),
);
}
public function withOrigin(string $origin): self
{
return new self($this->intake, $this->caseType, $this->values, $this->sources, $this->frozenAt, $origin);
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Process;
use App\Enums\ChannelBookingModel;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
/**
* Resolves the effective process settings: built-in default → landlord default (tenant) → deviation of the property
* (expert area) → deviation of the channel for the intake kind. A value that is not set inherits from the level above;
* a deliberately set 0, "no" or "manual" is a value of its own.
*/
class ProcessSettings
{
public function resolve(Property $property, ?Channel $channel, IntakeKind $intake): ProcessProfile
{
$propertyLevel = (array) ($property->process_overrides ?? []);
if ($property->contract_template_id !== null) {
$propertyLevel[ProcessSetting::ContractTemplate->value] = $property->contract_template_id;
}
$levels = [
ProcessProfile::TENANT => $this->tenantDefaults($property->tenant_id),
ProcessProfile::PROPERTY => $propertyLevel,
ProcessProfile::CHANNEL => $intake === IntakeKind::Internal || $channel === null ? [] : (array) (($channel->process_overrides ?? [])[$intake->value] ?? []),
];
$values = [];
$sources = [];
foreach (ProcessSetting::cases() as $setting) {
$values[$setting->value] = $setting->default();
$sources[$setting->value] = ProcessProfile::SYSTEM;
foreach ($levels as $level => $settings) {
if ($level === ProcessProfile::CHANNEL && ! in_array($intake, $setting->channelIntakes(), true)) {
continue;
}
$value = $setting->normalize($settings[$setting->value] ?? null);
if ($value !== null) {
$values[$setting->value] = $value;
$sources[$setting->value] = $level;
}
}
}
if ($intake !== IntakeKind::Booking) {
// A request is answered with our own offer and an internal case is ours anyway: the documents are ours.
$values[ProcessSetting::Documents->value] = Responsibility::Landlord->value;
$sources[ProcessSetting::Documents->value] = ProcessProfile::SYSTEM;
}
$documents = Responsibility::from((string) $values[ProcessSetting::Documents->value]);
$payments = Responsibility::from((string) $values[ProcessSetting::Payments->value]);
return new ProcessProfile($intake, ProcessProfile::caseTypeFor($intake, $channel !== null, $documents, $payments), $values, $sources);
}
/**
* The settings that would apply to a case right now (its frozen profile is what counts for the case itself).
*/
public function forBooking(Booking $booking): ProcessProfile
{
// The case's own landlord counts, whichever landlord is current (e.g. a case written by the system).
$property = $booking->property ?? Property::withoutGlobalScope('tenant')->findOrFail($booking->property_id);
return $this->resolve($property, $booking->processChannel(), $booking->intake ?? self::intakeFor($booking));
}
/**
* Landlord defaults as stored on the tenant (not set: empty).
*
* @return array<string, mixed>
*/
public function tenantDefaults(?int $tenantId): array
{
if ($tenantId === null) {
return [];
}
return (array) (Tenant::query()->find($tenantId)?->process_defaults ?? []);
}
/**
* Intake kind of a case that does not name one: a case from a channel that only passes on requests is a request,
* from other channels a booking that is already binding; everything else (website, phone, e-mail) a request.
*/
public static function intakeFor(Booking $booking): IntakeKind
{
$channel = $booking->processChannel();
if ($channel === null) {
return IntakeKind::Inquiry;
}
return $channel->booking_model === ChannelBookingModel::Inquiry ? IntakeKind::Inquiry : IntakeKind::Booking;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace App\Process;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\ChannelTaskAction;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Filament\Resources\InboxMessages\InboxMessageResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\ChannelTask;
use App\Models\InboxMessage;
/**
* "Zu erledigen": everything the landlord has to do, in one list – the next step of every open case, portals to block
* or release, calendar entries nobody knows yet and system notices that need a decision. Each entry names the thing in
* plain words and leads to the one place where it is done.
*/
class WorkList
{
/**
* @return list<array{title: string, detail: ?string, url: string, button: string, tone: string, sort: string}>
*/
public static function items(): array
{
$items = [];
$cases = Booking::query()
->with(['guest', 'property', 'payments', 'importChannel', 'originChannel'])
->whereNull('archived_at')
->whereNotIn('status', [BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed])
->where(fn ($query) => $query->whereNot('status', BookingStatus::Cancelled)->orWhereHas('tasks', fn ($tasks) => $tasks->where('status', 'open')))
->get();
foreach ($cases as $case) {
$next = CaseActivities::next($case);
if ($next === null) {
continue;
}
$items[] = [
'title' => $next->label,
'detail' => $case->guestName().' · '.$case->arrival->format('d.m.').'–'.$case->departure->format('d.m.Y').' · '.$case->property->name.($next->detail ? ' · '.$next->detail : ''),
'url' => BookingResource::getUrl('view', ['record' => $case]),
'button' => 'Vorgang öffnen',
'tone' => $next->state === ActivityState::Problem ? 'danger' : 'warning',
'sort' => ($next->state === ActivityState::Problem ? '0' : '1').$case->arrival->format('Ymd'),
];
}
foreach (ChannelTask::query()->open()->with('channel.property')->orderBy('starts_on')->get() as $task) {
$items[] = [
'title' => ($task->action === ChannelTaskAction::Block ? 'In '.$task->channel?->name.' sperren' : 'In '.$task->channel?->name.' wieder freigeben'),
'detail' => $task->period().' · '.$task->channel?->property?->name.' · '.$task->reason,
'url' => ChannelTaskResource::getUrl(),
'button' => 'Erledigen',
'tone' => 'danger',
'sort' => '0'.$task->starts_on->format('Ymd'),
];
}
foreach (BlockedPeriod::query()->unclear()->with(['channel', 'property'])->whereDate('ends_on', '>=', today())->orderBy('starts_on')->get() as $occupation) {
$items[] = [
'title' => 'Unbekannte Belegung von '.($occupation->channel?->name ?? 'einem Portal').' – was ist das?',
'detail' => $occupation->starts_on->format('d.m.').'–'.$occupation->ends_on->format('d.m.Y').' · '.$occupation->property?->name,
'url' => PortalOccupationResource::getUrl('view', ['record' => $occupation]),
'button' => 'Klären',
'tone' => 'warning',
'sort' => '1'.$occupation->starts_on->format('Ymd'),
];
}
foreach (InboxMessage::query()->whereNull('read_at')->latest()->get() as $message) {
$items[] = [
'title' => $message->subject,
'detail' => str($message->body)->limit(160)->toString(),
'url' => $message->action_url ?: InboxMessageResource::getUrl(),
'button' => 'Ansehen',
'tone' => 'info',
'sort' => '2'.$message->created_at?->format('YmdHis'),
];
}
usort($items, fn (array $a, array $b): int => strcmp($a['sort'], $b['sort']));
return $items;
}
}
@@ -3,6 +3,7 @@
namespace App\Providers\Filament;
use App\Enums\AdminMode;
use App\Filament\Pages\Dashboard;
use App\Http\Controllers\SwitchPropertyController;
use App\Http\Middleware\ResolveTheme;
use App\Models\User;
@@ -13,7 +14,6 @@
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
-212
View File
@@ -1,212 +0,0 @@
<?php
namespace App\Support;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChannelBookingModel;
use App\Models\Booking;
use App\Models\BookingMessage;
use App\Models\BookingTask;
use App\Models\Cancellation;
use Carbon\CarbonImmutable;
/**
* One view on where a booking stands: what kind of process it is, the steps with their state and the next
* thing the landlord has to do. Everything is derived from the booking, nothing is stored.
*/
class BookingProgress
{
public const OWN = 'own';
public const MANUAL = 'manual';
public const PORTAL_BOOKING = 'portal_booking';
public const PORTAL_INQUIRY = 'portal_inquiry';
public static function kind(Booking $booking): string
{
$channel = $booking->importChannel ?? $booking->originChannel;
if ($channel !== null) {
return $channel->booking_model === ChannelBookingModel::PortalBooking ? self::PORTAL_BOOKING : self::PORTAL_INQUIRY;
}
return $booking->source === 'website' ? self::OWN : self::MANUAL;
}
public static function kindLabel(Booking $booking): string
{
$portal = ($booking->importChannel ?? $booking->originChannel)?->name;
return match (self::kind($booking)) {
self::OWN => 'Eigene Webseite: Anfrage → Angebot → Annahme',
self::MANUAL => 'Manuell erfasste Buchung',
self::PORTAL_BOOKING => 'Portal-Buchung'.($portal ? " ({$portal})" : '').': beim Portal verbindlich, Vertrag von uns',
default => 'Portal-Anfrage'.($portal ? " ({$portal})" : '').': wir antworten persönlich, Angebot und Vertrag von uns',
};
}
/**
* The milestones of the process with the activities that belong to each. An activity names the action on the
* booking page that does it ("action"), so the landlord sees what was done, what is open and where to do it.
*
* @return list<array{label: string, state: string, detail: ?string, activities: list<array{label: string, done: bool, action: ?string}>}>
*/
public static function steps(Booking $booking): array
{
$today = CarbonImmutable::today();
$kind = self::kind($booking);
$closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true);
$binding = in_array($booking->status, BookingStatus::occupying(), true);
$hasEmail = filled($booking->guest?->email);
$activity = fn (string $label, bool $done, ?string $action = null): array => ['label' => $label, 'done' => $done, 'action' => $done ? null : $action];
$steps = [];
$steps[] = ['label' => 'Anfrage / Eingang', 'state' => 'done', 'detail' => $booking->created_at?->format('d.m.Y'), 'activities' => [
$activity($kind === self::OWN ? 'Anfrage über die Webseite eingegangen' : 'Vorgang angelegt ('.$booking->bookingChannelLabel().')', true),
]];
if (in_array($kind, [self::PORTAL_BOOKING, self::PORTAL_INQUIRY], true)) {
$asked = $booking->contact_requested_at !== null;
$steps[] = ['label' => 'Gast & Kontaktdaten', 'state' => $hasEmail ? 'done' : ($closed ? 'skipped' : 'current'), 'detail' => $hasEmail ? null : ($asked ? 'erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlen noch'), 'activities' => [
$activity('Gast um Kontaktdaten bitten', $hasEmail || $asked, 'Gast um Kontaktdaten bitten'),
$activity('Kontaktdaten eintragen (Name, E-Mail, Anschrift)', $hasEmail, 'Kontaktdaten eintragen'),
]];
}
$needsOffer = in_array($kind, [self::OWN, self::PORTAL_INQUIRY, self::MANUAL], true);
if ($needsOffer) {
$steps[] = [
'label' => 'Angebot',
'state' => $booking->offer_version > 0 || $binding ? 'done' : ($closed ? 'skipped' : 'current'),
'detail' => $booking->offer_version > 0 ? 'Version '.$booking->offer_version.', '.$booking->offer_sent_at?->format('d.m.Y') : null,
'activities' => [$activity('Angebot mit Vertragsentwurf an den Gast senden', $booking->offer_version > 0 || $binding, 'Angebot senden')],
];
}
$steps[] = [
'label' => $needsOffer ? 'Annahme / Vertrag' : 'Bestätigung / Vertrag',
'state' => $binding ? ($booking->confirmation_sent_at !== null || $booking->accepted_at !== null || $needsOffer ? 'done' : 'current') : ($closed ? 'skipped' : ($booking->status === BookingStatus::OfferSent ? 'current' : 'todo')),
'detail' => $booking->accepted_at ? 'angenommen '.$booking->accepted_at->format('d.m.Y') : ($booking->confirmation_sent_at ? 'Vertrag gesendet '.$booking->confirmation_sent_at->format('d.m.Y') : null),
'activities' => array_values(array_filter([
$needsOffer ? $activity('Gast nimmt das Angebot an (oder Buchung direkt bestätigen)', $binding, 'Direkt bestätigen') : $activity('Buchung bestätigen (Zeitraum fest belegen)', $binding, 'Direkt bestätigen'),
$activity('Mietvertrag mit Anlagen an den Gast senden', $booking->confirmation_sent_at !== null, $binding ? 'Bestätigung erneut senden' : null),
$booking->guest_confirmed_at ? $activity('Gast hat die Buchung per E-Mail bestätigt', true) : null,
])),
];
if ($booking->wantsPaymentTasks()) {
$paid = $booking->paidAmount();
$steps[] = ['label' => 'Anzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->deposit && $binding ? 'done' : ($binding ? 'current' : 'todo')), 'detail' => $booking->deposit_due_on ? 'fällig '.$booking->deposit_due_on->format('d.m.Y') : null, 'activities' => [
$activity('Zahlungseingang erfassen', $paid >= $booking->deposit && $binding, 'Zahlungen (unten)'),
]];
$steps[] = ['label' => 'Restzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->total && $binding ? 'done' : ($binding && $paid >= $booking->deposit ? 'current' : 'todo')), 'detail' => 'fällig '.$booking->balance_due_on?->format('d.m.Y'), 'activities' => [
$activity('Restzahlung erfassen', $paid >= $booking->total && $binding, 'Zahlungen (unten)'),
]];
} else {
$steps[] = ['label' => 'Zahlung', 'state' => 'skipped', 'detail' => 'läuft über das Portal', 'activities' => []];
}
$arrived = ! $closed && $binding && $booking->arrival <= $today;
$left = ! $closed && $binding && $booking->departure <= $today;
$steps[] = ['label' => 'Anreise', 'state' => $closed ? 'skipped' : ($arrived ? 'done' : 'todo'), 'detail' => $booking->arrival->format('d.m.Y'), 'activities' => [
$activity('Anreise-Informationen ('.$booking->property->arrival_info_days_before.' Tage vorher, automatisch)', $booking->arrival_info_sent_at !== null),
]];
$steps[] = ['label' => 'Vor Ort', 'state' => $closed ? 'skipped' : ($arrived && ! $left ? 'current' : ($left ? 'done' : 'todo')), 'detail' => null, 'activities' => []];
$steps[] = ['label' => 'Abreise', 'state' => $closed ? 'skipped' : ($left ? 'done' : 'todo'), 'detail' => $booking->departure->format('d.m.Y'), 'activities' => []];
return $steps;
}
/**
* What has happened so far, oldest first: milestones from the booking's own timestamps, payments and mails.
*
* @return list<array{at: CarbonImmutable, label: string}>
*/
public static function history(Booking $booking): array
{
$events = [];
$add = function (mixed $at, string $label) use (&$events): void {
if ($at !== null) {
$events[] = ['at' => CarbonImmutable::instance($at), 'label' => $label];
}
};
$add($booking->created_at, 'Vorgang angelegt ('.$booking->bookingChannelLabel().')');
$add($booking->contact_requested_at, 'Gast um Kontaktdaten gebeten');
$add($booking->offer_sent_at, 'Angebot Version '.$booking->offer_version.' gesendet');
$add($booking->accepted_at, 'Angebot vom Gast angenommen');
$add($booking->guest_confirmed_at, 'Gast hat die Buchung per E-Mail bestätigt');
$add($booking->confirmed_at, 'Buchung verbindlich bestätigt');
$add($booking->confirmation_sent_at, 'Bestätigung mit Mietvertrag an den Gast gesendet');
$add($booking->confirmation_failed_at, 'Versand der Bestätigung fehlgeschlagen');
$add($booking->arrival_info_sent_at, 'Anreise-Informationen gesendet');
$add($booking->cancelled_at, 'Storniert');
$add($booking->archived_at, 'Archiviert');
foreach ($booking->payments()->get() as $payment) {
$add($payment->paid_on ?? $payment->created_at, ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').Money::format(abs($payment->amount)).' erfasst');
}
foreach (BookingMessage::query()->where('booking_id', $booking->id)->get() as $message) {
$add($message->sent_at, 'E-Mail: '.$message->subject.' ('.$message->audience.')');
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Done)->get() as $task) {
$add($task->completed_at, 'Aufgabe erledigt: '.$task->kind->getLabel());
}
usort($events, fn (array $a, array $b): int => $a['at'] <=> $b['at']);
return $events;
}
private static function cancelledText(Booking $booking, bool $open): string
{
$cancellation = Cancellation::query()->where('booking_id', $booking->id)->first();
if ($cancellation === null) {
return $open ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.';
}
$balance = $cancellation->balance();
$text = 'Storniert am '.$cancellation->cancelled_on->format('d.m.Y').' ('.($cancellation->days_before ?? '?').' Tage vor Anreise). Stornokosten '.Money::format($cancellation->fee()).', bezahlt '.Money::format($cancellation->paid_amount).'.';
return $text.($cancellation->status === Cancellation::OPEN ? ($balance > 0 ? ' Noch einzufordern: '.Money::format($balance).'.' : ($balance < 0 ? ' Zu erstatten: '.Money::format(-$balance).'.' : ' Ausgeglichen – bitte als abgerechnet markieren.')) : ' Erledigt.');
}
/**
* @return array{title: string, text: string, color: string}
*/
public static function next(Booking $booking): array
{
$today = CarbonImmutable::today();
$kind = self::kind($booking);
$money = fn (int $cents): string => Money::format($cents);
$openTasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get();
$costs = $openTasks->firstWhere('kind', BookingTaskKind::CancellationFee);
$wish = $openTasks->firstWhere('kind', BookingTaskKind::CancellationRequest);
if ($wish !== null && $booking->status !== BookingStatus::Cancelled) {
return ['title' => 'Stornierungswunsch des Gastes', 'text' => 'Der Gast möchte stornieren. Bitte prüfen: stornieren (mit Mail an den Gast) oder ablehnen, und Stornokosten klären.', 'color' => 'danger'];
}
return match (true) {
$booking->status === BookingStatus::Cancelled => ['title' => 'Storniert', 'text' => self::cancelledText($booking, $costs !== null || $wish !== null), 'color' => $costs !== null ? 'warning' : 'gray'],
$booking->status === BookingStatus::Declined => ['title' => 'Abgelehnt', 'text' => 'Der Zeitraum ist wieder frei.', 'color' => 'gray'],
$booking->status === BookingStatus::Expired => ['title' => 'Abgelaufen', 'text' => 'Die Haltefrist ist verstrichen. Sie können die Anfrage trotzdem noch bestätigen, solange der Zeitraum frei ist.', 'color' => 'gray'],
blank($booking->guest?->email) && $booking->departure > $today => ['title' => 'Kontaktdaten fehlen', 'text' => ($booking->contact_requested_at ? 'Die Kontaktdaten wurden am '.$booking->contact_requested_at->format('d.m.Y').' erfragt – Antwort abwarten. ' : 'Den Gast um Kontaktdaten bitten („Gast um Kontaktdaten bitten“). ').'Sobald sie da sind: „Kontaktdaten eintragen“ – dort lässt sich der Vertragsprozess automatisch starten oder von Hand weiterführen.', 'color' => 'warning'],
$booking->status === BookingStatus::Reserved => ['title' => 'Anfrage prüfen', 'text' => $kind === self::PORTAL_BOOKING
? 'Kontaktdaten des Gastes eintragen, dann „Direkt bestätigen“ – der Vertrag geht per E-Mail an den Gast.'
: 'Angebot senden („Angebot senden“) oder ablehnen.'.($booking->hold_expires_at ? ' Vorgemerkt bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr.' : ' Es ist kein Zeitraum vorgemerkt.'), 'color' => 'warning'],
$booking->status === BookingStatus::OfferSent => ['title' => 'Wartet auf den Gast', 'text' => 'Angebot Version '.$booking->offer_version.' ist beim Gast. Gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr.', 'color' => 'info'],
$booking->confirmation_failed_at !== null && $booking->confirmation_sent_at === null => ['title' => 'Bestätigung nicht zugestellt', 'text' => 'Die Buchung steht, aber die Bestätigungs-E-Mail ist nicht beim Gast angekommen. „Bestätigung erneut senden“.', 'color' => 'danger'],
$kind === self::PORTAL_BOOKING && $booking->confirmation_sent_at === null && $booking->contract_path === null => ['title' => 'Vertrag senden', 'text' => 'Die Buchung ist beim Portal verbindlich. Bitte den Vertrag an den Gast senden (Bestätigung erneut senden).', 'color' => 'warning'],
$booking->wantsPaymentTasks() && $booking->openDeposit() > 0 && $booking->status === BookingStatus::Confirmed => ['title' => 'Anzahlung offen', 'text' => $money($booking->openDeposit()).' fällig bis '.$booking->deposit_due_on?->format('d.m.Y').'. Zahlungseingang unter „Zahlungen“ erfassen.', 'color' => $booking->deposit_due_on?->isPast() ? 'danger' : 'warning'],
$booking->wantsPaymentTasks() && $booking->openAmount() > 0 && $booking->balance_due_on?->lessThanOrEqualTo($today->addDays(14)) => ['title' => 'Restzahlung offen', 'text' => $money($booking->openAmount()).' fällig bis '.$booking->balance_due_on->format('d.m.Y').'.', 'color' => $booking->balance_due_on->isPast() ? 'danger' : 'warning'],
$booking->arrival <= $today && $booking->departure > $today => ['title' => 'Gast ist vor Ort', 'text' => 'Abreise am '.$booking->departure->format('d.m.Y').'.', 'color' => 'success'],
$booking->arrival > $today => ['title' => 'Anreise in '.$today->diffInDays($booking->arrival).' Tagen', 'text' => 'Anreise am '.$booking->arrival->format('d.m.Y').'. Anreise-Informationen gehen '.$booking->property->arrival_info_days_before.' Tage vorher automatisch an den Gast.', 'color' => 'success'],
default => ['title' => 'Aufenthalt beendet', 'text' => 'Abreise war am '.$booking->departure->format('d.m.Y').'.', 'color' => 'gray'],
};
}
}
@@ -0,0 +1,80 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* The booking becomes the one "case" (Vorgang) of every business occasion (docs/Prozessarchitektur, package 1 of
* UMSETZUNGSPLAN_v0.10): unknown guest, number of guests and amounts are allowed, every case knows its intake kind,
* its case type and the process profile frozen when it came in, and its history is stored as events. Settings get
* three levels: landlord defaults (tenant), optional deviations of a property (expert area) and of a channel per
* intake kind. Purely additive – nothing existing is removed here.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('bookings', function (Blueprint $table): void {
$table->foreignId('guest_id')->nullable()->change();
$table->unsignedTinyInteger('guests')->nullable()->change();
$table->json('quote')->nullable()->change();
$table->unsignedInteger('total')->nullable()->change();
$table->unsignedInteger('deposit')->nullable()->change();
$table->date('balance_due_on')->nullable()->change();
$table->string('intake', 12)->nullable()->after('source');
$table->string('case_type', 4)->nullable()->index()->after('intake');
$table->json('profile')->nullable()->after('case_type');
$table->string('processing_mode', 12)->nullable()->after('profile');
});
Schema::table('tenants', function (Blueprint $table): void {
$table->json('process_defaults')->nullable();
});
Schema::table('properties', function (Blueprint $table): void {
$table->json('process_overrides')->nullable();
});
Schema::table('channels', function (Blueprint $table): void {
$table->json('process_overrides')->nullable();
});
Schema::create('booking_events', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('type', 30);
$table->string('summary', 500);
$table->string('actor', 120)->nullable();
$table->text('reason')->nullable();
$table->json('data')->nullable();
$table->timestamp('occurred_at');
$table->timestamps();
$table->index(['booking_id', 'occurred_at']);
});
}
public function down(): void
{
Schema::dropIfExists('booking_events');
Schema::table('channels', function (Blueprint $table): void {
$table->dropColumn('process_overrides');
});
Schema::table('properties', function (Blueprint $table): void {
$table->dropColumn('process_overrides');
});
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn('process_defaults');
});
Schema::table('bookings', function (Blueprint $table): void {
$table->dropIndex(['case_type']);
$table->dropColumn(['intake', 'case_type', 'profile', 'processing_mode']);
});
}
};
@@ -0,0 +1,213 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
/**
* Carries the existing data over to the case core without changing behaviour:
*
* 1. Process settings of the properties (handling mode, pre-reservation, hold, arrival info) become landlord defaults
* where all properties of a landlord agree. Where they differ, nothing is unified: the landlord default stays the
* built-in default and every property keeps its own value as a deviation (expert area). Report:
* `php artisan process:settings-report`.
* 2. Channel switches (payment tasks per booking model, contract templates) become channel deviations per intake kind.
* 3. Every existing case gets intake kind, case type and a profile frozen with exactly the values the old code used
* for it (origin "migration").
* 4. The history so far is written from the timestamps, payments, mails and finished tasks.
* 5. Placeholder guests ("Gast (Portal)", no e-mail) are detached; unknown guests stay unknown.
*
* Only plain queries – no models, so later model changes cannot alter what this migration did.
*/
return new class extends Migration
{
/** Old property column => setting key. */
private const PROPERTY_SETTINGS = [
'offer_mode' => 'processing',
'pre_reservation_enabled' => 'pre_reservation',
'hold_hours' => 'hold_hours',
'arrival_info_days_before' => 'arrival_info_days_before',
];
public function up(): void
{
$this->moveSettings();
$this->moveChannelSwitches();
$this->backfillCases();
$this->backfillHistory();
$this->detachPlaceholderGuests();
}
public function down(): void
{
DB::table('booking_events')->delete();
DB::table('bookings')->update(['intake' => null, 'case_type' => null, 'profile' => null, 'processing_mode' => null]);
DB::table('channels')->update(['process_overrides' => null]);
DB::table('properties')->update(['process_overrides' => null]);
DB::table('tenants')->update(['process_defaults' => null]);
}
private function moveSettings(): void
{
foreach (DB::table('properties')->get() as $property) {
$byTenant[$property->tenant_id][] = $property;
}
foreach ($byTenant ?? [] as $tenantId => $properties) {
$defaults = [];
$overrides = [];
foreach (self::PROPERTY_SETTINGS as $column => $key) {
$values = array_map(fn (object $property): mixed => $this->settingValue($column, $property->{$column}), $properties);
if (count(array_unique($values, SORT_REGULAR)) === 1) {
$defaults[$key] = $values[0];
continue;
}
foreach ($properties as $property) {
$overrides[$property->id][$key] = $this->settingValue($column, $property->{$column});
}
}
DB::table('tenants')->where('id', $tenantId)->update(['process_defaults' => json_encode($defaults)]);
foreach ($overrides as $propertyId => $values) {
DB::table('properties')->where('id', $propertyId)->update(['process_overrides' => json_encode($values)]);
}
}
}
private function settingValue(string $column, mixed $value): string|int|bool
{
return match ($column) {
'offer_mode' => $value === 'automatic' ? 'automatic' : 'manual',
'pre_reservation_enabled' => (bool) $value,
default => (int) $value,
};
}
private function moveChannelSwitches(): void
{
foreach (DB::table('channels')->get() as $channel) {
$inquiry = [];
$booking = [];
if (! $channel->payment_tasks_inquiry) {
$inquiry['payments'] = 'portal';
}
if (! $channel->payment_tasks_reservation) {
$booking['payments'] = 'portal';
}
if ($channel->contract_template_id !== null) {
$inquiry['contract_template_id'] = (int) $channel->contract_template_id;
}
if (($channel->contract_template_reservation_id ?? $channel->contract_template_id) !== null) {
$booking['contract_template_id'] = (int) ($channel->contract_template_reservation_id ?? $channel->contract_template_id);
}
DB::table('channels')->where('id', $channel->id)->update(['process_overrides' => json_encode(array_filter(['inquiry' => $inquiry, 'booking' => $booking]))]);
}
}
private function backfillCases(): void
{
$properties = DB::table('properties')->get()->keyBy('id');
$channels = DB::table('channels')->get()->keyBy('id');
foreach (DB::table('bookings')->orderBy('id')->get() as $booking) {
$property = $properties[$booking->property_id] ?? null;
$channel = $channels[$booking->import_channel_id ?? $booking->origin_channel_id ?? 0] ?? null;
$intake = $channel === null || $channel->booking_model === 'inquiry' ? 'inquiry' : 'booking';
// Exactly what the old code did: payment tasks by the channel's booking model, documents always ours.
$payments = $channel === null || ($channel->booking_model === 'portal_booking' ? $channel->payment_tasks_reservation : $channel->payment_tasks_inquiry) ? 'landlord' : 'portal';
$caseType = $intake === 'inquiry' ? ($channel === null ? 'a1' : 'a2') : ($payments === 'portal' ? 'a4' : 'a3');
$values = [
'processing' => $property?->offer_mode === 'automatic' ? 'automatic' : 'manual',
'pre_reservation' => (bool) ($property->pre_reservation_enabled ?? true),
'hold_hours' => (int) ($property->hold_hours ?? 48),
'documents' => 'landlord',
'payments' => $payments,
'guest_messages' => 'landlord',
'arrival_info_days_before' => (int) ($property->arrival_info_days_before ?? 3),
];
DB::table('bookings')->where('id', $booking->id)->update([
'intake' => $intake,
'case_type' => $caseType,
'profile' => json_encode([
'intake' => $intake,
'case_type' => $caseType,
'values' => $values,
'sources' => array_fill_keys(array_keys($values), 'migration'),
'frozen_at' => now()->toIso8601String(),
'origin' => 'migration',
]),
]);
}
}
private function backfillHistory(): void
{
$facts = [
'created_at' => 'Vorgang angelegt',
'contact_requested_at' => 'Gast um Kontaktdaten gebeten',
'offer_sent_at' => 'Angebot gesendet',
'accepted_at' => 'Angebot vom Gast angenommen',
'guest_confirmed_at' => 'Gast hat die Buchung per E-Mail bestätigt',
'confirmed_at' => 'Buchung verbindlich',
'confirmation_sent_at' => 'Bestätigung mit Unterlagen an den Gast gesendet',
'confirmation_failed_at' => 'Versand der Bestätigung fehlgeschlagen',
'arrival_info_sent_at' => 'Anreise-Informationen gesendet',
'review_requested_at' => 'Gast um eine Bewertung gebeten',
'cancelled_at' => 'Storniert',
'archived_at' => 'Archiviert',
];
$now = now();
foreach (DB::table('bookings')->orderBy('id')->get() as $booking) {
$rows = [];
$add = function (mixed $at, string $type, string $summary) use (&$rows, $booking, $now): void {
if ($at !== null) {
$rows[] = ['tenant_id' => $booking->tenant_id, 'booking_id' => $booking->id, 'type' => $type, 'summary' => mb_substr($summary, 0, 500), 'actor' => 'System', 'reason' => null, 'data' => null, 'occurred_at' => $at, 'created_at' => $now, 'updated_at' => $now];
}
};
foreach ($facts as $column => $summary) {
$add($booking->{$column} ?? null, 'migrated', $column === 'offer_sent_at' ? 'Angebot Version '.$booking->offer_version.' gesendet' : $summary);
}
foreach (DB::table('payments')->where('booking_id', $booking->id)->get() as $payment) {
$add($payment->paid_on ?? $payment->created_at, 'payment', ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').number_format(abs($payment->amount) / 100, 2, ',', '.').' € erfasst');
}
foreach (DB::table('booking_messages')->where('booking_id', $booking->id)->get() as $message) {
$add($message->sent_at, 'mail', 'E-Mail: '.$message->subject);
}
foreach (DB::table('booking_tasks')->where('booking_id', $booking->id)->where('status', 'done')->get() as $task) {
$add($task->completed_at, 'task', 'Aufgabe erledigt ('.$task->kind.')');
}
$add($now, 'migrated', 'Bisheriger Verlauf aus den vorhandenen Daten übernommen');
foreach (array_chunk($rows, 100) as $chunk) {
DB::table('booking_events')->insert($chunk);
}
}
}
/**
* Guests created only to fill the required guest of a portal reservation: first name "Gast", the channel name in
* brackets as last name, no e-mail. Their cases now simply have no guest yet.
*/
private function detachPlaceholderGuests(): void
{
$placeholders = DB::table('guests')->where('first_name', 'Gast')->where('last_name', 'like', '(%)')->where(fn ($query) => $query->whereNull('email')->orWhere('email', ''))->pluck('id');
if ($placeholders->isEmpty()) {
return;
}
DB::table('bookings')->whereIn('guest_id', $placeholders)->update(['guest_id' => null]);
DB::table('blocked_periods')->whereIn('guest_id', $placeholders)->update(['guest_id' => null]);
foreach ($placeholders as $guestId) {
if (! DB::table('bookings')->where('guest_id', $guestId)->exists()) {
DB::table('guests')->where('id', $guestId)->delete();
}
}
}
};
@@ -0,0 +1,645 @@
---
id: PLAN-010
typ: umsetzungsplan
titel: Umsetzungsplan zur Prozessarchitektur v0.10
status: entwurf-zur-freigabe
version: "0.10"
stand: 2026-11-01
---
# Umsetzungsplan zur Prozessarchitektur v0.10
**Entwurf zur Entscheidung durch den Betreiber.** Dieses Dokument ist kein Teil der normativen Fachspezifikation. Es vergleicht die Sollbeschreibung v0.10 mit dem Code auf `develop`. Letzter Code-Commit zum Buchungsprozess ist `81c025f` vom 30.10.2026; danach kamen nur Website- und Compliance-Commits. Daraus leitet das Dokument einen priorisierten Umsetzungsplan ab. Es wurde nichts implementiert und nichts migriert.
**Kennzeichnung im Text:**
- **[Befund]** ist im Code nachgeprüft, mit Verweis.
- **[Empfehlung]** ist ein Vorschlag des Coding-Agenten.
- **[Annahme]** ist noch nicht geprüft und muss vor der Umsetzung bestätigt werden.
---
## 1. Management Summary
**Kernaussage:** Die fachliche Zielarchitektur v0.10 lässt sich ohne Neuentwicklung erreichen. Dafür reicht kein vorsichtiges Weiterbauen am Bestehenden. Nötig ist eine **gezielte Konsolidierung**:
- **ein** Vorgang statt drei paralleler Träger,
- **eine** Aufgabenliste statt vier,
- **eine** Zusammenstellung vor jedem Dokument,
- **eine** Einstellungshierarchie statt verstreuter Schalter an Wohnung und Kanal,
- eine neu gestaltete Vorgangsseite, die führt, statt ein Werkzeugkasten mit 17 Aktionsknöpfen zu sein.
**Was trägt:**
- Der Angebotsweg über die eigene Website (A1) ist fachlich solide und gut getestet: versionierte Angebote mit eingefrorenem Konditionsstand und Hash, signierter Annahmelink, atomare Annahme mit Kalender-Frischeprüfung, Vertragserzeugung, Zahlungserinnerungen, Anreise-Mail, Bewertung.
- Kanalanbindung, iCal-Regelwerk, Portal-Mail-Erkennung, Kalenderspiegelungen und die **Owner-/Ursprungskanal-Zuordnung** (E-028) sind vorhanden und werden weiterverwendet.
**Was nicht trägt:**
- Externe Direktbuchungen (A3–A5) entstehen nur über Umwege: manuelles „Akte anlegen“, ein zweiter Erfassungsweg, Platzhalter-Gäste und eigene Preisberechnung statt Portalpreis.
- A6 mit Gästen und Leistungen ist nicht abbildbar.
- Die Prozessart hängt am Kanal statt an der Eingangsart.
- Nach Buchungsabschluss gibt es keine Änderungsfunktion für einen gebuchten Vorgang.
- Die Bedienung setzt Kenntnis interner Statusmodelle voraus.
**Empfohlene Vorgehensweise:** neun Pakete in drei Stufen.
- **Stufe 1, Grundlagen:** Vorgangskern und Einstellungen, danach geführte Vorgangsbearbeitung.
- **Stufe 2, Kernfunktionen:** Dokumente, Eingang aller Kanäle, Änderung und Abbruch, A6, Angebotsweg mit Hold 0.
- **Stufe 3, Ergänzungen:** externe Beträge und Zahlungsstände, Aufenthalt und Abschluss.
**Erster Schritt:** Paket 1, „Vorgangskern und Einstellungen“ (§9).
**Betreiberentscheidungen:** Fünf kurze fachliche Entscheidungen sind nötig (§8.1). Keine davon blockiert Paket 1.
---
## 2. Aktualisierter Soll-Ist-Abgleich
### 2.1 Was aus der Analyse zu v0.9 weiterhin gilt
Alle damaligen Befunde sind im Code unverändert, weil seit `81c025f` niemand am Buchungscode gearbeitet hat. Durch v0.10 neu bewertet werden drei Punkte:
- Die drei damals offenen Grundsatzfragen sind **jetzt fachlich entschieden** und werden nicht erneut gestellt:
- **A6 ist immer ein Vorgang.** Quellen: [Archetypen](01_Buchungsarchetypen.md), E-023, E-024.
- **Das Profil richtet sich nach Kanal und Eingangsart. Die Partnerherkunft ist nur ein kaufmännisches Merkmal.** Quellen: E-012, [Profile](02_Abwicklungsprofile_und_Dokumente.md).
- **Bei Hold = 0 wird automatisch oder manuell bestätigt, je nach Einstellung.** Quelle: E-030.
- **Neu ist E-029:** Globale Standardwerte gelten je Vermieter, Kanalwerte überschreiben sie nur, wenn sie ausdrücklich gesetzt sind. Heute liegen die Prozess-Einstellungen an der **Wohnung**. Das ist eine zusätzliche Ebene, die v0.10 nicht vorsieht (siehe L4).
- **Neu ist die Gewichtung der Bedienbarkeit** (Auftrag §4). Die bisherige Oberfläche wird nicht als Maßstab übernommen; die UX-Befunde in 2.3 sind deshalb gleichrangig mit den fachlichen Lücken.
### 2.2 Fachliche und strukturelle Lücken
| # | Soll (v0.10) | Ist [Befund] | Bewertung |
|---|---|---|---|
| L1 | Ein Vorgang je Anlass, kein „Akte anlegen“ | Drei Träger: **(1)** `Booking`, **(2)** `BlockedPeriod` mit eigener Gastzuordnung ([AssignOccupationGuest](../../app/Actions/AssignOccupationGuest.php)) für Portalbelegungen und A6, **(3)** paralleler Erfassungsweg [RecordPortalBooking](../../app/Actions/RecordPortalBooking.php) mit Abschnitt „Buchungsweg“ in [BookingForm](../../app/Filament/Resources/Bookings/Schemas/BookingForm.php). Eine Portalreservierung wird nur per Klick über [OpenPortalFile](../../app/Actions/OpenPortalFile.php) zum Vorgang. | Strukturelle Kernlücke |
| L2 | Unbekannt ist nicht 0, keine Platzhalter | `bookings.guest_id` ist `NOT NULL` ([Migration](../../database/migrations/2026_10_22_092645_create_bookings_table.php)). `OpenPortalFile` legt deshalb den Gast „Gast (Portal)“ ohne E-Mail an, setzt 2 Personen und einen selbst berechneten Preis. `total` ist eine Pflicht-Ganzzahl. | Verstößt gegen E-014 und R01 „Kritische Ausnahmen“ |
| L3 | Profil nach Kanal **und Eingangsart**, Vorlagenwahl nicht nur nach Kanal | `Channel::booking_model` (Anfrage/Portalbuchung/Gemischt) steuert an vier Stellen: [BookingProgress](../../app/Support/BookingProgress.php), [OfferTerms::templateFor](../../app/Documents/OfferTerms.php), [Booking::wantsPaymentTasks](../../app/Models/Booking.php), [CalendarClearance](../../app/Availability/CalendarClearance.php). Bei „Gemischt“ wird für verbindliche Buchungen die Anfragevorlage gewählt. Archetypen A1–A6 kennt der Code nicht. | Kernlücke |
| L4 | Vermieterstandard → Kanalabweichung → Vorgang, „nicht gesetzt“ ≠ 0 | `hold_hours`, `pre_reservation_enabled`, `offer_mode`, `arrival_info_days_before` und `cancellation_mode` liegen an der Wohnung ([Property](../../app/Models/Property.php)). Am Tenant liegen andere Standards (`deposit_due_days`, `review_request_after_days`). Am Kanal liegen zwei Zahlungs-Booleans und zwei Vorlagen-IDs. Eine Vererbungslogik mit „nicht gesetzt“ gibt es nicht. **Kanäle sind je Wohnung angelegt** (`channels.property_id`). | Neu zu bauen; Migrationsfrage |
| L5 | Hold > 0: Angebot passend befristet; Hold = 0: Auskunft unter Vorbehalt, Buchungswunsch, erneute Prüfung | Bei der Anfrage wird `pre_reservation_enabled` berücksichtigt ([CreateReservation](../../app/Actions/CreateReservation.php): ohne Vorreservierung kein Hold). [SendOffer](../../app/Actions/SendOffer.php) setzt aber **immer** `hold_expires_at` und einen annehmbaren Link. Damit entsteht auch bei Hold = 0 ein Hold plus annehmbares Angebot, ein widersprüchlicher Zustand. Den Weg „Auskunft → Buchungswunsch“ gibt es nicht. | Lücke, Teilfehler |
| L6 | Portalpreis ist maßgeblich, keine erfundene Zerlegung, Beträge mit Quelle | [PortalPrice](../../app/Pricing/PortalPrice.php) zerlegt den Portal-Gesamtpreis in eigene Positionen plus „Abweichung Portalpreis“. `payments` kennt nur Betrag, Datum, Methode und Notiz, aber weder „laut Portal bezahlt“, Auszahlung, Provision noch Gast-Servicegebühr. | Verstößt gegen E-014, E-015 und K01 |
| L7 | Verlauf mit Ursache, Initiator und Quelle (E-019) | Der Verlauf wird aus Zeitstempeln abgeleitet (`BookingProgress::history()`), es gibt kein gespeichertes Ereignisprotokoll. | Lücke |
| L8 | Portalstorno oder -änderung erreicht den Vorgang | [SyncChannel](../../app/Actions/SyncChannel.php) löscht verschwundene Spiegeleinträge. [ProcessPortalMail](../../app/Actions/ProcessPortalMail.php) gibt bei Storno-Mails nur Sperren mit Quelle E-Mail frei. Für einen gebuchten Vorgang entsteht **keine Aufgabe**, die Buchung bleibt still „bestätigt“. | Sicherheitsrelevante Lücke |
| L9 | A6 mit Gästen, Leistungen, Kurabgabe und Zahlungen; reine Sperre schlank | Sperren ([BlockedPeriodResource](../../app/Filament/Resources/BlockedPeriods/BlockedPeriodResource.php)) haben Zweck und Notiz, aber keinen Gast, keine Leistungen und keine Zahlung. Kurabgabe existiert nur als Vertragstext. | Lücke |
| L10 | **Änderung nach Verbindlichkeit** (X02, X08): Zeitraum, Gäste, Leistungen, Preis mit Folgen | Es gibt **keine Bearbeitungsseite und keine Änderungsaktion** für gebuchte Vorgänge (Booking-Seiten: List, Create, View). Nur „Zusatzleistungen erfassen“ und die Statusumschaltung [SetBookingStatus](../../app/Actions/SetBookingStatus.php), die den Ablauf umgeht. | **Neu erkannt**, wesentliche Lücke |
| L11 | Sperrnachweis: veranlasst / sichtbar / wirksam (E-018) | `ChannelTask` kennt nur offen / erledigt / verworfen. | Kleine Lücke (E-027 pragmatisch) |
| L12 | Dokument passend zum Sachverhalt, Zusammenstellung vor Versand | `ConfirmBooking::bind()` wählt die Vorlage still. Eine Dokumentart „Dokumentation einer extern verbindlichen Buchung“ und eine A6-Bestätigung fehlen. Der Angebotsdialog ist die einzige Zusammenstellung. | Lücke |
| L13 | Abschluss mit Nachläufern (P05, E-010) | Der Status `Completed` wird von [SendBookingReminders](../../app/Actions/SendBookingReminders.php) gesetzt. Nachläufer (offene Forderung, Schaden) sind nur als Zahlungsaufgaben abbildbar. Das Abschluss-Gate ist fachlich noch offen. | Später |
### 2.3 Befunde zur Bedienung
| # | Befund [Befund] | Wirkung |
|---|---|---|
| U1 | **Vier getrennte Arbeitslisten:** „Aufgaben“ (`BookingTask`), „Portal-Aufgaben“ (`ChannelTask`), „Postfach“ (`InboxMessage`), „Ungeklärte Belegungen“ (PortalOccupations). Hinzu kommen abgeleitete „nächste Schritte“ in der Akte. | Die Vermieterin muss wissen, in welcher Liste sie suchen soll. |
| U2 | Die Vorgangsseite [ViewBooking](../../app/Filament/Resources/Bookings/Pages/ViewBooking.php) hat 17 Kopfaktionen (u. a. Angebot senden, Kontaktdaten, Kontakt anfordern, Angebotslink, PDF, Direkt bestätigen, Ablehnen, Vormerkung verlängern, Bestätigung erneut, Leistungen, Vertragstext, Vertrag, Notizen, Status setzen, Archiv, Storno). Welche gerade sinnvoll ist, muss man selbst wissen. | Keine Führung, Fehlbedienung möglich (z. B. Status setzen statt Storno) |
| U3 | „Angebot senden“ ist ein großer Dialog: Zeitraum, Personen, Rabattcode, Preisanpassung, Vorlage, Anlagen, Gültigkeit, Nachricht und Gastadresse. Vorlage und Anlagen muss man aktiv wählen. | Überladen; Entscheidungen, die das System treffen kann |
| U4 | Die einfache Ansicht ([AdminMode](../../app/Enums/AdminMode.php)) blendet nur Menüpunkte aus. Die Seiten selbst zeigen in beiden Modi dieselben technischen Details. | Der Expertenmodus ist nur eine Menüfrage. |
| U5 | Begriffe aus dem Innenleben stehen in der Oberfläche: Vormerkung/Hold, Akte, Repräsentation, Ursprungskanal, Buchungsmodell, Echo-Verhalten, Exportmodus. | Setzt Systemkenntnis voraus |
| U6 | Sperren und Portalbelegungen liegen in eigenen Listen außerhalb der Vorgänge. Ein Klick im Kalender führt je nach Herkunft auf unterschiedliche Seiten. | Kein einheitlicher Einstieg |
### 2.4 Was fachlich brauchbar ist und erhalten bleibt [Befund]
- **Angebotskette:** [SendOffer](../../app/Actions/SendOffer.php), [AcceptOffer](../../app/Actions/AcceptOffer.php), [ConfirmBooking](../../app/Actions/ConfirmBooking.php), [RejectOffer](../../app/Actions/RejectOffer.php), [ExpireReservations](../../app/Actions/ExpireReservations.php). Dazu gehören Konditions-Snapshot (`offer_terms`), Hash, signierte Links, Annahmeprotokoll und Sperrlogik `lockForTransition()`.
- **Verfügbarkeit:** `Booking::occupying()`, [CalendarClearance](../../app/Availability/CalendarClearance.php) (Frischeprüfung vor Annahme), Mindestaufenthalt, Preisberechnung `PriceCalculator`.
- **Kanäle:** Connector-System `app/Channels`, iCal-Regelwerk, [ReconcileChannelRepresentations](../../app/Actions/ReconcileChannelRepresentations.php) (Spiegelungen), Portal-Mail-Erkennung, Kanalaufgaben samt Erinnerungen, Export-Feeds.
- **Owner-Zuordnung:** `origin_channel_id` und `import_channel_id` an Buchungen und Belegungen, mit Konsistenzprüfung in [HasChannelProvenance](../../app/Models/Concerns/HasChannelProvenance.php).
- **Weitere:**
- versionierte Vertragsvorlagen und Anlagen
- Stornoregeln mit Staffeln und `Cancellation`-Datensatz (Initiator, Gebühr)
- Zahlungen, Mailprotokoll `BookingMessage`
- Postfach mit Fingerabdruck und Erinnerungsintervall, Tages- und Wochenberichte
- Mehrmandantenfähigkeit, Admin-Modi, 2FA
- etwa 525 Tests
---
## 3. Empfohlene Zielrichtung
### 3.1 Der Vorgang ist die bestehende Buchung, fachlich erweitert [Empfehlung]
| Option | Bewertung |
|---|---|
| **A – `Booking` wird der Vorgang.** Fachlich heißt er in der Oberfläche „Vorgang“, technisch wird er erweitert. | **Empfohlen.** Nummernkreis, Gast, Leistungen, Preis, Zahlungen, Aufgaben, Mails, Dokumente, Storno und Sperrlogik sind vorhanden. Erweiterungen sind additiv. Alle Tests, signierten Links und eingefrorenen Konditionsstände bleiben gültig. |
| B – neue Tabelle `cases` über `Booking` und `BlockedPeriod` | Damit entstünde genau die zusätzliche Struktur, die E-023 und E-028 ausschließen. Alle Beziehungen müssten umziehen, ohne fachlichen Gewinn. |
Daraus folgt:
1. **Jeder Anlass ist eine `Booking`-Zeile**, auch A3–A5 und **A6** (Eigennutzung, private Überlassung, Wartung).
- Die Art wird über zwei Merkmale geführt: **Vorgangsart** (A1–A6 bzw. ein „Typ“) und **Eingangsart** (Anfrage / verbindliche Buchung / interner Anlass).
- Der technische Name `Booking` bleibt; die Oberfläche sagt „Vorgang“.
2. **`BlockedPeriod` wird reiner Kalendernachweis:** importierte Fremdbelegungen, Spiegelungen, E-Mail-Schnellsperren und ungeklärte Einträge.
- Eigene Gastzuordnung und manuelle Zweck-Sperren entfallen dort und wandern in den Vorgang.
- Ein Nachweis verweist auf „seinen“ Vorgang (`linked_booking_id` besteht bereits).
3. **Belegung = Wirkung eines Vorgangs:** Die Kalenderlogik (`occupying`) gilt einheitlich für A1-Hold, verbindliche Buchung und A6. Für A6 kommt keine eigene Mechanik dazu.
4. **Unbekannte Werte sind erlaubt:**
- Gast, Personenzahl und Beträge sind optional.
- Die Oberfläche zeigt „noch nicht bekannt“.
- Eine Aktion, die den Wert braucht, wartet mit einer Aufgabe darauf.
### 3.2 Einstellungen in drei Ebenen [Empfehlung, folgt E-029]
1. **Vermieterstandard** (Tenant): Bearbeitung automatisch oder „ich gebe frei“, Haltefrist, Zuständigkeiten, Anreise-Info-Vorlauf, Bewertungsanfrage, Standardvorlagen je Dokumentart.
2. **Kanalabweichung je Eingangsart:** Für jeden Kanal kann je Eingangsart einzeln überschrieben werden. „Nicht gesetzt“ bedeutet „wie Standard“ und ist von 0, „nein“ und „manuell“ unterscheidbar. Im Datenmodell heißt das `null` bedeutet erben.
3. **Vorgang:** Beim Entstehen wird das **wirksame Profil eingefroren** (Snapshot). Der Bearbeiter kann es im Vorgang übersteuern, z. B. auf „Diesen Vorgang selbst prüfen“; das wird im Verlauf protokolliert.
**Ersetzt werden dadurch:**
- `Channel::booking_model` als Steuergröße,
- die Booleans `payment_tasks_inquiry/reservation`,
- die beiden Vorlagen-IDs am Kanal,
- die Prozessfelder an der Wohnung.
Preis, Belegung, Mindestaufenthalt und objektspezifische Vertragsdaten bleiben an der Wohnung (02_Abwicklungsprofile: „Objektkontext beeinflusst Preis, Belegung und Vorlagenauswahl“).
**Technischer Hinweis:** Kanäle sind heute je Wohnung angelegt. Ein Vermieter mit drei Wohnungen auf FeWo-direkt hat drei Kanalzeilen. Die Kanalabweichung wird deshalb in der Oberfläche **einmal je Portal** gepflegt und auf alle Wohnungen dieses Portals angewendet. Eine Abweichung je Wohnung wäre eine zusätzliche Ebene, die v0.10 nicht vorsieht; siehe Entscheidung B2.
### 3.3 Aktivitäten, Aufgaben, Automatik, Freigabe [Empfehlung]
Eine Workflow-Engine ist nicht nötig. Das Modell:
- **Aktivitätenkatalog im Code**, nicht konfigurierbar, etwa 15 Aktivitäten, z. B.:
- Gastdaten vervollständigen
- Angebot senden / Auskunft senden
- Buchung bestätigen / Buchungsunterlagen senden
- Andere Portale sperren
- Anzahlung überwachen / Restzahlung anfordern
- Anreise-Info senden
- Bewertung anfragen
- Portalstorno prüfen
Jede Aktivität hat eine **Anwendbarkeitsregel**, die sich aus Profil und Vorgangsart ergibt (z. B. „Zahlung überwachen“ nur bei eigener Zahlungszuständigkeit), eine **Voraussetzung** (benötigte Daten) und eine **Ausführung** (bestehende Actions).
- **Zustand je Aktivität:** offen, erledigt (intern), extern erledigt (mit Quelle), nicht anwendbar, wartet auf Daten, widersprüchlich. Das entspricht genau den Gate-Ergebnissen aus [Gates](Querschnitt/Gates_und_Nachweise.md). Die Gates G1–G5 werden **nicht** als Statusmaschine gebaut, sondern aus diesen Zuständen abgeleitet.
- **Automatik:**
- Ein Hintergrundlauf (Scheduler plus direkte Auslösung nach Ereignissen) führt anwendbare Aktivitäten aus, sobald die Voraussetzungen erfüllt sind und der Modus „automatisch“ ist. Das ist eine Verallgemeinerung des bestehenden [AutoOffer](../../app/Actions/AutoOffer.php) mit seinen „Blockern“.
- Fehlt etwas, entsteht **eine** verständliche Aufgabe („E-Mail-Adresse des Gastes fehlt“).
- Bei Modus „ich gebe frei“ bereitet das System das Ergebnis vollständig vor (Preis, Dokument, Mail) und legt eine **Freigabe-Aufgabe** mit Vorschau an.
- **Fortsetzung nach einer Aufgabe:** Beim Erledigen fragt das System nur, wenn es relevant ist: „Danach automatisch weitermachen?“ (Vorbelegung aus dem Profil). Die Wahl gilt für diesen Vorgang.
- **Verbindlichkeitsschutz:** Ein bereits verbindlicher Vorgang (eigene Annahme oder extern verbindlich) kann durch keine Einstellung und keinen Abbruch in „unverbindlich“ zurückfallen. „Beenden“ führt dann in den Stornoweg (§4.6).
- **Neutralitätsregel (Auftrag §3.2):** Automatische Prüfauslöser sind nur objektive Kriterien: fehlende oder widersprüchliche Daten, unzustellbare Adresse, Belegungskonflikt, Spam-Schutz. Nationalität oder Herkunft werden **nie** als Prüfkriterium verwendet. Das wird als Regel im Code dokumentiert und mit einem Test abgesichert.
- **Gespeicherter Verlauf:** Jede Aktivität, Übersteuerung, Änderung und jedes Portalereignis schreibt einen Ereigniseintrag (wer/was/wann/Quelle/Ursache). Die heutige abgeleitete Historie entfällt.
### 3.4 Was zurückgebaut oder ersetzt wird [Empfehlung]
| Bestand | Maßnahme |
|---|---|
| `RecordPortalBooking` und Formularabschnitt „Buchungsweg“ | Entfällt; die Erfassung läuft über „Neu“ (§4.2). |
| Knopf „Akte anlegen“, `OpenPortalFile` | Die Logik wandert in den automatischen Eingang; der Knopf entfällt. |
| `AssignOccupationGuest` (Gast an Belegung) | Entfällt; der Gast hängt am Vorgang. |
| Zerlegungslogik `PortalPrice` | Ersetzt durch „Gesamtpreis laut Portal“ als belegte Position. |
| `Channel::booking_model`, Zahlungs-Booleans, Vorlagen-IDs am Kanal | Ersetzt durch das Profil (§3.2). |
| `BookingProgress` (abgeleitete Schritte und Historie) | Ersetzt durch Aktivitäten und gespeicherten Verlauf. |
| `SetBookingStatus` als freie Statusumschaltung | Nur noch im Expertenmodus mit Pflichtbegründung; normale Wege laufen über Aktionen. |
| Vier Arbeitslisten | Eine Liste „Zu erledigen“; technische Systemmeldungen bleiben im Expertenmodus sichtbar. |
| Manuelle Sperren als eigene Ressource | A6-Vorgang mit Schnellerfassung. |
**Nicht gebaut werden:** Workflow-Designer, frei konfigurierbare Schritte, ein Nachweis-Enum je Feld, eine Risiko-Engine, Revenue Management und V02-Funktionen.
---
## 4. UX- und Bedienkonzept
### 4.1 Prinzipien
1. **Die Frage „Was ist zu tun?“ steht vorn.** Die Startseite zeigt die Liste „Zu erledigen“ mit wenigen Einträgen in Alltagssprache, jeweils mit **einem** Hauptknopf.
2. **Eine Vorgangsseite für alles.** Ganz oben steht der Stand in einem Satz, z. B. „Gebucht über FeWo-direkt · Anzahlung vom Portal eingezogen · Anreise in 12 Tagen“. Darunter folgen der Kasten „Als Nächstes“ und eine Zeitleiste mit dem Erledigten.
3. **Nur sinnvolle Knöpfe.** Aktionen erscheinen nur, wenn sie im aktuellen Stand anwendbar sind. Es gibt drei feste Sekundäraktionen: **Ändern**, **Nachricht an Gast**, **Beenden**.
4. **Das System entscheidet, was es entscheiden kann.** Vorlage, Anlagen, Fristen, Preise und Zuständigkeit ergeben sich aus dem Profil. Die Vermieterin sieht das Ergebnis in der Vorschau und kann es nur bei Bedarf ändern (Bereich „Anpassen“, standardmäßig zugeklappt).
5. **Unbekannt wird sichtbar gemacht.** Fehlende Angaben erscheinen als „noch nicht bekannt“ mit dem Hinweis, wofür sie gebraucht werden. Es gibt keine Pflichtfelder auf Vorrat.
6. **Klartext statt Interna.**
| Statt | Sagen wir |
|---|---|
| Hold | „Zeitraum reserviert bis …“ |
| Repräsentation | „im Kalender von …“ |
| Status `OfferSent` | „Angebot liegt beim Gast“ |
7. **Die Expertenansicht ist dieselbe Seite mit mehr Details.** Sie zeigt zusätzlich Kanalnachweise, Rohdaten, Versionen, Hashes, Regeln und Systemmeldungen. Es entstehen keine zwei Anwendungen: dieselben Seiten mit Abschnitten, die in der einfachen Ansicht ausgeblendet sind.
8. **Automatik bleibt sichtbar und steuerbar.**
- Jede Vorgangsseite zeigt „Wird automatisch bearbeitet“ oder „Sie geben jeden Schritt frei“, mit einem Umschalter für diesen Vorgang.
- Automatisch Erledigtes steht in der Zeitleiste mit „automatisch“ gekennzeichnet.
**Menü in der einfachen Ansicht (Vorschlag):**
- Start (Zu erledigen)
- Kalender
- Vorgänge
- Gäste
- Preise
Alles andere steht im Expertenmenü oder unter „Einstellungen“.
### 4.2 Benutzerweg: Neue Anfrage (A1, A2)
1. **Eingang**
- Eine Website-Anfrage erzeugt den Vorgang automatisch, wie heute.
- Telefon, E-Mail oder eine Portalanfrage erfasst die Vermieterin über **Neu → „Anfrage“**: Zeitraum, Personen (optional), Name und Kontakt (so weit bekannt), Kanal.
2. **Automatische Vorbereitung**
- Verfügbarkeit prüfen.
- Haltefrist laut Profil:
- Bei > 0 wird der Zeitraum reserviert und andere Portale werden gesperrt (automatisch oder als Aufgabe).
- Bei 0 wird nichts reserviert.
- Preis berechnen, Dokument vorbereiten (Angebot oder Auskunft).
3. **Modus automatisch:** Das System versendet und vermerkt in der Zeitleiste „Angebot automatisch gesendet“. Die Startseite meldet das nur zur Information.
4. **Modus „ich gebe frei“** (oder es fehlt etwas): Unter „Zu erledigen“ erscheint z. B.:
- **„Angebot an Frau Meier prüfen“** mit dem Knopf „Ansehen & senden“. Das öffnet die **Zusammenstellung** (§4.5).
- **„E-Mail-Adresse von Frau Meier fehlt“** mit dem Knopf „Eintragen“. Nach dem Speichern fragt das System: „Angebot jetzt automatisch senden?“
5. **Gast nimmt an** (Hold > 0): Der Vorgang wird gebucht, ohne zweite Freigabe (E-003). Bestätigung, Vertrag und Zahlungsplan laufen automatisch.
6. **Gast äußert Buchungswunsch** (Hold = 0): Erneute Prüfung, dann entweder automatische Bestätigung oder die Aufgabe „Buchungswunsch von Frau Meier bestätigen?“ mit „Bestätigen / Ablehnen“ (E-030).
7. **Ablauf oder Ablehnung:** Der Vorgang endet automatisch mit „ohne Buchung beendet“. Die Reservierung wird freigegeben, auf der Startseite erscheint nur ein Hinweis.
### 4.3 Benutzerweg: Externe Direktbuchung (A3–A5)
1. **Eingang:** Eine Portal-Mail oder eine sicher erkannte iCal-Reservierung erzeugt **automatisch** einen Vorgang „Gebucht über FeWo-direkt“. Mehrfachmeldungen werden zusammengeführt. Bei Portalen ohne Automatik erfasst die Vermieterin die Buchung über **Neu → „Buchung von einem Portal“**: Portal, Buchungsnummer, Zeitraum, Gesamtpreis laut Portal, Gast so weit bekannt.
2. **Unklare Kalendereinträge** werden nicht zum Vorgang. Sie erscheinen als Aufgabe „Unbekannte Belegung von FeWo-direkt 10.–17.07. – was ist das?“ mit den Antworten „Buchung“, „eigene Sperre/Spiegelung“, „ignorieren“.
3. **Folgeaufgaben gemäß Profil:**
- „Andere Portale sperren“, nur wo nötig
- „Gastdaten aus dem Portal ergänzen“
- „Buchungsunterlagen senden“ (A3/A4, mit Vorschau)
- „Zahlungen überwachen“, nur wenn wir zuständig sind; bei A4 steht „Zahlung über FeWo-direkt“ als extern verantwortet
4. **Keine Annahme, kein Angebot, kein eigener Preis.** Der Portalpreis steht als „Gesamtpreis laut Portal“ im Vorgang. Unbekannte Bestandteile stehen als „nicht übermittelt“.
5. **Storno oder Änderung im Portal erkannt:** Es entsteht die Aufgabe „FeWo-direkt meldet Stornierung – prüfen“. Ein Klick übernimmt die Stornierung in den Vorgang mit Initiator „Gast über Portal“ und den Folgen.
### 4.4 Benutzerweg: Eigene Nutzung, Besuch, Wartung (A6)
- **Neu → „Eigene Nutzung / Besuch“:** Zeitraum, Anlass, optional Gäste, Leistungen (Wäsche, Kurabgabe), Betrag (Miete 0 ist Standard). Optional wird eine Bestätigung an die Gäste gesendet. Zahlungen sind optional.
- **Neu → „Sperre (z. B. Wartung)“**, auch per Markieren eines Zeitraums im Kalender: nur Zeitraum und Grund. Es gibt weder Gast noch Dokument noch Zahlung. Portale werden gesperrt (automatisch oder als Aufgabe).
- **Ändern / Aufheben** auf derselben Vorgangsseite. Aufheben ist **keine** Stornierung, sondern „Sperre aufgehoben“; die Portale werden entsperrt.
### 4.5 Freigabe: die Zusammenstellung
**Eine** wiederverwendbare Ansicht für alle Dokumente: Angebot, Auskunft, Buchungsbestätigung, Buchungsunterlagen extern, A6-Bestätigung, Storno- und Änderungsbestätigung. Sie zeigt Gast, Zeitraum, Preis mit Quelle, Leistungen, Stornoregel, die gewählte Vorlage (Name, nicht ID) und die Anlagen sowie eine **PDF- und Mail-Vorschau**.
Knöpfe:
- **„Senden“**
- **„Anpassen“**: klappt Felder auf, mit Neuberechnung und neuer Vorschau
- **„Nicht senden“**: mit der Frage, ob die Aktivität entfällt oder später kommt
Für extern verbindliche Buchungen markiert die Zusammenstellung, wenn die gewählte Vorlage Pflichten enthält, die nicht nachweislich vereinbart sind (E-004). Sie sperrt nicht hart, verlangt aber eine bewusste Bestätigung.
### 4.6 Bestehende Vorgänge: Ändern und Beenden
- **„Ändern“** (Zeitraum, Personen, Leistungen, Preis):
- **vor der Verbindlichkeit:** neue Angebotsversion, wie heute;
- **danach:** Änderungserfassung mit Antragsteller, Grund und wirksam ab, mit automatischer Folgenanzeige vor dem Speichern:
- Kalender und Portalsperren,
- Preisdifferenz (A1/A2: neu berechnen und anzeigen; A3–A5: Portalbetrag eintragen),
- Zahlungsplan,
- neue Bestätigung ja/nein.
- **„Beenden“** fragt **eine** Sache: „Warum?“. Das System leitet den passenden Weg ab:
| Stand | Ergebnis |
|---|---|
| Unverbindlich | „ohne Buchung beendet“ (Absage an den Gast optional) |
| Verbindlich, eigene Buchung | Stornodialog mit Initiator (Gast / Vermieter), Stornokosten laut eingefrorener Regel, Erstattungsaufgabe |
| Verbindlich, extern (A3–A5) | Stornodialog plus Hinweis bzw. Aufgabe „Stornierung im Portal veranlassen/prüfen“; lokal wird nichts still gelöscht |
| A6 | „Sperre aufheben“ bzw. „Aufenthalt abgesagt“ |
---
## 5. Priorisierter Umsetzungsplan
### 5.1 Übersicht und Reihenfolge
```
Stufe 1 (Grundlagen) Stufe 2 (Kernfunktionen) Stufe 3 (Ergänzung)
┌──────────────┐ ┌────────────────────┐ ┌──────────────────────┐
│ 1 Vorgangs- │─▶│ 2 Geführte Vor- │─┬▶│ 3 Zusammenstellung & │─┬▶ 7 Hold 0 / Buchungswunsch
│ kern & │ │ gangsbearbeitung │ │ │ Dokumente │ │
│ Einstellung│ │ (Aufgaben, Auto- │ │ └──────────────────────┘ ├▶ 8 Externe Beträge & Zahlungsstände
└──────────────┘ │ matik, Seite) │ ├▶ 4 Ein Eingang für alle Kanäle (A2–A5) ┘
└────────────────────┘ ├▶ 5 Änderung, Storno, Abbruch
└▶ 6 A6 im Vorgang ──▶ 9 Aufenthalt & Abschluss
```
| # | Paket | Stufe | Abhängig von | Archetypen / Phasen | Größe |
|---|---|---|---|---|---|
| 1 | Vorgangskern und Einstellungen | Grundlage | – | alle / P01–P03 | groß |
| 2 | Geführte Vorgangsbearbeitung | Grundlage | 1 | alle / P01–P05 | groß |
| 3 | Zusammenstellung und Dokumente | Kern | 2 | A1–A4, A6 / P02–P03 | mittel |
| 4 | Ein Eingang für alle Kanäle | Kern | 2 (für Vollabnahme A3: 3) | A2–A5 / P01–P03 | groß |
| 5 | Änderung, Storno, kontrollierter Abbruch | Kern | 2, 3 | alle / X01–X04, X08 | mittel–groß |
| 6 | A6 im Vorgang | Kern | 2, 3 | A6 / P01–P05 | mittel |
| 7 | Angebotsweg Hold 0 und Buchungswunsch | Kern (spät) | 3 | A1, A2 / P01–P02 | mittel |
| 8 | Externe Beträge und Zahlungsstände | Ergänzung | 4 | A3–A5 / P03 | mittel |
| 9 | Aufenthalt und Abschluss | Ergänzung | 2, 6; Entscheidung B4 | alle / P04–P05 | mittel |
Die Pakete 4, 5 und 6 können nach 3 parallel laufen, wenn getrennte Agenten an getrennten Dateien arbeiten (siehe [ZUSAMMENARBEIT](../ZUSAMMENARBEIT.md)). Paket 7 kommt bewusst später: Der heutige A1-Weg mit Hold > 0 funktioniert. Paket 7 wird nur vorgezogen, wenn ein Vermieter bald Hold = 0 nutzen will (Entscheidung B5).
### 5.2 Paket 1: Vorgangskern und Einstellungen (konkret)
**Fachliches Ziel:** Jeder Anlass lässt sich als Vorgang führen, ohne erfundene Daten. Das System weiß für jeden Vorgang, **was für ein Fall er ist** und **welche Regeln für ihn gelten**.
**Veränderungen gegenüber dem Ist:**
- Gast, Personenzahl und Beträge des Vorgangs werden optional. Vorhandene Platzhalter-Gäste („Gast (Portal)“ ohne Kontaktdaten) werden vom Vorgang gelöst und gelöscht, sofern sie nirgends sonst hängen.
- Neue Merkmale am Vorgang: **Vorgangsart** (A1–A6) und **Eingangsart**. Bestehende Vorgänge werden aus `source`, Kanal und Status abgeleitet.
- **Einstellungshierarchie** nach §3.2:
- Vermieterstandards neu am Tenant.
- Kanalabweichung je Eingangsart mit „nicht gesetzt = erben“, bearbeitet je Portal.
- Wirksames Profil als eingefrorener Snapshot am Vorgang.
- Ein Profil-Resolver ersetzt alle vier Auswertungen von `booking_model`.
- Migration der Prozessfelder von der Wohnung an den Tenant. Weichen Wohnungen eines Vermieters voneinander ab, wird der häufigste Wert Standard und die Abweichung gemeldet (siehe B2).
- **Gespeicherter Verlauf** (Ereignisprotokoll). Bestehende Zeitstempel werden einmalig als Startereignisse übernommen.
- Zuständigkeitsschalter im Profil: Vertrag/Dokumente, Gastkommunikation, Zahlungseinzug, Mahnung, Storno/Erstattung, Kalenderpflege.
- **Oberfläche:** neue, einfache Einstellungsseite „So arbeite ich“ (Vermieterstandard) und „Abweichungen für dieses Portal“. Beide sind kurz, mit Klartext-Fragen statt Feldnamen.
**Bewusst noch nicht:** neue Vorgangsseite (Paket 2), automatische Portalvorgänge (Paket 4).
**Risiken:**
- `guest_id` nullable berührt alle Stellen, die `$booking->guest->…` lesen: Mails, PDFs, Tabellen, Exporte. Abhilfe: vorher alle Zugriffe ermitteln und gezielt absichern.
- Eine Fehlmigration der Einstellungen könnte das Verhalten bestehender Wohnungen ändern (z. B. automatische Angebote). Abhilfe: Trockenlauf mit Vorher/Nachher-Bericht je Vermieter.
**Abnahme:** §6, Paket 1.
### 5.3 Paket 2: Geführte Vorgangsbearbeitung (konkret)
**Fachliches Ziel:** Die Vermieterin sieht auf einen Blick, was vorliegt, was erledigt ist und was als Nächstes zu tun ist. Das System erledigt, was es darf, und fragt nur, wo es muss.
**Veränderungen:**
- Aktivitätenkatalog mit Anwendbarkeit, Voraussetzungen und Zuständen (§3.3). Bestehende Actions werden als Ausführung angebunden.
- **Automatiklauf** als Verallgemeinerung von `AutoOffer` und der Erinnerungs- und Zahlungs-Jobs:
- Er führt aus, was automatisch darf.
- Andernfalls erzeugt er eine Aufgabe in Alltagssprache (aus den heutigen „Blocker“-Texten).
- **Eine Liste „Zu erledigen“** als Startseite:
- Sie fasst Vorgangsaufgaben (heute `BookingTask`), Kanalaufgaben (heute `ChannelTask`) und klärungsbedürftige Belegungen zusammen.
- Technische Systemmeldungen (Sync-Fehler) erscheinen dort nur, wenn eine Handlung möglich ist; sonst stehen sie im Expertenmodus.
- Ob die Tabellen technisch zusammengelegt oder nur gemeinsam angezeigt werden, entscheidet der Agent; die fachliche Anforderung ist **eine** Liste.
- **Neue Vorgangsseite** nach §4.1: Stand in einem Satz, „Als Nächstes“, Zeitleiste aus dem Verlauf, Bereiche Gast / Preis & Zahlungen / Dokumente / Kalender & Portale, Umschalter „automatisch / ich gebe frei“. Kontextabhängige Knöpfe ersetzen die 17 Kopfaktionen.
- **Neu-Dialog** mit vier Einstiegen (Anfrage, Buchung von einem Portal, Eigene Nutzung/Besuch, Sperre). In diesem Paket wird er zunächst für Anfragen und die manuelle Portalbuchung umgesetzt (die Logik aus `RecordPortalBooking` wandert hierher, der Formularabschnitt „Buchungsweg“ entfällt).
- Ein Klick im Kalender führt immer auf den Vorgang (bzw. auf die Klärungsaufgabe bei unklaren Einträgen).
- Die einfache Ansicht blendet technische Abschnitte auf den Seiten aus, nicht nur Menüpunkte.
- Einfaches Menü nach §4.1.
**Risiken:**
- Größter Eingriff in die gewohnte Oberfläche. Abhilfe: Die alte Akte bleibt im Expertenmenü erreichbar, bis die Abnahme mit der Vermieterin erfolgt ist.
- Die Automatik darf keine doppelten Mails erzeugen. Abhilfe: bestehende Idempotenz (Zeitstempel je Aktivität) beibehalten.
### 5.4 Paket 3: Zusammenstellung und Dokumente
**Ziel:** Vor jedem Dokument sieht und ändert man dasselbe Bild, und das richtige Dokument kommt automatisch.
**Veränderungen:**
- Die Zusammenstellung nach §4.5 löst den Angebotsdialog ab.
- Dokumentarten: bindendes Angebot, Auskunft unter Vorbehalt (Text folgt in Paket 7), Buchungsbestätigung eigener Buchung, **Buchungsdokumentation extern verbindlich** (ohne Annahmelink, E-004), A6-Aufenthaltsbestätigung, interne Bestätigung.
- Vorlagen und Anlagen werden über das Profil je Dokumentart gewählt; `ConfirmBooking` wählt nicht mehr still.
- Vorlagenkonflikt-Hinweis für extern verbindliche Buchungen.
**Abhängigkeit:** Die Texte der neuen Dokumentarten liefert der Betreiber (§8.4). Bis dahin gibt es neutrale Arbeitsfassungen, die im Live-Modus gesperrt sind (wie heute bei `contractTextsReleased()`).
### 5.5 Paket 4: Ein Eingang für alle Kanäle
**Ziel:** Externe Direktbuchungen und Portalanfragen werden ohne Umweg zum Vorgang mit dem richtigen Profil, und Portalereignisse erreichen den Vorgang.
**Veränderungen:**
- Sicher erkannte Reservierungen (Portal-Mail oder iCal-Regel mit Ergebnis „Buchung“) erzeugen **automatisch** einen Vorgang (Logik aus `OpenPortalFile`).
- **Dublettenregel:** Portalreferenz, dann Kanal mit Zeitraum, dann vorhandene Spiegelung. Unsichere Fälle erzeugen eine Klärungsaufgabe.
- Pro Kanal gibt es einen Schalter „Vorgänge automatisch anlegen“ mit vorgeschaltetem **Beobachtungsmodus** (protokolliert nur, was entstehen würde).
- Der Portalpreis wird als „Gesamtpreis laut Portal“ mit Quelle übernommen; die `PortalPrice`-Zerlegung entfällt.
- **Portalstorno oder -änderung** (Mail-Typ Storno, verschwundener iCal-Eintrag eines gebuchten Vorgangs) erzeugt eine Aufgabe am Vorgang. Es gibt keine automatische Stornierung (E-019).
- **Sperrnachweis in drei Stufen** für Kanalaufgaben: veranlasst / im Zielportal gesehen (optional mit Notiz oder Bild) / wirksam bestätigt (E-018).
- Bestehende verknüpfte Portalbelegungen ohne Vorgang werden per Befehl mit Trockenlauf nachgezogen.
- `AssignOccupationGuest`, „Akte anlegen“ und die Liste „Ungeklärte Belegungen“ als eigene Seite entfallen.
**Risiken:** Eingriff in den 5-Minuten-Sync (siehe §7).
### 5.6 Paket 5: Änderung, Storno, kontrollierter Abbruch
**Ziel:** Jeder Vorgang lässt sich nachvollziehbar ändern und beenden, mit den richtigen Folgen und ohne Verbindlichkeiten zu ignorieren.
**Veränderungen:**
- Aktion „Ändern“ für gebuchte Vorgänge nach §4.6, mit Folgenvorschau: Kalender, Portalsperren, Preis, Zahlungsplan, neue Bestätigung.
- Aktion „Beenden“ mit der Weichenlogik aus §4.6.
- Der bestehende Stornoweg (`CancelBooking`, `Cancellation`, Stornoregel-Snapshot) wird um Ursache, Ausführenden und „wirksam ab“ ergänzt und für A3–A5 um die Portalaufgabe.
- `SetBookingStatus` wandert in den Expertenmodus und verlangt eine Begründung.
- No-show, Verlängerung und vorzeitige Abreise (X08) laufen als Sonderfälle von „Ändern“.
### 5.7 Paket 6: A6 im Vorgang
**Ziel:** Eigennutzung, private Überlassung und Wartung laufen im selben Vorgang, mit genau so vielen Schritten wie nötig.
**Veränderungen:**
- Neu-Einstiege „Eigene Nutzung / Besuch“ und „Sperre“ sowie ein Kalender-Schnellweg.
- Das A6-Profil schaltet Vertrag, Zahlungsmahnung, Bewertung und Marketing aus. Zahlung und Bestätigung sind optional.
- **Kurabgabe** als Leistung mit vom Vermieter gepflegtem Satz, nicht als Produktkonstante (Offene_Fragen; B1).
- Bestehende manuelle Sperren (`BlockedPeriod` mit Quelle manuell) werden per Migration mit Trockenlauf zu A6-Vorgängen. Exportfeeds und Kanalaufgaben bleiben unverändert wirksam.
### 5.8 Paket 7: Angebotsweg Hold 0 und Buchungswunsch
**Ziel:** E-026 und E-030 vollständig umsetzen.
**Veränderungen:**
- Bei Hold = 0 gibt es keine Reservierung und kein annehmbares Angebot. Stattdessen „Auskunft unter Vorbehalt“ mit signiertem Link **„Buchung anfragen“**, danach erneute Verfügbarkeits- und Kalenderprüfung (`CalendarClearance`) und Bestätigung automatisch oder per Freigabe.
- Bei Hold > 0 bleiben Angebotsfrist und Hold gleich lang, wie heute (P01: „dürfen nicht widersprüchlich enden“).
- Der heutige Widerspruch „Vorreservierung aus, aber Angebot erzeugt Hold“ (L5) wird beseitigt.
- Konfliktfall: Der Buchungswunsch kommt, nachdem der Zeitraum anderweitig vergeben wurde. Der Gast bekommt eine freundliche Absage oder Alternativen; die Vermieterin erhält einen Hinweis.
### 5.9 Paket 8: Externe Beträge und Zahlungsstände
**Ziel:** K01 und [Preise_und_Zahlungen](Querschnitt/Preise_und_Zahlungen.md) abbilden, ohne Scheingenauigkeit.
**Veränderungen:**
- Je Vorgang beliebig viele **Beträge mit Art, Quelle und Zeitpunkt**: Gastgesamtbetrag laut Portal, Übernachtung, Rabatt, Sammelposten „Gebühren und Steuern“, Vermieterprovision, angekündigte Auszahlung, tatsächlicher Eingang. Die Art „ungeklärt“ ist zulässig, widersprüchliche Werte bleiben nebeneinander stehen.
- Zahlungen erhalten Art und Quelle: Gast an uns / Gast über Portal (laut Portal bezahlt) / Portal-Auszahlung / Erstattung.
- Die Anzeige „offener Betrag“ unterscheidet nach Zuständigkeit.
- Erleichterte manuelle Erfassung aus der Portalansicht („Werte aus FeWo-direkt eintragen“).
### 5.10 Paket 9: Aufenthalt und Abschluss
**Ziel:** P04 und P05 vollständig nach Profil.
**Veränderungen:**
- Anreisedaten-Prüfung als Aktivität: nötige Kontaktdaten, Anreisezeit.
- Lokale Leistungen und Dienstleisteraufgaben (Reinigung, Schlüssel, Wäsche) als Aktivitäten im Vorgang, keine Personaldisposition.
- Externe Versandzuständigkeit (Portal-Anreisenachricht) als „extern verantwortet“.
- Abschluss nach dem Gate aus Entscheidung B4. **Nachläufer** (offene Forderung, Schaden, Auszahlungsdifferenz) bleiben als zugewiesene Aufgaben am abgeschlossenen Vorgang.
- Bewertung nur, wo anwendbar.
- Melde- und Abgabefelder nach rechtlicher Klärung (Offene_Fragen).
---
## 6. Fachliche Abnahmekriterien
Abgenommen wird auf der **Testumgebung** mit nachgestellten Fällen. Jedes Kriterium beschreibt beobachtbares Verhalten. Die Kennungen werden in den Abnahmeprotokollen verwendet.
### Paket 1: Vorgangskern und Einstellungen
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 1.1 | Bestehende Vorgänge nach Migration | Alle Website-Buchungen, Angebote, Annahmen und Verträge sind unverändert abrufbar. Ein noch offener Angebotslink funktioniert weiter. Jeder Vorgang zeigt eine Vorgangsart. |
| 1.2 | Portalvorgang ohne Gastdaten | Ein FeWo-direkt-Vorgang ohne bekannte Gastdaten zeigt „Gast: noch nicht bekannt“. Es gibt keinen Gast „Gast (Portal)“ und keine geschätzte Personenzahl. |
| 1.3 | Vermieterstandard | Die Vermieterin stellt „Reservierung bei Anfragen: 48 Stunden“ und „Angebote: ich gebe frei“ ein. Eine neue Website-Anfrage reserviert 48 Stunden und wartet auf Freigabe. |
| 1.4 | Kanalabweichung, „nicht gesetzt“ | Für FeWo-direkt-Anfragen ist keine Haltefrist gesetzt: Es gelten die 48 Stunden des Standards. Wird für FeWo-direkt ausdrücklich „0“ gesetzt, gilt 0. Die Einstellungsseite zeigt beide Fälle unterscheidbar („wie Standard (48 h)“ gegenüber „0 Stunden“). |
| 1.5 | Gemischter Kanal | Ein Portal liefert eine Anfrage und eine verbindliche Buchung. Die Vorgänge bekommen unterschiedliche Vorgangsarten und unterschiedliche Vorlagen bzw. Zuständigkeiten. |
| 1.6 | Profil eingefroren | Eine Einstellung wird nach Entstehen eines Vorgangs geändert. Der bestehende Vorgang behält sein Verhalten, ein neuer Vorgang nutzt die neue Einstellung. Beides ist im Verlauf erkennbar. |
| 1.7 | Verlauf | Jede Statusänderung, jeder Versand und jede Übersteuerung erscheint im Verlauf mit wer/wann/warum, auch nach erneutem Laden und unabhängig von späteren Datenänderungen. |
### Paket 2: Geführte Vorgangsbearbeitung
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 2.1 | **A1 automatisch** | Website-Anfrage bei Modus automatisch und Hold > 0: Ohne Klick wird reserviert, das Angebot versendet und die Portalsperre angestoßen. Die Startseite zeigt keine Pflichtaufgabe, die Zeitleiste zeigt alle Schritte als „automatisch“. |
| 2.2 | **A1 manuell** | Dieselbe Anfrage bei „ich gebe frei“: Auf der Startseite erscheint „Angebot an … prüfen“. Ein Klick zeigt das fertig vorbereitete Angebot, ein weiterer Klick sendet es. |
| 2.3 | **Fehlende Daten** | Website-Anfrage ohne E-Mail-Adresse (telefonisch erfasst) bei Modus automatisch: Der Vorgang hält an, die Aufgabe heißt „E-Mail-Adresse von … fehlt“. Nach dem Eintragen fragt das System „Automatisch weitermachen?“. Bei „Ja“ geht das Angebot ohne weiteren Klick hinaus, bei „Nein“ erscheint eine Freigabe-Aufgabe. |
| 2.4 | **A1 durchgängig** | Anfrage → Angebot → Annahme durch den Gast → Bestätigung, Vertrag und Zahlungsplan → Anzahlungserinnerung → Anreise-Info → Abreise → Bewertungsanfrage. Alles läuft in **einem** Vorgang ohne Medienbruch und ist in der Zeitleiste nachvollziehbar. |
| 2.5 | **Vereinfachte Bedienung** | Eine Person ohne Systemkenntnis (Abnahme mit der Vermieterin) beantwortet für drei vorbereitete Vorgänge ohne Hilfe: Wie ist der Stand? Was muss ich als Nächstes tun? Was kann ich entscheiden? Auf der Vorgangsseite erscheinen nur anwendbare Knöpfe. |
| 2.6 | Eine Liste | Alle Handlungsbedarfe (Freigaben, fehlende Daten, Portal sperren, unklare Belegung) stehen in „Zu erledigen“. Es gibt keine weitere Liste, die man im Normalbetrieb kennen muss. |
| 2.7 | Expertenansicht | In der Expertenansicht zeigt dieselbe Vorgangsseite zusätzlich Kanalnachweise, Rohdaten und Versionen. In der einfachen Ansicht sind diese Abschnitte nicht sichtbar. |
| 2.8 | Neutralität | Kein automatischer Prüfauslöser verwendet Nationalität, Land oder Namen. Ein ausländischer Gast mit vollständigen Daten läuft identisch durch. |
### Paket 3: Zusammenstellung und Dokumente
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 3.1 | Vorschau vor Versand | Vor jedem Dokumentversand ist dasselbe Prüfbild sichtbar: Gast, Zeitraum, Preis mit Quelle, Leistungen, Stornoregel, Vorlage, Anlagen, PDF und Mail. Eine Anpassung (z. B. Nachlass) aktualisiert die Vorschau sofort. |
| 3.2 | Richtige Vorlage automatisch | Website-Anfrage → bindendes Angebot mit Annahmelink. Verbindliche FeWo-direkt-Buchung → Buchungsdokumentation **ohne** Annahmelink mit der für dieses Portal und diese Eingangsart hinterlegten Vorlage. Beides geschieht ohne manuelle Vorlagenwahl. |
| 3.3 | Kein stiller Pflichtenzuwachs | Enthält die Vorlage für eine extern verbindliche Buchung eine nicht nachgewiesene Gebühr, weist die Zusammenstellung darauf hin und verlangt eine bewusste Bestätigung. |
### Paket 4: Ein Eingang für alle Kanäle
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 4.1 | **A3 – Destination Solutions** | Eine verbindliche DS-Buchung wird manuell über „Buchung von einem Portal“ erfasst (Portal, Nummer, Zeitraum, Gesamtpreis, Gast). Ergebnis: ein Vorgang „gebucht“ ohne Angebot und ohne Annahme. Aufgaben: „Andere Portale sperren“, „Buchungsunterlagen senden“ (Vorschau, Paket 3), Zahlungsplan und -überwachung durch uns, Gastkommunikation über unsere Mails. Der Preis ist der Portalpreis. |
| 4.2 | **A4 – FeWo-direkt, Eingang** | Eine FeWo-direkt-Buchungsmail erzeugt ohne Klick einen Vorgang. Ein späterer iCal-Eintrag desselben Falls erzeugt **keinen** zweiten Vorgang. Die Zahlung steht als „über FeWo-direkt“ und erzeugt keine eigenen Mahnungen. Fehlende Adresse erzeugt nur dann eine Aufgabe, wenn ein eigenes Dokument sie braucht. |
| 4.3 | Unklare Belegung | Ein iCal-Eintrag ohne Erkennung wird kein Vorgang. Es entsteht eine Aufgabe „Was ist das?“; die Antwort „Buchung“ legt den Vorgang an. |
| 4.4 | Portalstorno | Eine FeWo-direkt-Stornomail oder ein verschwundener iCal-Eintrag zu einem gebuchten Vorgang erzeugt die Aufgabe „Stornierung prüfen“. Der Vorgang bleibt gebucht, bis die Vermieterin übernimmt. |
| 4.5 | Sperrnachweis | Bei Portalen mit manueller Sperrpflicht erscheint „In Portal X sperren“. Erledigen erlaubt „gesperrt“ und optional „im Portal geprüft“ mit Notiz. Die Vorgangsseite zeigt den Nachweisgrad. |
| 4.6 | Beobachtungsmodus | Mit aktivem Beobachtungsmodus entstehen keine Vorgänge, aber ein Bericht listet, welche entstanden wären. |
| 4.7 | **A2 – Portalanfrage** | Eine unverbindliche Portalanfrage mit unvollständigen Daten wird als Anfrage erfasst. Das System fordert gezielt die fehlenden Daten an und läuft danach wie A1 (2.1 bis 2.3). |
### Paket 5: Änderung, Storno, kontrollierter Abbruch
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 5.1 | **Änderung nach Buchung (A1)** | Der Gast verlängert um 2 Nächte. Die Vermieterin wählt „Ändern“ und sieht vor dem Speichern: Kalender frei, Mehrpreis, neue Restzahlung, Portalsperren werden angepasst, neue Bestätigung (Vorschau). Nach dem Speichern sind Kalender, Portalexport bzw. Sperraufgaben, Zahlungsplan und Verlauf aktualisiert. |
| 5.2 | Änderung extern (A4) | Eine Datumsänderung einer FeWo-direkt-Buchung wird mit dem Portalbetrag eingetragen. Es gibt keine eigene Neuberechnung, der Kalender ist angepasst. |
| 5.3 | **Kontrollierter Abbruch, unverbindlich** | „Beenden“ bei einem offenen Angebot führt zu „ohne Buchung beendet“. Die Reservierung wird freigegeben, eine Absage an den Gast ist optional, im Verlauf steht der Grund. |
| 5.4 | **Kontrollierter Abbruch, verbindlich** | „Beenden“ bei einer gebuchten eigenen Buchung öffnet den Stornoweg: Wer storniert (Gast/Vermieter)? Grund? Stornokosten laut eingefrorener Regel, Erstattungsaufgabe. Der Vorgang lässt sich **nicht** ohne diese Angaben in „unverbindlich“ zurücksetzen. |
| 5.5 | Abbruch extern | „Beenden“ bei einer A3/A4-Buchung erzeugt zusätzlich „Stornierung im Portal veranlassen bzw. prüfen“. Der Vorgang ist erst „storniert“, wenn die Wirksamkeit bestätigt ist. |
| 5.6 | Storno durch Gast | Die Stornierung über den bestehenden Gast-Stornolink landet als Aufgabe im selben Vorgang und nutzt denselben Stornoweg. |
### Paket 6: A6 im Vorgang
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 6.1 | **A6 – Private Überlassung** | Familienbesuch, 5 Nächte, 3 Personen, Miete 0, Wäschepaket, Kurabgabe. Ergebnis: ein Vorgang mit Gästen, Leistungen und Gesamtbetrag, optional eine Aufenthaltsbestätigung (Vorschau), Zahlung erfassbar. Portale werden gesperrt. Es gibt keinen Mietvertrag, keine Bewertungsanfrage, keine Marketingmail. |
| 6.2 | **A6 – Wartungssperre** | Ein Zeitraum wird im Kalender markiert, „Sperre – Wartung“ gewählt: ein Vorgang mit Grund und Zeitraum, ohne Gast, Dokument oder Zahlung, mit Portalsperre. Er lässt sich verlängern (Portale angepasst) und aufheben (Portale entsperrt, Verlauf „Sperre aufgehoben“, **keine** Stornierung). |
| 6.3 | Bestandsmigration | Alle bisherigen manuellen Sperren erscheinen nach der Migration als A6-Vorgänge mit unverändertem Zeitraum. Der Kalenderexport ist vor und nach der Migration identisch. |
### Paket 7: Angebotsweg Hold 0 und Buchungswunsch
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 7.1 | Hold 0 | Website-Anfrage bei Haltefrist 0: Der Kalender bleibt frei. Der Gast erhält eine „Auskunft unter Vorbehalt“ mit „Buchung anfragen“, ohne Annahmewirkung. |
| 7.2 | Buchungswunsch, automatisch | Der Gast klickt „Buchung anfragen“, der Zeitraum ist frei, der Modus ist automatisch: Die Buchung wird bestätigt, Vertrag und Zahlungsplan folgen. |
| 7.3 | Buchungswunsch, manuell | Dasselbe bei „ich gebe frei“: Es entsteht die Aufgabe „Buchungswunsch bestätigen?“. |
| 7.4 | Zwischenzeitlich belegt | Der Zeitraum wurde inzwischen anderweitig gebucht: Es entsteht keine Buchung, der Gast bekommt eine Absage oder Alternativen, die Vermieterin einen Hinweis. |
### Paket 8: Externe Beträge und Zahlungsstände
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 8.1 | **A4 – Preis- und Zahlungsangaben** | Das Referenzbeispiel R09 lässt sich exakt erfassen: 840,00 / −42,00 / 181,51 als ungeklärte Sammelposition / 979,51 Gast gesamt / −84,82 „an FeWo-direkt“ / 894,69 und 900,20 als zwei Auszahlungsangaben mit Differenzhinweis / Rate 390,61 laut Portal bezahlt / Rate 588,90 fällig. Es entsteht keine erfundene Tagespreis- oder Provisionsaufteilung, keine Summe wird doppelt gezählt. |
| 8.2 | Bezahlt ist nicht eingegangen | „Laut Portal bezahlt“ wird getrennt vom Bankeingang angezeigt. Offene Beträge erscheinen nur bei der Partei, die sie einzieht. |
### Paket 9: Aufenthalt und Abschluss
| ID | Szenario | Erwartetes Ergebnis |
|---|---|---|
| 9.1 | Anreise | Fehlende Anreisedaten erzeugen rechtzeitig vor Anreise eine Aufgabe. Bei extern verantworteter Portal-Anreisenachricht erscheint „durch Portal (angekündigt)“ statt einer eigenen Mail. |
| 9.2 | Abschluss mit Nachläufer | Nach der Abreise mit offener Restforderung wird der Vorgang „abgeschlossen“. Die Forderung bleibt als zugewiesene Aufgabe sichtbar. |
---
## 7. Risiken und Absicherung
### 7.1 Wesentliche Risiken
| Risiko | Betroffen | Bewertung | Absicherung |
|---|---|---|---|
| Bestehende Angebote, Annahmen und Verträge werden ungültig | Signierte Links, `offer_hash`, PDF-Hashes, Annahmeprotokolle | hoch, falls Snapshot-Felder verändert werden | Eingefrorene Felder **nie** umschreiben, nur ergänzen. Abnahme 1.1 mit echten offenen Angebotslinks. |
| Doppelte oder fehlende Vorgänge durch den automatischen Eingang | 5-Minuten-Sync, Portal-Mails | hoch | Beobachtungsmodus je Kanal, Dublettenregel, idempotente Erzeugung (Schlüssel Kanal und Referenz), Schalter zum Abschalten je Kanal. |
| Fehlmigration der Einstellungen ändert das Automatikverhalten | AutoOffer, Erinnerungen | mittel | Trockenlauf mit Vorher/Nachher-Bericht je Vermieter. Automatik nach der Migration erst aktivieren, wenn der Bericht bestätigt ist. |
| Nullable Gast und Beträge erzeugen Fehler in Mails, PDFs und Tabellen | alle Stellen mit `$booking->guest->…`, `total` | mittel | Zugriffe vorab inventarisieren, Charakterisierungstests der Mails und PDFs vor dem Umbau. |
| Doppelte Mails durch den neuen Automatiklauf | Gastkommunikation | mittel | Idempotenz je Aktivität (Zeitstempel bzw. Verlauf), Testmodus der Mailzustellung (`Settings`) auf der Testumgebung. |
| Kalenderexport verändert sich durch die A6-Migration | Portal-Feeds, Fremdportale | hoch (Doppelbuchungsrisiko) | Feed-Vergleich vor und nach der Migration (Abnahme 6.3), Migration außerhalb der Saisonspitze. |
| UI-Umstellung überfordert die Nutzerin | Betrieb | mittel | Alte Akte im Expertenmenü bis zur Abnahme 2.5. Kurze Einweisung mit der Vermieterin. |
| Parallele Agenten im selben Ordner | Repository | mittel | Paketweise Branches, Dateizuständigkeit laut [ZUSAMMENARBEIT](../ZUSAMMENARBEIT.md), nur eigene Dateien stagen. |
| Strato: Migrationen auf MySQL/MariaDB, Dateiquote | Deployment | niedrig–mittel | Additive Migrationen, Datenbanksicherung vor jedem Deploy mit Migration ([BETRIEB](../BETRIEB.md)), Rollback-Weg laut [DEPLOYMENT](../DEPLOYMENT.md). |
| Nebenläufigkeit bei Annahme und Buchungswunsch | Doppelbuchung eigener Wege | niedrig (E-027) | Bestehende Sperrlogik `lockForTransition` wiederverwenden. Echte MariaDB-Nebenläufigkeitstests fehlen weiterhin; einmalig vor Paket 7 prüfen. |
### 7.2 Vorgehen zur Absicherung
1. **Vor Paket 1:** Bestandsaufnahme der Produktionsdaten, nur lesend über `deploy.sh artisan`: Zahl der Vorgänge je Status, Platzhalter-Gäste, Portalbelegungen mit und ohne Vorgang, manuelle Sperren, abweichende Wohnungseinstellungen. **[Annahme]** Auf Produktion gibt es nur wenige echte Vorgänge; das ist zu bestätigen.
2. **Je Paket:**
- Charakterisierungstests der berührten Bestandsabläufe zuerst, dann der Umbau.
- Migrationen nur additiv; destruktive Schritte (Spalte löschen) frühestens ein Paket später.
- Jede Datenmigration bekommt einen Artisan-Befehl mit `--dry-run` und Bericht.
3. **Schalter:** Neue Automatiken (automatischer Portaleingang, Automatiklauf) sind je Vermieter oder Kanal abschaltbar.
4. **Abnahme auf Test:** Ein Szenario-Seeder (nur Test und lokal) stellt die Fälle R01, R07, R08 und R09 nach. Die Abnahmetabellen aus §6 dienen als Protokoll. Erst danach folgt der Deploy auf Produktion, nach Freigabe.
5. **STATUS.md** wird nach jedem Paket aktualisiert. Die normative Prozessarchitektur bleibt unverändert, solange der Betreiber keine Änderung freigibt.
---
## 8. Offene Entscheidungen
### 8.1 Fachliche Entscheidungen des Betreibers
Diese Fragen sind weder durch v0.10 noch durch den Auftrag beantwortet. Jede hat eine Empfehlung, die als Vorgabe gilt, falls keine andere Entscheidung kommt.
| ID | Frage | Empfehlung | Benötigt für |
|---|---|---|---|
| **B1** | **Kurabgabe:** Soll die Anwendung sie berechnen, oder wird sie als normale Leistung mit vom Vermieter gepflegtem Satz geführt, mit manueller Personenzahl und Befreiungen? | Als Leistung mit gepflegtem Satz je Person und Nacht; Befreiungen manuell. Keine rechtliche Berechnungslogik im MVP. | Paket 6 |
| **B2** | **Prozess-Einstellungen je Wohnung:** Dürfen Haltefrist, Modus usw. je Wohnung eines Vermieters abweichen? v0.10 sieht das ohne Entscheidung nicht vor. | Nein. Vermieterstandard plus Portalabweichung reicht für 1–3 Wohnungen. | Paket 1 (Migration) |
| **B3** | **Änderung nach Verbindlichkeit (A1/A2):** Reicht es, wenn die Vermieterin eine mit dem Gast vereinbarte Änderung einträgt und das System eine aktualisierte Bestätigung sendet, oder braucht jede Änderung eine erneute Annahme durch den Gast (neuer Annahmelink)? | Eintragen plus aktualisierte Bestätigung als Standard. Optional „Änderung vom Gast bestätigen lassen“ für Preiserhöhungen. Rechtlich prüfen lassen. | Paket 5 |
| **B4** | **Abschluss-Gate:** Wann gilt ein Vorgang als abgeschlossen? | Automatisch nach der Abreise (A6: nach Ende), wenn keine Pflichtaufgabe mehr offen ist. Offene Forderungen und Schäden laufen als Nachläufer weiter und verhindern den Abschluss nicht. | Paket 9 |
| **B5** | **Priorität Hold = 0:** Will ein aktueller Vermieter zeitnah mit Haltefrist 0 arbeiten? | Wenn nein, bleibt Paket 7 in Stufe 2 hinten; wenn ja, wird es direkt nach Paket 3 umgesetzt. | Reihenfolge |
### 8.2 Technische Entscheidungen, die der Coding-Agent selbst trifft
- `Booking` bleibt technischer Träger des Vorgangs, ohne neue Vorgangstabelle (§3.1).
- Vorgangsart, Eingangsart und Profil-Snapshot liegen am Vorgang. Der Resolver liegt in einem eigenen Namensraum (z. B. `app/Process`).
- „Nicht gesetzt“ ist `null`. Einstellungen mit Klartext-Labels und Anzeige des geerbten Werts.
- Aktivitätenkatalog im Code, keine konfigurierbare Engine. Gate-Ergebnisse werden abgeleitet.
- Ereignisprotokoll als eigene Tabelle; nur Ergänzung, kein Event-Sourcing.
- Ob `BookingTask`, `ChannelTask` und Systemmeldungen technisch zusammengelegt oder nur in einer gemeinsamen Liste angezeigt werden.
- Dublettenschlüssel für Portalvorgänge, Beobachtungsmodus, Umfang der Charakterisierungstests.
- Wann veraltete Spalten gelöscht werden (frühestens im Folgepaket nach erfolgreicher Migration).
### 8.3 Portalspezifische Konfigurationsfragen (erst bei der Kanaleinrichtung)
Diese Fragen blockieren den Plan nicht. Sie bestimmen nur die Profilwerte des jeweiligen Kanals; alle Pakete sind so ausgelegt, dass „unbekannt“ erlaubt ist.
| Frage (Offene_Fragen) | Wirkt auf |
|---|---|
| DS-01, DS-02, DS-06 (Stornobedingungen, Basis „Mietpreis“, Änderungsweg) | Stornoregel bzw. Vorlage im DS-Profil (Pakete 3, 5) |
| DS-03, DS-04 (Gastgebühren, Detailtiefe) | Erfassungsmaske „Buchung von einem Portal“, Betragsarten (Pakete 4, 8) |
| DS-05, FW-07 (Sperrnachweis, iCal-Verzug) | Nachweisstufen und Erinnerungsintervalle (Paket 4) |
| FW-01 (Bedingungen vor Buchung) | Vorlagenwahl und Konflikthinweis im FeWo-direkt-Profil (Paket 3) |
| FW-02 bis FW-04 (Gebühren, Auszahlung, Export) | Betragsarten und Zuordnung (Paket 8) |
| FW-05 (Storno und Änderung im Konto) | Portalaufgaben beim Storno (Paket 5) |
| FW-06 (Gästedaten) | Aktivität „Gastdaten ergänzen“ (Pakete 4, 9) |
| Pro Portal: Liefert der Kanal verbindliche Buchungen, Anfragen oder beides? Erkennt die iCal-Regel sicher? | Eingangsart-Profil, Schalter „Vorgänge automatisch anlegen“ (Paket 4) |
### 8.4 Zulieferungen (keine Entscheidungen, aber Voraussetzungen)
- Texte der neuen Dokumentarten (Paket 3, Paket 7): Auskunft unter Vorbehalt und Knopf „Buchung anfragen“, Buchungsdokumentation extern verbindlich, A6-Aufenthaltsbestätigung. Offene_Fragen sieht hierfür eine rechtliche Prüfung vor.
- Kurabgabesätze des Vermieters (Paket 6, falls B1 wie empfohlen).
- Zeit für eine Bedienprobe mit der Vermieterin (Abnahme 2.5).
### 8.5 Nicht geprüfte Annahmen
- **[Annahme]** Auf Produktion liegen nur wenige echte Vorgänge und Portalbelegungen. Prüfung über die Bestandsaufnahme in §7.2.
- **[Annahme]** Portal-Mails von FeWo-direkt erlauben eine sichere Unterscheidung „Buchung“ / „Anfrage“ / „Storno“. Heute erkennt `PortalEmailType` diese Typen; die Zuverlässigkeit an echten Mails ist im Beobachtungsmodus zu bestätigen.
- **[Annahme]** Destination Solutions liefert weder iCal noch maschinenlesbare Mails; der Eingang ist manuell (R08). Liefert DS doch Mails, kann ein Parser später ergänzt werden.
---
## 9. Empfohlener Einstieg
**Zuerst Paket 1, „Vorgangskern und Einstellungen“**, unmittelbar gefolgt von **Paket 2, „Geführte Vorgangsbearbeitung“**.
Begründung:
1. **Alles hängt daran.** Jede weitere Funktion braucht dieselben drei Dinge: einen Vorgang, der unbekannte Werte zulässt, die Vorgangsart und das wirksame Profil. Ohne Paket 1 würde jedes Folgepaket erneut eigene Weichen nach `booking_model` oder Platzhalter-Gäste bauen, also genau die Parallelstrukturen, die abgebaut werden sollen.
2. **Geringes Betriebsrisiko bei hoher Wirkung.** Paket 1 ändert kaum sichtbares Verhalten, die Migrationen sind additiv, und der Erfolg lässt sich mit den Kriterien 1.1–1.7 eindeutig prüfen. Damit eignet es sich als Einstieg, bevor Sync oder Oberfläche angefasst werden.
3. **Die Bedienung folgt sofort.** Paket 2 ist der erste für die Vermieterin sichtbare Fortschritt: eine Liste „Zu erledigen“, eine geführte Vorgangsseite, Automatik oder Freigabe. Es sollte direkt danach beauftragt werden, damit die neue Fachlogik nicht in der alten Oberfläche versickert.
Für Paket 1 ist keine Betreiberentscheidung erforderlich außer **B2** (Einstellungen je Wohnung); die Empfehlung „Nein“ gilt als Vorgabe. Die übrigen Entscheidungen B1, B3, B4 und B5 werden erst für spätere Pakete benötigt.
[Zur Startseite](README.md) · [Gültige Entscheidungen](Entscheidungen.md) · [Offene Prüfungen](Offene_Fragen.md)
@@ -64,7 +64,7 @@
@endif
@if (!$event['guest_assigned'] && $event['kind'] === 'reservation')<small>Gastzuordnung offen</small>@endif
@if ($event['needs_review'])<small>Klärung erforderlich</small>@endif
<small class="occupancy-open">{{ $event['record_type'] === 'booking' ? 'Akte öffnen →' : ($event['kind'] === 'block' ? 'Details →' : 'Akte anlegen →') }}</small>
<small class="occupancy-open">{{ $event['record_type'] === 'booking' ? 'Vorgang öffnen →' : ($event['kind'] === 'block' ? 'Details →' : 'Als Buchung übernehmen →') }}</small>
</a>
@endforeach
@foreach ($day['departures'] as $event)
@@ -76,7 +76,7 @@
<div class="occupancy-list">
<h2 style="font-size:1.1rem;font-weight:700">Alle Vorgänge dieses Zeitraums</h2>
<table>
<thead><tr><th>Zeitraum</th><th>Art / Status</th><th>Gast</th><th>Kanal / Quelle</th><th>Hinweise</th><th>Akte</th></tr></thead>
<thead><tr><th>Zeitraum</th><th>Art / Status</th><th>Gast</th><th>Kanal / Quelle</th><th>Hinweise</th><th>Vorgang</th></tr></thead>
<tbody>
@forelse ($calendar['rows'] as $event)
<tr>
@@ -95,7 +95,7 @@
@endif
</td>
<td>{{ $event['review_note'] ?? ($event['kind'] === 'block' ? $event['reason'] : null) }}@if ($event['representations'])<br>{{ $event['representations'] }} zugeordnete Kalenderdarstellung(en)@endif</td>
<td><x-filament::button tag="a" size="sm" :href="$event['url']">{{ $event['record_type'] === 'booking' ? 'Akte öffnen' : ($event['kind'] === 'block' ? 'Details' : 'Akte anlegen') }}</x-filament::button></td>
<td><x-filament::button tag="a" size="sm" :href="$event['url']">{{ $event['record_type'] === 'booking' ? 'Vorgang öffnen' : ($event['kind'] === 'block' ? 'Details' : 'Als Buchung übernehmen') }}</x-filament::button></td>
</tr>
@empty
<tr><td colspan="6">Keine Vorgänge in diesem Zeitraum.</td></tr>
@@ -0,0 +1,24 @@
<x-filament-widgets::widget>
<x-filament::section icon="heroicon-o-check-circle" :heading="'Zu erledigen'" :description="count($items) === 0 ? null : (count($items) === 1 ? 'Eine Sache wartet auf Sie.' : count($items).' Sachen warten auf Sie.')">
@if (count($items) === 0)
<p style="font-size:1.05rem">Alles erledigt – im Moment ist nichts zu tun.</p>
@else
<ul style="list-style:none;margin:0;padding:0">
@foreach ($items as $item)
<li style="display:flex;gap:1rem;align-items:center;justify-content:space-between;padding:.8rem 0;border-bottom:1px solid rgba(128,128,128,.2)">
<div style="min-width:0">
<div style="font-size:1.05rem;font-weight:600">
<x-filament::badge :color="$item['tone']" style="display:inline-flex;vertical-align:middle;margin-right:.4rem">{{ match ($item['tone']) { 'danger' => 'dringend', 'info' => 'Hinweis', default => 'zu tun' } }}</x-filament::badge>
{{ $item['title'] }}
</div>
@if ($item['detail'])
<div style="color:#6b7280;font-size:.9rem;margin-top:.15rem">{{ $item['detail'] }}</div>
@endif
</div>
<x-filament::button tag="a" :href="$item['url']" size="lg" :color="$item['tone'] === 'info' ? 'gray' : 'primary'">{{ $item['button'] }}</x-filament::button>
</li>
@endforeach
</ul>
@endif
</x-filament::section>
</x-filament-widgets::widget>
@@ -1,7 +1,7 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null">
# {{ $cancelled ? 'Buchung vom Gast storniert' : 'Stornierungswunsch eines Gastes' }}
**{{ $booking->guest->full_name }}** · Buchung **{{ $booking->reference }}** · {{ $booking->property->name }}<br>
**{{ $booking->guestName() }}** · Buchung **{{ $booking->reference }}** · {{ $booking->property->name }}<br>
**Zeitraum:** {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}<br>
**Gesamtpreis:** {{ \App\Support\Money::format($booking->total) }}, bezahlt {{ \App\Support\Money::format($booking->paidAmount()) }}
+4 -4
View File
@@ -53,10 +53,10 @@
</td>
<td>
<h2>Mieter</h2>
{{ $booking->guest->full_name }}<br>
@if ($booking->guest->street){{ $booking->guest->street }}<br>@endif
@if ($booking->guest->city){{ $booking->guest->postal_code }} {{ $booking->guest->city }}<br>@endif
{{ $booking->guest->email }}@if ($booking->guest->phone) · {{ $booking->guest->phone }}@endif
{{ $booking->guestName() }}<br>
@if ($booking->guest?->street){{ $booking->guest->street }}<br>@endif
@if ($booking->guest?->city){{ $booking->guest->postal_code }} {{ $booking->guest->city }}<br>@endif
{{ $booking->guest?->email }}@if ($booking->guest?->phone) · {{ $booking->guest->phone }}@endif
</td>
</tr>
</table>
+3 -2
View File
@@ -36,9 +36,10 @@ public function test_rentals_staff_starts_in_the_simple_mode_with_the_daily_menu
$this->assertSame(AdminMode::Simple, $user->adminMode());
$this->get(Dashboard::getUrl())
->assertOk()
->assertSee('Anfragen &amp; Buchungen', false)
->assertSee('Vorgänge')
->assertSee('Sperrzeiten')
->assertSee('Portal-Aufgaben')
->assertSee('Zu erledigen')
->assertDontSee('Portal-Aufgaben')
->assertSee('Verwaltung')
->assertDontSee('Kalenderabgleich')
->assertDontSee('Vertragsvorlagen')
+3 -4
View File
@@ -6,7 +6,6 @@
use App\Actions\CreateReservation;
use App\Actions\SendOffer;
use App\Enums\BookingStatus;
use App\Enums\OfferMode;
use App\Exceptions\ReservationException;
use App\Mail\NewReservation;
use App\Mail\OfferMade;
@@ -86,7 +85,7 @@ public function test_automatic_offer_can_be_accepted_end_to_end(): void
public function test_without_pre_reservation_a_request_blocks_nothing(): void
{
$this->property->update(['pre_reservation_enabled' => false]);
Settings::tenant()->update(['process_defaults' => ['pre_reservation' => false]]);
$first = $this->request();
$second = $this->request('other@example.org');
@@ -100,7 +99,7 @@ public function test_without_pre_reservation_a_request_blocks_nothing(): void
public function test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why(): void
{
$this->property->update(['offer_mode' => OfferMode::Automatic, 'pre_reservation_enabled' => false]);
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => false]]);
$booking = $this->request();
@@ -205,7 +204,7 @@ public function test_live_operation_needs_released_contract_texts_for_automatic_
private function automatic(): void
{
$this->property->update(['offer_mode' => OfferMode::Automatic]);
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
}
private function request(string $email = 'gast@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
+2 -2
View File
@@ -70,7 +70,7 @@ public function test_landlord_declines_without_notifying_the_guest(): void
$booking = Booking::factory()->for($this->property)->reserved()->create();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('decline', ['notify' => false]);
->callAction('end', ['reason' => 'Zeitraum passt nicht', 'notify' => false]);
$this->assertSame(BookingStatus::Declined, $booking->fresh()->status);
Mail::assertNotSent(BookingDeclined::class);
@@ -123,7 +123,7 @@ public function test_phone_booking_for_occupied_dates_is_refused(): void
'email' => 'peter@example.com',
])
->call('create')
->assertNotified('Buchung nicht möglich');
->assertNotified('Nicht möglich');
$this->assertSame(1, Booking::count());
}
+20 -17
View File
@@ -4,9 +4,11 @@
use App\Actions\CancelBooking;
use App\Actions\SendOffer;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CaseType;
use App\Filament\Resources\Bookings\Pages\ListBookings;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
@@ -18,12 +20,11 @@
use App\Models\Channel;
use App\Models\Property;
use App\Models\User;
use App\Support\BookingProgress;
use App\Process\CaseActivities;
use App\Support\Settings;
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\Mail;
use Illuminate\Support\Facades\Storage;
@@ -53,31 +54,33 @@ protected function setUp(): void
public function test_next_step_follows_the_state_of_the_booking(): void
{
$request = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']);
$this->assertSame('Anfrage prüfen', BookingProgress::next($request)['title']);
$this->assertSame('sendOffer', CaseActivities::next($request)?->action);
Mail::fake();
$offer = app(SendOffer::class)->handle($request);
$this->assertSame('Wartet auf den Gast', BookingProgress::next($offer)['title']);
$this->assertNull(CaseActivities::next($offer));
$this->assertStringContainsString('Angebot liegt beim Gast', CaseActivities::situation($offer));
$confirmed = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05', 'deposit_due_on' => '2026-10-25', 'balance_due_on' => '2026-11-20', 'total' => 100000, 'deposit' => 30000]);
$this->assertSame('Anzahlung offen', BookingProgress::next($confirmed)['title']);
$this->assertSame('resendConfirmation', CaseActivities::next($confirmed)?->action);
$this->travelTo(CarbonImmutable::parse('2026-12-02 12:00'));
$confirmed->update(['status' => BookingStatus::Paid, 'total' => 0, 'deposit' => 0]);
$this->assertSame('Gast ist vor Ort', BookingProgress::next($confirmed->fresh())['title']);
$this->assertContains('current', array_column(BookingProgress::steps($confirmed->fresh()), 'state'));
$this->assertStringContainsString('Gast ist vor Ort', CaseActivities::situation($confirmed->fresh()));
$this->assertSame(ActivityState::Waiting, collect(CaseActivities::for($confirmed->fresh()))->firstWhere('key', 'stay')->state);
}
public function test_portal_booking_is_recognised_without_payment_steps_and_asks_to_send_the_contract(): void
{
$portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking']);
$portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'process_overrides' => ['booking' => ['payments' => 'portal']]]);
$booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'import_channel_id' => $portal->id, 'source' => 'portal', 'arrival' => '2026-12-01', 'departure' => '2026-12-05']);
$this->assertSame(BookingProgress::PORTAL_BOOKING, BookingProgress::kind($booking));
$this->assertStringContainsString('FeWo-direkt', BookingProgress::kindLabel($booking));
$this->assertSame('Vertrag senden', BookingProgress::next($booking)['title']);
$this->assertContains('Zahlung', array_column(BookingProgress::steps($booking), 'label'));
$this->assertNotContains('Anzahlung', array_column(BookingProgress::steps($booking), 'label'));
$this->assertSame(CaseType::A4, $booking->caseType());
$this->assertStringContainsString('Gebucht über FeWo-direkt', CaseActivities::situation($booking));
$this->assertSame('resendConfirmation', CaseActivities::next($booking)?->action);
$keys = array_map(fn ($activity) => $activity->key, CaseActivities::for($booking));
$this->assertContains('payment', $keys);
$this->assertNotContains('deposit', $keys);
}
public function test_every_booking_mail_lands_in_the_communication_log_with_its_audience(): void
@@ -121,7 +124,7 @@ public function test_cancellation_without_guest_mail_and_the_admin_action_offer_
$this->actingAs(User::factory()->create());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('cancel')->arguments([]), ['notify_guest' => false, 'costs_task' => false])
->callAction('end', ['initiated_by' => 'landlord', 'reason' => 'Wasserschaden', 'notify' => false, 'costs_task' => false])
->assertNotified('Buchung storniert');
Mail::assertNotSent(BookingCancelled::class);
@@ -149,9 +152,9 @@ public function test_the_booking_page_shows_process_contract_tasks_and_mail_log(
$this->actingAs(User::factory()->create());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertSee('Nächster Schritt: Wartet auf den Gast')
->assertSee('Vertrag')
->assertSee('Angebot (PDF) Version 1');
->assertSee('Angebot liegt beim Gast')
->assertSee('Gast nimmt das Angebot an')
->assertSee('Angebot Version 1');
Livewire::test(MessagesRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class])->assertSuccessful();
}
+2 -2
View File
@@ -17,7 +17,7 @@
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Models\User;
use App\Support\BookingProgress;
use App\Process\CaseActivities;
use App\Support\CancellationCost;
use App\Support\SelfServiceLinks;
use Carbon\CarbonImmutable;
@@ -109,7 +109,7 @@ public function test_cancelling_records_the_cancellation_with_the_proposed_cost_
$this->assertSame(CancellationCost::rent($booking), $record->base_amount);
$this->assertSame($record->calculated_fee, $record->fee());
$this->assertStringContainsString('Vorschlag nach Stornoregel', BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->sole()->note);
$this->assertStringContainsString('Stornokosten', BookingProgress::next($booking->fresh())['text']);
$this->assertStringContainsString('Stornokosten', CaseActivities::next($booking->fresh())?->label);
}
public function test_guest_link_is_instant_only_while_the_rule_makes_it_free_and_shows_the_cost(): void
+223
View File
@@ -0,0 +1,223 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\SendOffer;
use App\Actions\TakeOverExternalBooking;
use App\Documents\OfferTerms;
use App\Enums\BookingStatus;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\BookingEvent;
use App\Models\Channel;
use App\Models\ContractTemplate;
use App\Models\Guest;
use App\Models\Property;
use App\Models\User;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
/**
* Package 1 of UMSETZUNGSPLAN_v0.10: one case for every occasion, unknown stays unknown, settings in levels
* (landlord → property → channel per intake kind → case), the profile frozen per case and a stored history.
*/
class CaseCoreTest extends TestCase
{
use RefreshDatabase;
private Property $property;
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();
Mail::fake();
Storage::fake('local');
}
/** 1.2 */
public function test_a_portal_booking_without_guest_data_stays_unknown_instead_of_getting_a_placeholder(): void
{
$portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking']);
$guestsBefore = Guest::query()->count();
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $portal, CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05'), ['portal_reference' => 'HA-1']);
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertNull($booking->guest_id);
$this->assertNull($booking->guests);
$this->assertNull($booking->total);
$this->assertNull($booking->quote);
$this->assertSame('Gast noch nicht bekannt', $booking->guestName());
$this->assertSame($guestsBefore, Guest::query()->count());
$this->assertSame(IntakeKind::Booking, $booking->intake);
$this->assertSame(CaseType::A3, $booking->case_type);
$this->assertSame(0, $booking->openAmount());
$this->assertFalse($booking->wantsPaymentTasks());
}
public function test_a_known_portal_price_is_taken_over_as_one_line_and_never_split(): void
{
$portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking']);
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $portal, CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05'), ['portal_total' => 97951, 'guests' => 2]);
$this->assertSame(97951, $booking->total);
$this->assertCount(1, $booking->quote['lines']);
$this->assertSame(97951, $booking->quote['lines'][0]['amount']);
$this->assertStringContainsString('laut Portal', $booking->quote['lines'][0]['label']);
}
/** 1.3 */
public function test_landlord_defaults_apply_to_a_new_request(): void
{
Settings::tenant()->update(['process_defaults' => ['hold_hours' => 24, 'processing' => 'manual']]);
$booking = $this->request();
$this->assertSame(BookingStatus::Reserved, $booking->status);
$this->assertTrue($booking->hold_expires_at->equalTo(now()->addHours(24)));
$this->assertSame(ProcessingMode::Manual, $booking->processingMode());
$this->assertSame(CaseType::A1, $booking->case_type);
}
/** 1.4 */
public function test_a_channel_value_that_is_not_set_inherits_and_a_set_value_wins_even_when_it_is_no(): void
{
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'pre_reservation' => true]]);
$inherits = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'process_overrides' => ['inquiry' => ['processing' => null]]]);
$deviates = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'process_overrides' => ['inquiry' => ['processing' => 'manual', 'pre_reservation' => '0']]]);
$settings = app(ProcessSettings::class);
$inherited = $settings->resolve($this->property, $inherits, IntakeKind::Inquiry);
$deviated = $settings->resolve($this->property, $deviates, IntakeKind::Inquiry);
$this->assertSame(ProcessingMode::Automatic, $inherited->processing());
$this->assertTrue($inherited->preReservation());
$this->assertSame('tenant', $inherited->source(ProcessSetting::Processing));
$this->assertSame(ProcessingMode::Manual, $deviated->processing());
$this->assertFalse($deviated->preReservation());
$this->assertSame('channel', $deviated->source(ProcessSetting::PreReservation));
}
public function test_a_property_deviation_sits_between_landlord_default_and_channel(): void
{
Settings::tenant()->update(['process_defaults' => ['hold_hours' => 48]]);
$this->property->update(['process_overrides' => ['hold_hours' => 12]]);
$this->assertSame(12, app(ProcessSettings::class)->resolve($this->property->fresh(), null, IntakeKind::Inquiry)->holdHours());
}
/** 1.5 */
public function test_one_mixed_portal_handles_requests_and_bindings_differently(): void
{
$inquiryTemplate = ContractTemplate::query()->create(['name' => 'Anfrage', 'terms' => '<p>A</p>']);
$bookingTemplate = ContractTemplate::query()->create(['name' => 'Portalbuchung', 'terms' => '<p>B</p>']);
$portal = Channel::factory()->for($this->property)->create(['booking_model' => 'mixed', 'process_overrides' => [
'inquiry' => ['contract_template_id' => $inquiryTemplate->id],
'booking' => ['contract_template_id' => $bookingTemplate->id, 'payments' => 'portal'],
]]);
$request = $this->request(channel: $portal);
$binding = app(TakeOverExternalBooking::class)->handle($this->property, $portal, CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14'));
$this->assertSame(CaseType::A2, $request->case_type);
$this->assertSame(CaseType::A4, $binding->case_type);
$this->assertSame('Anfrage', OfferTerms::templateFor($request)?->name);
$this->assertSame('Portalbuchung', OfferTerms::templateFor($binding)?->name);
$this->assertSame(Responsibility::Landlord, $request->process()->payments());
$this->assertSame(Responsibility::Portal, $binding->process()->payments());
}
/** 1.6 */
public function test_the_profile_is_frozen_with_the_case(): void
{
$before = $this->request();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'hold_hours' => 72]]);
$after = $this->request('zweite@example.org', '2026-12-01', '2026-12-04');
$this->assertSame(ProcessingMode::Manual, $before->fresh()->processingMode());
$this->assertSame(48, $before->fresh()->process()->holdHours());
$this->assertSame(72, $after->process()->holdHours());
$before->fresh()->update(['processing_mode' => ProcessingMode::Automatic]);
$this->assertSame(ProcessingMode::Automatic, $before->fresh()->processingMode());
$this->assertTrue(BookingEvent::query()->where('booking_id', $before->id)->where('type', 'mode')->exists());
}
/** 1.7 */
public function test_the_history_is_stored_and_does_not_change_with_the_case(): void
{
$booking = $this->request();
$this->actingAs(User::factory()->create(['name' => 'Ingrid']));
app(SendOffer::class)->handle($booking);
$summaries = $booking->events()->pluck('summary')->all();
$this->assertStringStartsWith('Vorgang angelegt', $summaries[0]);
$this->assertContains('Angebot Version 1 gesendet, gültig bis 24.10.2026, 10:00 Uhr', $summaries);
$this->assertSame('Ingrid', $booking->events()->where('type', 'offer')->value('actor'));
$booking->fresh()->update(['offer_version' => 0, 'offer_sent_at' => null]);
$this->assertContains('Angebot Version 1 gesendet, gültig bis 24.10.2026, 10:00 Uhr', $booking->events()->pluck('summary')->all());
}
/** 1.1 */
public function test_the_migration_keeps_behaviour_of_existing_cases_and_differing_properties(): void
{
$second = Property::factory()->create(['tenant_id' => $this->property->tenant_id, 'hold_hours' => 24, 'offer_mode' => 'manual']);
$this->property->update(['hold_hours' => 48, 'offer_mode' => 'manual']);
$portal = Channel::factory()->for($this->property)->create(['booking_model' => 'portal_booking', 'payment_tasks_reservation' => false]);
$placeholder = Guest::query()->create(['first_name' => 'Gast', 'last_name' => '(FeWo-direkt)', 'email' => '']);
$legacy = Booking::factory()->for($this->property)->create(['import_channel_id' => $portal->id, 'source' => 'portal', 'guest_id' => $placeholder->id, 'offer_hash' => 'abc', 'offer_version' => 2]);
DB::table('bookings')->update(['intake' => null, 'case_type' => null, 'profile' => null]);
DB::table('booking_events')->delete();
DB::table('tenants')->update(['process_defaults' => null]);
(require database_path('migrations/2026_11_01_090100_move_process_settings_and_backfill_cases.php'))->up();
$tenant = Settings::tenant()->fresh();
$this->assertSame('manual', $tenant->process_defaults['processing']);
$this->assertArrayNotHasKey('hold_hours', $tenant->process_defaults);
$this->assertSame(48, $this->property->fresh()->process_overrides['hold_hours']);
$this->assertSame(24, $second->fresh()->process_overrides['hold_hours']);
$this->assertSame(24, app(ProcessSettings::class)->resolve($second->fresh(), null, IntakeKind::Inquiry)->holdHours());
$legacy = $legacy->fresh();
$this->assertSame(CaseType::A4, $legacy->case_type);
$this->assertSame('migration', $legacy->process()->origin);
$this->assertFalse($legacy->wantsPaymentTasks());
$this->assertSame('abc', $legacy->offer_hash);
$this->assertSame(2, $legacy->offer_version);
$this->assertNull($legacy->guest_id);
$this->assertNull(Guest::query()->find($placeholder->id));
$this->assertTrue($legacy->events()->exists());
}
private function request(string $email = 'gast@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10', ?Channel $channel = null): 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],
sendMails: false,
originChannel: $channel,
);
}
}
+2 -3
View File
@@ -95,8 +95,7 @@ public function test_portal_reservation_uses_the_reservation_template_and_a_conf
$reservation = $this->template('FeWo-direkt', '<p>PORTAL-VERTRAG {{ mieter }}</p>', null, null);
$portal = Channel::factory()->for($this->property)->create([
'booking_model' => 'portal_booking',
'contract_template_id' => $inquiry->id,
'contract_template_reservation_id' => $reservation->id,
'process_overrides' => ['inquiry' => ['contract_template_id' => $inquiry->id], 'booking' => ['contract_template_id' => $reservation->id, 'payments' => 'portal']],
]);
$booking = $this->booking(['import_channel_id' => $portal->id, 'source' => 'portal']);
@@ -109,7 +108,7 @@ public function test_portal_reservation_uses_the_reservation_template_and_a_conf
Storage::disk('local')->assertExists($booking->contract_path);
Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => ! str_contains($mail->render(), 'überweisen'));
$inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'contract_template_id' => $inquiry->id, 'contract_template_reservation_id' => $reservation->id]);
$inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'process_overrides' => ['inquiry' => ['contract_template_id' => $inquiry->id], 'booking' => ['contract_template_id' => $reservation->id]]]);
$this->assertSame($inquiry->id, OfferTerms::templateFor($this->booking(['import_channel_id' => $inquiryPortal->id, 'source' => 'portal', 'arrival' => '2026-12-01', 'departure' => '2026-12-03']))->id);
}
+1 -1
View File
@@ -62,7 +62,7 @@ public function test_default_order_is_explicit_choice_then_portal_then_property(
$propertyDefault = $this->template('Direkt', ['terms' => '<p>DIREKT</p>']);
$portalDefault = $this->template('Portal', ['terms' => '<p>PORTAL</p>']);
$this->property->update(['contract_template_id' => $propertyDefault->id]);
$channel = Channel::factory()->for($this->property)->create(['contract_template_id' => $portalDefault->id]);
$channel = Channel::factory()->for($this->property)->create(['process_overrides' => ['booking' => ['contract_template_id' => $portalDefault->id]]]);
$direct = $this->offer();
$viaPortal = $this->offer([], ['import_channel_id' => $channel->id, 'arrival' => '2026-12-01', 'departure' => '2026-12-04']);
+259
View File
@@ -0,0 +1,259 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\ProvideGuestContact;
use App\Enums\AdminMode;
use App\Enums\BookingStatus;
use App\Enums\ProcessingMode;
use App\Filament\Pages\HandlingSettings;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Filament\Widgets\WorkListWidget;
use App\Mail\OfferMade;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\InboxMessage;
use App\Models\Property;
use App\Models\User;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\WorkList;
use App\Support\Content;
use App\Support\Settings;
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 Livewire\Livewire;
use Tests\TestCase;
/**
* Package 2 of UMSETZUNGSPLAN_v0.10: the work list, the guided case page, automatic or manual handling, continuing
* after a stop and ending a case without bypassing obligations.
*/
class GuidedCaseHandlingTest extends TestCase
{
use RefreshDatabase;
private Property $property;
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();
Mail::fake();
Storage::fake('local');
Http::fake(['*' => Http::response('', 500)]);
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
/** 2.1 */
public function test_an_automatic_request_gets_its_offer_without_a_click_and_leaves_nothing_to_do(): void
{
$this->releaseContractTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
$booking = $this->request(sendMails: true);
$this->assertSame(BookingStatus::OfferSent, $booking->status);
Mail::assertSent(OfferMade::class);
$this->assertNull(CaseActivities::next($booking));
$this->assertSame([], WorkList::items());
}
/** 2.2 */
public function test_a_manual_request_is_prepared_and_waits_for_release_in_the_work_list(): void
{
$booking = $this->request();
$this->assertSame(BookingStatus::Reserved, $booking->status);
$items = WorkList::items();
$this->assertCount(1, $items);
$this->assertSame('Angebot prüfen und senden', $items[0]['title']);
$this->assertStringContainsString('Gesa Gast', $items[0]['detail']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertSee('Angebot prüfen und senden')
->assertSee('Sie geben jeden Schritt selbst frei')
->callAction(TestAction::make('sendOffer')->arguments([]))
->assertNotified('Angebot gesendet');
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
$this->assertSame('Ingrid', $booking->events()->where('type', 'offer')->value('actor'));
}
/** 2.3 */
public function test_missing_data_stops_the_case_with_a_task_and_it_continues_automatically_afterwards(): void
{
$this->releaseContractTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
Livewire::test(CreateBooking::class)
->fillForm([
'kind' => BookingForm::INQUIRY, 'property_id' => $this->property->id, 'guests' => 2,
'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'first_name' => 'Paul', 'last_name' => 'Telefon', 'send_mails' => true,
])
->call('create')
->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame(BookingStatus::Reserved, $booking->status);
$this->assertSame('provideContact', CaseActivities::next($booking)?->action);
$this->assertSame('E-Mail-Adresse des Gastes eintragen', WorkList::items()[0]['title']);
Mail::assertNotSent(OfferMade::class);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Paul', 'last_name' => 'Telefon', 'email' => 'paul@example.org'], 'process' => ProvideGuestContact::AUTOMATIC, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert, Angebot gesendet');
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
Mail::assertSent(OfferMade::class, 1);
}
public function test_after_completing_a_task_the_landlord_may_keep_releasing_by_hand(): void
{
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
$booking = $this->request(email: '');
app(ProvideGuestContact::class)->handle($booking, ['email' => 'gesa@example.org'], ProvideGuestContact::MANUAL);
$this->assertSame(BookingStatus::Reserved, $booking->fresh()->status);
$this->assertSame('sendOffer', CaseActivities::next($booking->fresh())?->action);
Mail::assertNotSent(OfferMade::class);
}
public function test_the_handling_of_one_case_can_be_switched_and_is_recorded(): void
{
$booking = $this->request();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('automation', ['mode' => ProcessingMode::Automatic->value]);
$this->assertSame(ProcessingMode::Automatic, $booking->fresh()->processing_mode);
$this->assertStringContainsString('Automatisch', $booking->events()->where('type', 'mode')->value('summary'));
}
/** 2.5 / 2.6 */
public function test_the_work_list_brings_everything_to_do_into_one_list(): void
{
$this->request();
$portal = Channel::factory()->for($this->property)->create(['name' => 'Ostsee-Portal']);
ChannelTask::factory()->for($portal)->create(['starts_on' => '2026-12-01', 'ends_on' => '2026-12-05']);
BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $portal->id, 'source' => 'channel', 'external_uid' => 'x1', 'starts_on' => '2026-12-20', 'ends_on' => '2026-12-22', 'needs_review' => true]);
InboxMessage::factory()->create(['subject' => 'Angebot nicht zugestellt']);
$titles = array_column(WorkList::items(), 'title');
$this->assertContains('Angebot prüfen und senden', $titles);
$this->assertContains('In Ostsee-Portal sperren', $titles);
$this->assertContains('Unbekannte Belegung von Ostsee-Portal – was ist das?', $titles);
$this->assertContains('Angebot nicht zugestellt', $titles);
Livewire::test(WorkListWidget::class)->assertSee('In Ostsee-Portal sperren')->assertSee('Vorgang öffnen');
}
/** 2.5 */
public function test_the_case_page_shows_the_state_the_next_step_and_only_fitting_buttons(): void
{
$booking = $this->request();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertSee('Anfrage über die Webseite')
->assertSee('Zeitraum reserviert bis')
->assertSee('Als Nächstes')
->assertActionVisible('sendOffer')
->assertActionVisible('end')
->assertActionHidden('resendConfirmation')
->assertActionHidden('portalPrice')
->assertDontSee('Technische Angaben')
->assertDontSee('Status von Hand ändern');
}
/** 2.7 */
public function test_the_expert_view_shows_technical_details_on_the_same_page(): void
{
$booking = $this->request();
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertSee('Technische Angaben')
->assertSee('Abwicklungsprofil (eingefroren)')
->assertSee('Grundeinstellung');
}
/** 2.8 */
public function test_nationality_is_never_a_reason_to_stop(): void
{
$this->releaseContractTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
$foreign = app(CreateReservation::class)->handle(
$this->property->fresh(),
new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2),
['first_name' => 'Ayşe', 'last_name' => 'Yılmaz', 'email' => 'ayse@example.com.tr', 'country' => 'TR', 'city' => 'İzmir'],
);
$this->assertSame(BookingStatus::OfferSent, $foreign->status);
}
public function test_ending_a_request_needs_a_reason_and_ends_it_without_booking(): void
{
$booking = $this->request();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['reason' => '', 'notify' => false])
->assertHasFormErrors(['reason' => 'required']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['reason' => 'Hund nicht erlaubt', 'notify' => false])
->assertNotified('Vorgang beendet');
$this->assertSame(BookingStatus::Declined, $booking->fresh()->status);
$this->assertSame(0, Booking::query()->occupying()->count());
$this->assertSame('Hund nicht erlaubt', $booking->events()->where('type', 'status')->value('reason'));
}
public function test_the_landlord_sets_defaults_on_one_page_and_a_portal_deviates_per_intake(): void
{
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(HandlingSettings::class)
->fillForm(['processing' => 'automatic', 'hold_hours' => 24, 'pre_reservation' => null])
->call('save')
->assertNotified('Gespeichert');
$this->assertSame(['processing' => 'automatic', 'hold_hours' => 24], Settings::tenant()->fresh()->process_defaults);
}
private function request(string $email = 'gesa@example.org', bool $sendMails = false): Booking
{
return app(CreateReservation::class)->handle(
$this->property->fresh(),
new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2),
['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email],
sendMails: $sendMails,
);
}
/**
* Automatic offers wait for released contract texts in live mode; tests run in test mode, but the texts are set as
* a real landlord would have them.
*/
private function releaseContractTexts(): void
{
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']);
}
}
+107 -72
View File
@@ -4,26 +4,31 @@
use App\Actions\OpenPortalFile;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPortalBooking;
use App\Actions\ResolveChannelOccupation;
use App\Actions\SetBookingStatus;
use App\Actions\TakeOverExternalBooking;
use App\Availability\AvailabilityChecker;
use App\Enums\AdminMode;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\CaseType;
use App\Enums\ChannelBookingModel;
use App\Enums\OccupationKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ListBookings;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation;
use App\Mail\BookingConfirmed;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Models\User;
use App\Pricing\StayRequest;
use App\Support\BookingProgress;
use App\Process\CaseActivities;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
@@ -35,8 +40,9 @@
use Tests\TestCase;
/**
* Portal bookings entered without contact data, the contract process that follows (automatic or by hand),
* manual status changes, the archive and the clarification of portal occupations.
* Bookings already binding on a portal (A3–A5): one way to take them over – entered by hand or found in the portal
* calendar –, the documents that follow (automatic or released by hand), manual status corrections, ending, the
* archive and the clarification of portal occupations.
*/
class PortalBookingTest extends TestCase
{
@@ -59,97 +65,107 @@ protected function setUp(): void
$this->withoutVite();
}
public function test_a_portal_booking_without_contact_data_occupies_the_dates_but_creates_no_contract(): void
public function test_a_binding_portal_booking_is_taken_over_without_offer_acceptance_or_contract(): void
{
$booking = $this->record(RecordPortalBooking::CONFIRM, total: 123400, reference: 'HA-123');
$booking = $this->takeOver(total: 123400, reference: 'HA-123', guest: ['first_name' => 'Erika', 'last_name' => 'Muster']);
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertSame(CaseType::A3, $booking->case_type);
$this->assertSame($this->portal->id, $booking->origin_channel_id);
$this->assertSame('HA-123', $booking->portal_reference);
$this->assertSame(123400, $booking->total);
$this->assertSame(0, $booking->offer_version);
$this->assertSame('', $booking->guest->email);
$this->assertNull($booking->contract_path);
$this->assertSame(BookingProgress::PORTAL_BOOKING, BookingProgress::kind($booking));
$this->assertSame('Kontaktdaten fehlen', BookingProgress::next($booking)['title']);
$this->assertSame('provideContact', CaseActivities::next($booking)?->action);
Mail::assertNothingSent();
}
public function test_an_immediate_contract_needs_the_email_address(): void
public function test_entering_the_contact_data_can_send_the_documents_automatically(): void
{
$this->expectException(ReservationException::class);
$booking = $this->takeOver(total: 50000);
$this->record(RecordPortalBooking::CONTRACT);
}
public function test_entering_the_contact_data_can_start_the_contract_automatically(): void
{
$booking = $this->record(RecordPortalBooking::CONFIRM);
$message = app(ProvideGuestContact::class)->handle($booking, ['email' => 'Gast@Example.test', 'street' => 'Hauptstr. 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn'], ProvideGuestContact::AUTOMATIC, guestConfirmed: true);
$message = app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'Gast@Example.test', 'street' => 'Hauptstr. 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn'], ProvideGuestContact::AUTOMATIC, guestConfirmed: true);
$booking->refresh();
$this->assertSame('Kontaktdaten gespeichert, Vertrag gesendet', $message);
$this->assertSame('gast@example.test', $booking->guest->email);
$this->assertNotNull($booking->contract_path);
$this->assertNotNull($booking->guest_confirmed_at);
$this->assertSame(ProcessingMode::Automatic, $booking->processing_mode);
Mail::assertSent(BookingConfirmed::class, 1);
}
public function test_entering_the_contact_data_by_hand_sends_nothing(): void
public function test_automatic_documents_wait_for_the_portal_price(): void
{
$booking = $this->record(RecordPortalBooking::CONFIRM);
$booking = $this->takeOver();
app(ProvideGuestContact::class)->handle($booking, ['email' => 'gast@example.test'], ProvideGuestContact::MANUAL);
$this->expectException(ReservationException::class);
$this->expectExceptionMessage('Gesamtpreis');
app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'gast@example.test'], ProvideGuestContact::AUTOMATIC);
}
public function test_entering_the_contact_data_by_hand_sends_nothing_and_the_documents_become_the_next_step(): void
{
$booking = $this->takeOver(total: 50000);
app(ProvideGuestContact::class)->handle($booking, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'gast@example.test'], ProvideGuestContact::MANUAL);
$this->assertNull($booking->fresh()->contract_path);
$this->assertSame('Vertrag senden', BookingProgress::next($booking->fresh())['title']);
$this->assertSame('resendConfirmation', CaseActivities::next($booking->fresh())?->action);
Mail::assertNothingSent();
}
public function test_a_recorded_request_stays_open_and_automatic_continuation_needs_an_email(): void
{
$booking = $this->record(RecordPortalBooking::RECORD);
$this->assertSame(BookingStatus::Reserved, $booking->status);
$this->expectException(ReservationException::class);
app(ProvideGuestContact::class)->handle($booking, ['phone' => '0123'], ProvideGuestContact::AUTOMATIC);
}
public function test_the_booking_form_records_a_portal_booking_and_the_page_offers_the_contact_actions(): void
public function test_the_new_dialog_takes_over_a_portal_booking_and_the_page_leads_to_the_contact_data(): void
{
$this->actingAs(User::factory()->create());
Livewire::test(CreateBooking::class)
->fillForm([
'property_id' => $this->property->id, 'guests' => 2, 'arrival' => '2026-11-07', 'departure' => '2026-11-10',
'channel_id' => $this->portal->id, 'portal_reference' => 'HA-9', 'portal_process' => RecordPortalBooking::CONFIRM,
'first_name' => 'Erika', 'last_name' => 'Muster',
'kind' => BookingForm::EXTERNAL,
'property_id' => $this->property->id, 'arrival' => '2026-11-07', 'departure' => '2026-11-10',
'channel_id' => $this->portal->id, 'portal_reference' => 'HA-9',
])
->call('create')
->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame('HA-9', $booking->portal_reference);
$this->assertNull($booking->guest_id);
$this->assertNull($booking->guests);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertActionVisible('requestContact')
->callAction('requestContact')
->assertSee('Name und Kontaktdaten des Gastes eintragen')
->assertSee('Gesamtpreis laut Portal eintragen')
->callAction(TestAction::make('requestContact')->arguments([]))
->assertNotified('Als angefragt vermerkt')
->callAction('provideContact', ['guest' => ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.test'], 'process' => ProvideGuestContact::MANUAL, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert');
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.test'], 'process' => ProvideGuestContact::MANUAL, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert')
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2])
->assertNotified('Preis gespeichert');
$this->assertNotNull($booking->fresh()->contact_requested_at);
$this->assertSame('erika@example.test', $booking->fresh()->guest->email);
$booking->refresh();
$this->assertNotNull($booking->contact_requested_at);
$this->assertSame('erika@example.test', $booking->guest->email);
$this->assertSame(97951, $booking->total);
$this->assertSame(2, $booking->guests);
}
public function test_status_can_be_changed_by_hand_with_a_reason_and_the_calendar_is_checked(): void
public function test_status_can_be_corrected_by_hand_but_a_binding_booking_never_falls_back_to_a_request(): void
{
$booking = $this->record(RecordPortalBooking::CONFIRM);
$booking = $this->takeOver();
$set = app(SetBookingStatus::class);
$set->handle($booking, BookingStatus::Paid, 'Zahlung über das Portal erhalten', 'Test');
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
$this->assertStringContainsString('Zahlung über das Portal erhalten', $booking->fresh()->internal_notes);
$this->assertSame('Von Hand gesetzt: Zahlung über das Portal erhalten', $booking->events()->where('type', 'status')->reorder()->latest('id')->value('reason'));
try {
$set->handle($booking->fresh(), BookingStatus::Reserved, 'zurück');
$this->fail('A binding booking must not become a request again.');
} catch (ReservationException) {
$this->assertSame(BookingStatus::Paid, $booking->fresh()->status);
}
$booking->update(['status' => BookingStatus::Expired]);
$other = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-11-08', 'departure' => '2026-11-09']);
@@ -168,12 +184,15 @@ public function test_status_can_be_changed_by_hand_with_a_reason_and_the_calenda
$set->handle($booking->fresh(), BookingStatus::Cancelled, 'nicht erlaubt');
}
public function test_the_manual_status_action_is_not_offered_for_the_own_website_process(): void
public function test_the_manual_status_action_is_an_expert_function_and_not_offered_for_the_website_process(): void
{
$own = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['source' => 'website', 'arrival' => '2026-11-07', 'departure' => '2026-11-10']);
$portal = $this->record(RecordPortalBooking::CONFIRM, arrival: '2026-12-01', departure: '2026-12-04');
$this->actingAs(User::factory()->create());
$portal = $this->takeOver(arrival: '2026-12-01', departure: '2026-12-04');
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Simple]));
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->assertDontSee('Status von Hand ändern');
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])->assertDontSee('Status von Hand ändern');
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->assertSee('Status von Hand ändern')
->callAction(TestAction::make('setStatus')->arguments([]), ['status' => BookingStatus::Paid->value, 'reason' => 'Portal zahlt aus'])
@@ -181,6 +200,21 @@ public function test_the_manual_status_action_is_not_offered_for_the_own_website
$this->assertSame(BookingStatus::Paid, $portal->fresh()->status);
}
public function test_ending_a_portal_booking_cancels_it_and_asks_to_cancel_on_the_portal_too(): void
{
$booking = $this->takeOver(total: 50000);
$this->actingAs(User::factory()->create());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Gast storniert im Portal', 'costs_task' => true])
->assertNotified('Buchung storniert');
$this->assertSame(BookingStatus::Cancelled, $booking->fresh()->status);
$this->assertTrue(BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PortalCancellation)->exists());
$this->assertSame('Gast storniert im Portal', $booking->events()->where('type', 'status')->reorder()->latest('id')->value('reason'));
$this->assertSame('Stornierung im Portal veranlassen bzw. prüfen', CaseActivities::next($booking->fresh())?->label);
}
public function test_archived_bookings_leave_the_list_but_keep_everything(): void
{
$past = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Completed, 'arrival' => '2026-09-01', 'departure' => '2026-09-05']);
@@ -195,7 +229,7 @@ public function test_archived_bookings_leave_the_list_but_keep_everything(): voi
public function test_the_list_filters_by_channel_period_and_missing_contact_data(): void
{
$portalBooking = $this->record(RecordPortalBooking::CONFIRM, arrival: '2026-12-01', departure: '2026-12-04');
$portalBooking = $this->takeOver(arrival: '2026-12-01', departure: '2026-12-04');
$own = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-11-07', 'departure' => '2026-11-10']);
$this->actingAs(User::factory()->create());
@@ -218,9 +252,9 @@ public function test_an_independent_occupation_with_a_booking_channel_is_no_long
$this->assertSame(OccupationKind::Reservation, $block->fresh()->occupation_kind);
}
public function test_a_portal_reservation_from_the_calendar_gets_a_booking_file_and_stays_occupied(): void
public function test_a_portal_reservation_from_the_calendar_becomes_one_case_and_stays_occupied(): void
{
$block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u2', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Reservation]);
$block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u2', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Reservation, 'ical_interpretation' => ['fields' => ['guest_first_name' => 'Mia']]]);
$checker = app(AvailabilityChecker::class);
$this->assertFalse($checker->isAvailable($this->property, CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14')));
@@ -228,8 +262,10 @@ public function test_a_portal_reservation_from_the_calendar_gets_a_booking_file_
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertSame($this->portal->id, $booking->origin_channel_id);
$this->assertSame(BookingProgress::PORTAL_BOOKING, BookingProgress::kind($booking));
$this->assertSame('', $booking->guest->email);
$this->assertSame(CaseType::A3, $booking->case_type);
$this->assertNull($booking->guest_id);
$this->assertNull($booking->total);
$this->assertStringContainsString('Name laut Kalender: Mia', $booking->internal_notes);
$this->assertTrue($block->fresh()->is_representation);
$this->assertSame($booking->id, $block->fresh()->linked_booking_id);
$this->assertFalse($checker->isAvailable($this->property, CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14')));
@@ -237,7 +273,7 @@ public function test_a_portal_reservation_from_the_calendar_gets_a_booking_file_
$this->assertSame(1, Booking::query()->count());
}
public function test_a_blocked_period_gets_no_booking_file(): void
public function test_a_blocked_period_does_not_become_a_booking(): void
{
$block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u3', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Block]);
@@ -245,7 +281,7 @@ public function test_a_blocked_period_gets_no_booking_file(): void
app(OpenPortalFile::class)->handle($block);
}
public function test_the_occupation_page_offers_the_file_and_leads_to_the_booking(): void
public function test_the_occupation_page_takes_the_reservation_over_and_leads_to_the_case(): void
{
$block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u4', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Reservation]);
$this->actingAs(User::factory()->create());
@@ -254,32 +290,31 @@ public function test_the_occupation_page_offers_the_file_and_leads_to_the_bookin
$booking = Booking::query()->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->assertSee('Ablauf: Meilensteine und Aktivitäten')
->assertSee('Bisheriger Verlauf')
->assertSee('Standardprozess')
->assertSee('Kontaktdaten eintragen');
->assertSee('Als Nächstes')
->assertSee('Ablauf')
->assertSee('Verlauf')
->assertSee('Gebucht über FeWo-direkt')
->assertSee('Gast noch nicht bekannt');
}
public function test_every_milestone_lists_its_activities_and_the_history_records_what_happened(): void
public function test_the_history_records_what_happened_with_its_actor(): void
{
$booking = $this->record(RecordPortalBooking::CONFIRM);
$booking = $this->takeOver();
$steps = collect(BookingProgress::steps($booking))->keyBy('label');
$this->assertFalse($steps['Gast & Kontaktdaten']['activities'][1]['done']);
$this->assertSame('Kontaktdaten eintragen', $steps['Gast & Kontaktdaten']['activities'][1]['action']);
$this->assertSame(['Vorgang angelegt (FeWo-direkt)', 'Buchung verbindlich bestätigt'], array_column(BookingProgress::history($booking), 'label'));
$this->assertSame(['Vorgang angelegt: Portalbuchung, Abwicklung bei uns (FeWo-direkt)', 'Beim Portal verbindlich gebucht – übernommen'], $booking->events()->pluck('summary')->all());
}
private function record(string $process, ?int $total = null, ?string $reference = null, string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
/**
* @param array<string, ?string>|null $guest
*/
private function takeOver(?int $total = null, ?string $reference = null, string $arrival = '2026-11-07', string $departure = '2026-11-10', ?array $guest = null): Booking
{
return app(RecordPortalBooking::class)->handle(
return app(TakeOverExternalBooking::class)->handle(
$this->property,
$this->portal,
new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2),
['first_name' => 'Erika', 'last_name' => 'Muster'],
$process,
$reference,
$total,
CarbonImmutable::parse($arrival),
CarbonImmutable::parse($departure),
['portal_total' => $total, 'portal_reference' => $reference, 'guest' => $guest],
);
}
}
+2 -2
View File
@@ -137,8 +137,8 @@ public function test_free_cancellation_window_switches_between_instant_and_reque
public function test_payment_tasks_follow_the_channel_policy(): void
{
$own = $this->confirmed();
$reservationPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'portal_booking', 'payment_tasks_reservation' => false]);
$inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'payment_tasks_inquiry' => true]);
$reservationPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'portal_booking', 'process_overrides' => ['booking' => ['payments' => 'portal']]]);
$inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'process_overrides' => ['inquiry' => ['payments' => 'landlord']]]);
$portalReservation = $this->confirmed('2026-12-10', '2026-12-14', ['import_channel_id' => $reservationPortal->id, 'source' => 'portal']);
$portalInquiry = $this->confirmed('2026-12-16', '2026-12-18', ['import_channel_id' => $inquiryPortal->id, 'source' => 'portal']);