Buchungsakte: Vorgang, naechster Schritt, Vertrag, Mailverlauf, Storno mit Mail, Archiv
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
- Buchungsseite zeigt Art des Vorgangs, Verlaufsleiste und den naechsten Schritt in Klartext - Vertragsabschnitt (Vorlage, Dokumente mit Pruefsumme, Zustellung) und Vertragstext-Ansicht - Reiter Aufgaben und Mailverlauf (jede Mail zur Buchung wird protokolliert) - Stornieren in der Verwaltung informiert Gast und Vermieter und legt eine Aufgabe fuer Stornokosten an - Stornierte/abgelehnte/abgelaufene Buchungen aus der Hauptliste, Filter Archiv anzeigen Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
89d569b6c8
commit
5baf39441f
15 files changed
+684
-7
No files matched your search
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingCancelled;
|
||||
use App\Mail\CancellationRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
|
||||
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
|
||||
* the cancellation costs is created. Open cancellation requests of the guest are completed.
|
||||
*/
|
||||
class CancelBooking
|
||||
{
|
||||
/**
|
||||
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung'): 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 {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||
}
|
||||
|
||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
||||
|
||||
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()]);
|
||||
|
||||
if ($costsTask) {
|
||||
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], ['status' => BookingTaskStatus::Open, 'due_on' => today()]);
|
||||
}
|
||||
});
|
||||
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
|
||||
return $this->notify($booking, $notifyGuest);
|
||||
}
|
||||
|
||||
private function notify(Booking $booking, bool $notifyGuest): bool
|
||||
{
|
||||
$informed = true;
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, cancelled: true));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Stornomitteilung an den Vermieter nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
|
||||
if ($notifyGuest) {
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, cancelled: true));
|
||||
} catch (Throwable $exception) {
|
||||
$informed = false;
|
||||
Log::warning('Stornomail an den Gast nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
|
||||
return $informed;
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ enum BookingTaskKind: string implements HasLabel
|
||||
case BalanceRequest = 'balance_request';
|
||||
case BalanceReminder = 'balance_reminder';
|
||||
case CancellationRequest = 'cancellation_request';
|
||||
case CancellationFee = 'cancellation_fee';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
@@ -23,12 +24,13 @@ public function getLabel(): string
|
||||
self::BalanceRequest => 'Restzahlung bald fällig – anfordern',
|
||||
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
|
||||
self::CancellationRequest => 'Stornierungswunsch des Gastes',
|
||||
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
|
||||
};
|
||||
}
|
||||
|
||||
public function isPayment(): bool
|
||||
{
|
||||
return $this !== self::CancellationRequest;
|
||||
return ! in_array($this, [self::CancellationRequest, self::CancellationFee], true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,7 +44,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 => null,
|
||||
self::CancellationRequest, self::CancellationFee => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@
|
||||
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\RelationManagers\MessagesRelationManager;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingForm;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
|
||||
use App\Filament\Resources\Bookings\Tables\BookingsTable;
|
||||
@@ -72,6 +74,8 @@ public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
PaymentsRelationManager::class,
|
||||
TasksRelationManager::class,
|
||||
MessagesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Bookings\Pages;
|
||||
|
||||
use App\Actions\CancelBooking;
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Actions\DeclineBooking;
|
||||
use App\Actions\SendOffer;
|
||||
@@ -189,6 +190,16 @@ protected function getHeaderActions(): array
|
||||
$notification = Notification::make()->title($sent ? 'Bestätigung gesendet' : 'Versand fehlgeschlagen');
|
||||
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->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)
|
||||
@@ -209,12 +220,23 @@ protected function getHeaderActions(): array
|
||||
->icon(Heroicon::OutlinedNoSymbol)
|
||||
->color('danger')
|
||||
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Der Zeitraum wird wieder freigegeben. Der Gast wird nicht automatisch benachrichtigt.')
|
||||
->action(function (): void {
|
||||
$this->record->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
||||
->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();
|
||||
|
||||
Notification::make()->title('Buchung storniert')->success()->send();
|
||||
return;
|
||||
}
|
||||
|
||||
$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();
|
||||
}),
|
||||
]),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Bookings\RelationManagers;
|
||||
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* Communication log: every e-mail that went out for this booking.
|
||||
*/
|
||||
class MessagesRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'messages';
|
||||
|
||||
protected static ?string $title = 'Mailverlauf';
|
||||
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('subject')
|
||||
->defaultSort('sent_at', 'desc')
|
||||
->emptyStateHeading('Noch keine E-Mails zu dieser Buchung')
|
||||
->description('Betreff und Empfängerart jeder E-Mail zu dieser Buchung. Im Testbetrieb gehen alle Mails an die Testadresse.')
|
||||
->columns([
|
||||
TextColumn::make('sent_at')->label('Gesendet')->dateTime('d.m.Y, H:i'),
|
||||
TextColumn::make('audience')->label('An')->badge()->formatStateUsing(fn (string $state): string => match ($state) {
|
||||
'guest' => 'Gast',
|
||||
'landlord' => 'Vermieter',
|
||||
default => 'Testadresse',
|
||||
}),
|
||||
TextColumn::make('subject')->label('Betreff')->wrap(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Bookings\RelationManagers;
|
||||
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Models\BookingTask;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* Tasks of this booking (payment reminders, cancellation requests and costs).
|
||||
*/
|
||||
class TasksRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'tasks';
|
||||
|
||||
protected static ?string $title = 'Aufgaben';
|
||||
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('kind')
|
||||
->defaultSort('created_at', 'desc')
|
||||
->emptyStateHeading('Keine Aufgaben zu dieser Buchung')
|
||||
->columns([
|
||||
TextColumn::make('kind')->label('Aufgabe')->badge(),
|
||||
TextColumn::make('status')->label('Status')->badge(),
|
||||
TextColumn::make('due_on')->label('Seit / fällig')->date('d.m.Y')->placeholder('–'),
|
||||
TextColumn::make('note')->label('Hinweis')->wrap()->placeholder('–'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('done')
|
||||
->label('Erledigt')
|
||||
->icon(Heroicon::OutlinedCheck)
|
||||
->color('success')
|
||||
->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open)
|
||||
->action(fn (BookingTask $record) => $record->complete(auth()->user()->name)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -3,24 +3,68 @@
|
||||
namespace App\Filament\Resources\Bookings\Schemas;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Support\BookingProgress;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
class BookingInfolist
|
||||
{
|
||||
/**
|
||||
* The steps of the process as a row of chips.
|
||||
*/
|
||||
private static function timeline(Booking $booking): HtmlString
|
||||
{
|
||||
$style = [
|
||||
'done' => 'background:#dcfce7;color:#14532d',
|
||||
'current' => 'background:#fef3c7;color:#78350f;font-weight:700',
|
||||
'todo' => 'background:#f3f4f6;color:#4b5563',
|
||||
'skipped' => 'background:#f3f4f6;color:#9ca3af;text-decoration:line-through',
|
||||
];
|
||||
$icon = ['done' => '✓ ', 'current' => '● ', 'todo' => '', 'skipped' => ''];
|
||||
|
||||
return new HtmlString('<div style="display:flex;flex-wrap:wrap;gap:.4rem">'.collect(BookingProgress::steps($booking))->map(fn (array $step): string => '<span style="padding:.25rem .6rem;border-radius:999px;font-size:.8rem;'.$style[$step['state']].'">'.$icon[$step['state']].e($step['label']).($step['detail'] ? ' · '.e($step['detail']) : '').'</span>')->implode('').'</div>');
|
||||
}
|
||||
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Vorgang')
|
||||
->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('steps')
|
||||
->label('Verlauf')
|
||||
->state(fn (Booking $record): HtmlString => self::timeline($record))
|
||||
->html()
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
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([
|
||||
|
||||
@@ -37,6 +37,9 @@ public static function configure(Table $table, ?int $guestId = null): Table
|
||||
}
|
||||
if (filled($filters['status']['values'] ?? [])) {
|
||||
$records = $records->whereIn('status_key', $filters['status']['values']);
|
||||
} elseif (! ($filters['show_closed']['isActive'] ?? false)) {
|
||||
// Cancelled, declined and expired requests leave the main list (they stay available as archive).
|
||||
$records = $records->reject(fn (array $record): bool => in_array($record['status_key'], ['cancelled', 'declined', 'expired'], true));
|
||||
}
|
||||
$column = in_array($sortColumn, ['arrival', 'departure', 'reference', 'guest', 'source', 'total'], true) ? $sortColumn : 'arrival';
|
||||
$records = $records->sortBy($column, SORT_REGULAR, $sortDirection === 'desc');
|
||||
@@ -69,6 +72,7 @@ public static function configure(Table $table, ?int $guestId = null): Table
|
||||
'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed',
|
||||
]),
|
||||
Filter::make('upcoming')->label('Nur kommende Aufenthalte'),
|
||||
Filter::make('show_closed')->label('Archiv anzeigen (storniert, abgelehnt, abgelaufen)'),
|
||||
Filter::make('without_guest')->label('Gastzuordnung offen'),
|
||||
])
|
||||
->recordUrl(fn (array $record): string => $record['url'])
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingMessage;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Mail\Events\MessageSent;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Writes every mail that belongs to a booking (the mailable has a public $booking) into the booking's communication
|
||||
* log. Who received it is derived from the recipient address – in test operation everything goes to the test
|
||||
* address and is marked as such. A logging problem never disturbs the mail.
|
||||
*/
|
||||
class LogBookingMail
|
||||
{
|
||||
public function handle(MessageSent $event): void
|
||||
{
|
||||
try {
|
||||
$booking = $event->data['booking'] ?? null;
|
||||
if (! $booking instanceof Booking) {
|
||||
return;
|
||||
}
|
||||
|
||||
$recipients = collect($event->message->getTo())->map(fn ($address): string => mb_strtolower($address->getAddress()));
|
||||
$guest = mb_strtolower((string) $booking->guest?->email);
|
||||
$audience = ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord');
|
||||
|
||||
BookingMessage::query()->create([
|
||||
'booking_id' => $booking->id,
|
||||
'audience' => $audience,
|
||||
'subject' => mb_substr((string) $event->message->getSubject(), 0, 255),
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
} catch (Throwable) {
|
||||
// The log is a convenience; the mail has been sent.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -236,6 +236,22 @@ public function review(): HasOne
|
||||
return $this->hasOne(Review::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BookingMessage, $this>
|
||||
*/
|
||||
public function messages(): HasMany
|
||||
{
|
||||
return $this->hasMany(BookingMessage::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BookingTask, $this>
|
||||
*/
|
||||
public function tasks(): HasMany
|
||||
{
|
||||
return $this->hasMany(BookingTask::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Payment, $this>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* An e-mail that went out for a booking (communication log). Only subject and audience are kept.
|
||||
*/
|
||||
#[Fillable(['booking_id', 'audience', 'subject', 'sent_at'])]
|
||||
class BookingMessage extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
use BelongsToTenant;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['sent_at' => 'immutable_datetime'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Booking, $this>
|
||||
*/
|
||||
public function booking(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Booking::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?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\BookingTask;
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{label: string, state: string, detail: ?string}> state: done | current | todo | skipped
|
||||
*/
|
||||
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);
|
||||
$steps = [];
|
||||
|
||||
$steps[] = ['label' => 'Anfrage / Eingang', 'state' => 'done', 'detail' => $booking->created_at?->format('d.m.Y')];
|
||||
|
||||
$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,
|
||||
];
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'label' => $needsOffer ? 'Annahme / Vertrag' : 'Vertrag senden',
|
||||
'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),
|
||||
];
|
||||
|
||||
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];
|
||||
$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')];
|
||||
} else {
|
||||
$steps[] = ['label' => 'Zahlung', 'state' => 'skipped', 'detail' => 'läuft über das Portal'];
|
||||
}
|
||||
|
||||
$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')];
|
||||
$steps[] = ['label' => 'Vor Ort', 'state' => $closed ? 'skipped' : ($arrived && ! $left ? 'current' : ($left ? 'done' : 'todo')), 'detail' => null];
|
||||
$steps[] = ['label' => 'Abreise', 'state' => $closed ? 'skipped' : ($left ? 'done' : 'todo'), 'detail' => $booking->departure->format('d.m.Y')];
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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' => $costs !== null || $wish !== null ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.', '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'],
|
||||
$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,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Communication log per booking: which mail was sent when (subject and audience only – no addresses, no body).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('booking_messages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('audience', 12);
|
||||
$table->string('subject', 255);
|
||||
$table->timestamp('sent_at');
|
||||
$table->index(['booking_id', 'sent_at']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('booking_messages');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
@php($document = \App\Documents\OfferTerms::document($booking))
|
||||
<div class="space-y-4 text-sm">
|
||||
<p class="text-gray-500">
|
||||
Der Vertragstext, wie er beim Angebot festgehalten wurde (Stand {{ \Carbon\CarbonImmutable::parse($booking->offer_terms['captured_at'])->format('d.m.Y, H:i') }} Uhr).
|
||||
@if ($booking->offer_hash) Prüfsumme des Angebots: {{ substr($booking->offer_hash, 0, 16) }}… @endif
|
||||
</p>
|
||||
|
||||
@if ($document)
|
||||
<div class="prose max-w-none">{!! $document['body'] !!}</div>
|
||||
@if ($document['annex'])
|
||||
<hr>
|
||||
<h3 class="font-semibold">{{ $document['annex_title'] ?: 'Anlage' }}</h3>
|
||||
<div class="prose max-w-none">{!! $document['annex'] !!}</div>
|
||||
@endif
|
||||
@else
|
||||
<div class="prose max-w-none">{{ $booking->offerHtml('contract.terms') }}</div>
|
||||
@if ($booking->offerText('stay.cancellation'))
|
||||
<h3 class="font-semibold">Rücktritt / Stornierung</h3>
|
||||
<div class="prose max-w-none">{{ $booking->offerHtml('stay.cancellation') }}</div>
|
||||
@endif
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\CancelBooking;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
|
||||
use App\Mail\BookingCancelled;
|
||||
use App\Mail\CancellationRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingMessage;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use App\Support\BookingProgress;
|
||||
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;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* The booking file: where a process stands, next step, communication log, cancellation by the landlord, archive.
|
||||
*/
|
||||
class BookingFileTest 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();
|
||||
Storage::fake('local');
|
||||
$this->withoutVite();
|
||||
}
|
||||
|
||||
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']);
|
||||
|
||||
Mail::fake();
|
||||
$offer = app(SendOffer::class)->handle($request);
|
||||
$this->assertSame('Wartet auf den Gast', BookingProgress::next($offer)['title']);
|
||||
|
||||
$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->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'));
|
||||
}
|
||||
|
||||
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']);
|
||||
$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'));
|
||||
}
|
||||
|
||||
public function test_every_booking_mail_lands_in_the_communication_log_with_its_audience(): void
|
||||
{
|
||||
$booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']);
|
||||
|
||||
app(SendOffer::class)->handle($booking);
|
||||
$this->assertSame(['test'], BookingMessage::query()->pluck('audience')->unique()->all());
|
||||
|
||||
Settings::tenant()->update(['operating_mode' => Settings::MODE_LIVE]);
|
||||
Settings::applyMailRouting();
|
||||
BookingMessage::query()->delete();
|
||||
$other = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-12-01', 'departure' => '2026-12-04']);
|
||||
app(SendOffer::class)->handle($other);
|
||||
|
||||
$message = BookingMessage::query()->where('booking_id', $other->id)->sole();
|
||||
$this->assertSame('guest', $message->audience);
|
||||
$this->assertStringContainsString('Angebot', $message->subject);
|
||||
}
|
||||
|
||||
public function test_cancellation_by_the_landlord_informs_guest_and_landlord_and_leaves_a_cost_task(): void
|
||||
{
|
||||
$booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']);
|
||||
BookingTask::query()->create(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationRequest, 'status' => BookingTaskStatus::Open]);
|
||||
Mail::fake();
|
||||
|
||||
$this->assertTrue(app(CancelBooking::class)->handle($booking, notifyGuest: true));
|
||||
|
||||
$this->assertSame(BookingStatus::Cancelled, $booking->fresh()->status);
|
||||
Mail::assertSent(BookingCancelled::class, fn (BookingCancelled $mail): bool => $mail->cancelled);
|
||||
Mail::assertSent(CancellationRequested::class, 1);
|
||||
$this->assertSame(BookingTaskStatus::Done, BookingTask::query()->where('kind', BookingTaskKind::CancellationRequest)->sole()->status);
|
||||
$this->assertSame(BookingTaskStatus::Open, BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->sole()->status);
|
||||
$this->assertSame(0, Booking::query()->occupying()->count());
|
||||
}
|
||||
|
||||
public function test_cancellation_without_guest_mail_and_the_admin_action_offer_both_choices(): void
|
||||
{
|
||||
$booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']);
|
||||
Mail::fake();
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
|
||||
->callAction(TestAction::make('cancel')->arguments([]), ['notify_guest' => false, 'costs_task' => false])
|
||||
->assertNotified('Buchung storniert');
|
||||
|
||||
Mail::assertNotSent(BookingCancelled::class);
|
||||
Mail::assertSent(CancellationRequested::class, 1);
|
||||
$this->assertSame(0, BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->count());
|
||||
}
|
||||
|
||||
public function test_cancelled_bookings_leave_the_main_list_but_stay_in_the_archive_filter(): void
|
||||
{
|
||||
$active = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']);
|
||||
$cancelled = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Cancelled, 'arrival' => '2026-12-10', 'departure' => '2026-12-12']);
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
Livewire::test(ListBookings::class)
|
||||
->assertSee($active->reference)
|
||||
->assertDontSee($cancelled->reference)
|
||||
->filterTable('show_closed', true)
|
||||
->assertSee($cancelled->reference);
|
||||
}
|
||||
|
||||
public function test_the_booking_page_shows_process_contract_tasks_and_mail_log(): void
|
||||
{
|
||||
Mail::fake();
|
||||
$booking = app(SendOffer::class)->handle(Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']));
|
||||
$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');
|
||||
|
||||
Livewire::test(MessagesRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class])->assertSuccessful();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user