Files
fewo-stommer/app/Filament/Resources/Bookings/Pages/ViewBooking.php
T
LarsandClaude Opus 5.5 cf11c8a474
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m59s
Dokumentenzusammenstellung und Vorlagensteuerung (Paket 3, Prozessarchitektur v0.10)
Eine Zusammenstellung vor jedem Dokument (Angebot, Bestaetigung, Buchungsunterlagen
extern), Dokumentart je Vorgangsart, Freigaben fuer Vorlagen und Dokumentarten,
Schutz vor unvereinbarten Bedingungen bei Portalbuchungen (E-004), kein doppelter
Versand, Absicherung Hold 0 bis Paket 7, A6-Aufenthaltsbestaetigung vorbereitet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 19:44:52 +01:00

665 lines
38 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\SendBookingDocuments;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Forms\DocumentCompositionFields;
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\QuoteException;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden;
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\Group;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* 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->guestName()}";
}
public function getSubheading(): string|Htmlable|null
{
return CaseActivities::situation($this->record);
}
protected function getHeaderActions(): array
{
$actions = collect([
$this->sendOfferAction(),
$this->provideContactAction(),
$this->requestContactAction(),
AssignGuestAction::make(),
$this->confirmAction(),
$this->sendDocumentsAction(),
$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 Zusammenstellung; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.')
->modalSubmitActionLabel('Senden')
->modalWidth('4xl')
->fillForm(fn (): array => [
'expected_version' => $this->record->offer_version,
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'promo_code' => $this->record->promo_code,
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
'price_adjustment_label' => $this->record->price_adjustment_label,
'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
'annex_ids' => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [],
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']) ?? [],
])
->schema([
Hidden::make('expected_version'),
...DocumentCompositionFields::make($this->record, DocumentKind::Offer, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message', 'contract_template_id', 'annex_ids', 'guest']))),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast – die Zusammenstellung oben rechnet sofort neu.')->collapsed()->schema([
Section::make('Termin')->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
]),
Section::make('Preis')->columns(3)->schema([
TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true),
TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true),
]),
...$this->templateFields(),
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()
->live(onBlur: true),
Section::make('Gast – so erscheint er im Vertrag')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150)->live(onBlur: true),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20)->live(onBlur: true),
TextInput::make('guest.city')->label('Ort')->maxLength(100)->live(onBlur: true),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50)->live(onBlur: true),
]),
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Angebot gesendet'));
}
/**
* The documents of a binding case (confirmation with contract, or booking documentation of a portal booking), sent
* after the landlord saw their composition.
*/
private function sendDocumentsAction(): Action
{
return Action::make('sendDocuments')
->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null && $this->record->process()->documents() === Responsibility::Landlord)
->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel())
->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.')
->modalSubmitActionLabel('Senden')
->modalWidth('4xl')
->fillForm(fn (): array => ['annex_ids' => $this->record->contract_path === null && $this->record->offer_version === 0 ? (OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []) : null])
->schema(fn (): array => [
...DocumentCompositionFields::make($this->record, SendBookingDocuments::kindFor($this->record), fn (Get $get): array => $this->documentChanges(self::formState($get, ['contract_template_id', 'annex_ids']))),
Section::make('Anpassen')->description('Vorlage und Anlagen für diesen Vorgang.')->collapsed()->visible($this->record->contract_path === null && $this->record->offer_version === 0)->schema($this->templateFields()),
])
->action(function (array $data, SendBookingDocuments $documents): void {
$this->runWorkflow(function () use ($data, $documents): void {
if (! $documents->handle($this->record, $this->documentChanges($data), (bool) ($data['acknowledged'] ?? false))) {
throw new ReservationException('Der Versand ist fehlgeschlagen (Details im Postfach). Sie können ihn über „Unterlagen erneut senden“ wiederholen.');
}
}, 'Unterlagen gesendet');
});
}
/**
* Choice of template and annexes for one case; changing the template proposes its annexes.
*
* @return list<Section>
*/
private function templateFields(): array
{
return [
Section::make('Vorlage und Anlagen')->schema([
Select::make('contract_template_id')
->label('Andere Vorlage für diesen Vorgang')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label().($template->isReleased() ? '' : ' – nicht freigegeben')])->all())
->placeholder('wie eingestellt')
->live()
->afterStateUpdated(fn (Set $set, $state) => $set('annex_ids', OfferTerms::templateFor($this->record, $state)?->annexesFor($this->record)->pluck('id')->all() ?? [])),
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->live()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()),
]),
];
}
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('Nicht möglich')->body($exception->getMessage())->danger()->send();
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
{
$kind = fn (): DocumentKind => $this->record->intake === IntakeKind::Booking ? DocumentKind::ExternalRecord : DocumentKind::Confirmation;
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))
->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.')
->modalSubmitActionLabel('Bestätigen')
->modalWidth('4xl')
->fillForm(fn (): array => ['notify' => filled($this->record->guest?->email)])
->schema(fn (): array => [
Toggle::make('notify')->label('Unterlagen an den Gast senden')->live(),
Group::make(DocumentCompositionFields::make($this->record, $kind(), fn (Get $get): array => [], fn (Get $get): bool => (bool) $get('notify')))
->visible(fn (Get $get): bool => (bool) $get('notify')),
])
->action(function (array $data, ConfirmBooking $confirm, SendBookingDocuments $documents) use ($kind): void {
$notify = (bool) ($data['notify'] ?? false);
$acknowledged = (bool) ($data['acknowledged'] ?? false);
if ($notify) {
$composition = DocumentCompositionFields::compose($this->record, $kind(), []);
if (! $composition->canSendByHand($acknowledged)) {
Notification::make()->title('Nicht möglich')->body(implode(' ', [...$composition->blockers(), ...$composition->toConfirm()]))->danger()->send();
return;
}
}
$this->runWorkflow(function () use ($confirm, $documents, $notify, $acknowledged): void {
DB::transaction(fn () => $confirm->bind($this->record));
$notify ? $documents->handle($this->record->fresh(), [], $acknowledged) : $confirm->deliver($this->record->fresh(), notifyGuest: false);
}, '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) && ($this->record->confirmation_sent_at !== null || $this->record->confirmation_failed_at !== null))
->requiresConfirmation()
->modalDescription(fn (): string => 'Der Gast erhält dieselben Unterlagen noch einmal (Vorlage: '.(isset($this->record->offer_terms['template']['name']) ? $this->record->offer_terms['template']['name'].', Version '.$this->record->offer_terms['template']['version'] : 'Texte der Webseite').').')
->action(function (ConfirmBooking $confirm): void {
if ($this->record->contract_path === null) {
Notification::make()->title('Bitte zuerst prüfen')->body('Die Unterlagen wurden noch nie erstellt – bitte über „Unterlagen prüfen und senden“.')->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([
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]);
CaseLog::record($this->record, 'services', 'Zusatzleistungen erfasst');
Notification::make()->title('Zusatzleistungen gespeichert')->success()->send();
});
}
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"));
}
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"));
}
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');
}
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();
});
}
/**
* 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');
$greeting = $booking->guest ? "Guten Tag {$booking->guest->first_name} {$booking->guest->last_name}," : 'Guten Tag,';
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"
."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,
'acknowledged' => (bool) ($data['acknowledged'] ?? false),
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
];
}
/**
* The current values of some fields of a modal form.
*
* @param list<string> $fields
* @return array<string, mixed>
*/
private static function formState(Get $get, array $fields): array
{
return collect($fields)->mapWithKeys(fn (string $field): array => [$field => $get($field)])->all();
}
/**
* Form data of the documents modal as composition changes.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function documentChanges(array $data): array
{
return array_filter(Arr::only($data, ['contract_template_id', 'annex_ids']), fn ($value): bool => $value !== null);
}
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;
}
$this->record->refresh();
Notification::make()->title($successTitle)->success()->send();
}
}