Files
fewo-stommer/app/Filament/Resources/Bookings/Pages/ViewBooking.php
T
LarsandClaude Sonnet 5.5 5ba9ae08ab
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
Portal-Direktbuchung erfassen, Kontaktdaten-Prozess, manueller Statuswechsel, Archiv, Filter, Menue Verwaltung/Einrichtung
- Buchung erfassen: Buchungsweg Portal (Referenz, Portalpreis, ohne Kontaktdaten), Prozess bestaetigen/Vertrag sofort/nur erfassen
- Buchungsakte: Kontaktdaten eintragen (automatisch oder manuell weiter), Gast um Kontaktdaten bitten, Status von Hand aendern, Archivieren
- Liste: Filter Kanal, Anreisezeitraum, Kontaktdaten fehlen; Spalten ausblendbar; Archiv
- Klaerung: verstaendlichere Texte, eigenstaendige Belegung mit Kanal gilt als geklaert (Gitea #4)
- Akte per Button aus Liste und Belegungsplan erreichbar
- Menue: Gruppen Verwaltung (Tagesgeschaeft) und Einrichtung (Konfiguration), einfache Ansicht auf 8 Punkte

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 18:04:03 +01:00

433 lines
27 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\CancelBooking;
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\ProvideGuestContact;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Support\BookingProgress;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Icons\Heroicon;
use Throwable;
/**
* @property Booking $record
*/
class ViewBooking extends ViewRecord
{
protected static string $resource = BookingResource::class;
public function getTitle(): string
{
return "{$this->record->reference} · {$this->record->guest->full_name}";
}
protected function getHeaderActions(): array
{
return [
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([
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('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([
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.'),
]),
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([
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),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
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;
}
$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('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])
->schema([
Textarea::make('internal_notes')->label('Interne Notizen')->rows(6),
])
->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();
return;
}
$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();
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();
}),
]),
];
}
/**
* Suggested message asking a portal guest for the contact data the contract needs.
*/
private function contactRequestText(): string
{
$booking = $this->record;
$landlord = config('fewo.owner.name') ?: config('app.name');
return "Guten Tag {$booking->guest->first_name} {$booking->guest->last_name},\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"
."Freundliche Grüße\n{$landlord}";
}
/**
* Form data of the offer modal as SendOffer changes (euro input → cents).
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function offerChanges(array $data): array
{
return [
...$data,
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
];
}
/**
* Live price shown in the offer modal, calculated exactly like the offer itself.
*/
private function offerPricePreview(Get $get): string
{
try {
$stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null);
$quote = app(PriceCalculator::class)->calculate($this->record->property, $stay);
} catch (QuoteException $exception) {
return 'Preis: '.$exception->getMessage();
} catch (Throwable) {
return 'Preis: bitte Termin und Personen angeben.';
}
$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;
}
private function runWorkflow(callable $workflow, string $successTitle): void
{
try {
$workflow();
} catch (ReservationException|QuoteException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
Notification::make()->title($successTitle)->success()->send();
}
}