Files
fewo-stommer/app/Filament/Resources/Bookings/Pages/ViewBooking.php
T
2026-10-27 21:51:56 +01:00

259 lines
14 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\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\SendOffer;
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\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
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\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('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('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('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('regenerateContract')
->label('Mietvertrag neu erzeugen')
->icon(Heroicon::OutlinedArrowPath)
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true))
->requiresConfirmation()
->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.')
->action(function (RentalContract $contract): void {
$contract->generate($this->record);
Notification::make()->title('Mietvertrag neu erzeugt')->success()->send();
}),
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('cancel')
->label('Stornieren')
->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()]);
Notification::make()->title('Buchung storniert')->success()->send();
}),
]),
];
}
/**
* 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();
}
}