Files
fewo-stommer/app/Filament/Resources/Bookings/Pages/ViewBooking.php
T
LarsandClaude Sonnet 5.5 8442d0a3d8 V2.1: Kanalfähigkeiten, Ausführungsvarianten, Dokumentenentkopplung, Portalbestätigung
Modellwahl über Kanalfähigkeiten mit erklärten Einschränkungen, Abgleich alter Werte,
Ausführungsvarianten je Modul, getrennte Vertrags-/Buchungsinformation, Warten auf
die Portalbestätigung mit Eskalation und Wiederaufnahme (Fälle C und D getestet).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:54:11 +01:00

1072 lines
65 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\ChangeBooking;
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\EndInternalCase;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPortalAmounts;
use App\Actions\RequestCaseData;
use App\Actions\SendBookingDocuments;
use App\Actions\SendBookingNotice;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingNoticeMode;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
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\Filament\Resources\Bookings\Pages\Concerns\HandlesWishAndStay;
use App\Models\Booking;
use App\Models\BookingChange;
use App\Models\BookingTask;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\DataRequest;
use App\Models\Extra;
use App\Models\User;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Process\Activity;
use App\Process\ActivityDetails;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Process\PortalConfirmation;
use App\Process\ProcessRunner;
use App\Support\Countries;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Checkbox;
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\Schemas\Components\View;
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
{
use HandlesWishAndStay;
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);
}
/**
* Filament builds the header actions before an action runs; rebuild them afterwards so the large button already
* shows the next step instead of the one just done.
*/
protected function afterActionCalled(Action $action): void
{
parent::afterActionCalled($action);
$fresh = $this->record->exists ? $this->record->fresh() : null;
if ($fresh === null) {
return;
}
$this->record = $fresh;
$this->cachedHeaderActions = [];
$this->cacheInteractsWithHeaderActions();
}
protected function getHeaderActions(): array
{
$actions = collect([
$this->sendInformationAction(),
$this->decideWishAction(),
$this->sendOfferAction(),
$this->provideContactAction(),
$this->arrivalDetailsAction(),
$this->completeTaskAction(),
$this->addTaskAction(),
$this->closeStayAction(),
$this->settleAction(),
$this->requestContactAction(),
$this->approveDataRequestAction(),
$this->stopDataRequestAction(),
AssignGuestAction::make(),
$this->confirmAction(),
$this->sendDocumentsAction(),
$this->resendConfirmationAction(),
$this->confirmPortalAction(),
$this->sendBookingNoticeAction(),
$this->portalPriceAction(),
$this->changeAction(),
$this->confirmPortalCancellationAction(),
$this->withdrawChangeAction(),
$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());
// While the case waits for the guest's missing details, entering them oneself (call, other mail) is the step at hand.
$next = CaseActivities::next($this->record)?->action
?? collect(CaseActivities::for($this->record))->first(fn ($activity): bool => $activity->key === 'contact' && $activity->action !== null)?->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 => match (true) {
$this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden',
! $this->record->process()->preReservation() => 'Stattdessen verbindliches Angebot mit Reservierung senden',
default => '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 || ($this->record->isInternal() && $this->record->internal_kind !== InternalKind::Block && filled($this->record->guest?->email))))
->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 => match (true) {
$this->record->guest === null => 'Gast eintragen',
RequestCaseData::needs($this->record) !== null => 'Fehlende Angaben selbst eintragen',
default => 'Gastdaten bearbeiten',
})
->icon(Heroicon::OutlinedUserPlus)
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Kontaktdaten des Gastes')
->modalDescription(fn (): string => 'Aus Telefonat, E-Mail, Portalnachricht oder Gespräch. Nur eintragen, was bekannt ist; Ihre Eingabe gilt und wird mit Herkunft „von Ihnen eingetragen“ festgehalten. Eine laufende Rückfrage endet, sobald alles da ist.'.$this->openFactConflicts())
->modalWidth('3xl')
->fillForm(fn (): array => [
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']) ?? [],
'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),
Select::make('guest.country')->label('Land')->options(Countries::options())->placeholder('nicht bekannt'),
]),
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();
});
}
/**
* Details from the guest's side that differ from the stored ones (v0.11 fact intake), for the contact dialog.
*/
private function openFactConflicts(): string
{
$notes = $this->record->tasks()->where('kind', BookingTaskKind::FactConflict)->where('status', BookingTaskStatus::Open)->pluck('note')->all();
return $notes === [] ? '' : ' Abweichende Angaben des Gastes – bitte den richtigen Wert eintragen: '.implode(' · ', $notes);
}
/**
* What lies behind one step of the progress list (clicked in "Ablauf"): its history entries and – for the guest's
* details – each detail with source, time, evidence and certainty, with the way to correct it or to do the step.
*/
public function activityDetailsAction(): Action
{
return Action::make('activityDetails')
->modalHeading(fn (array $arguments): string => ActivityDetails::activity($this->record, (string) ($arguments['key'] ?? ''))?->label ?? 'Schritt')
->modalWidth('4xl')
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->modalContent(function (array $arguments): \Illuminate\Contracts\View\View {
$key = (string) ($arguments['key'] ?? '');
$activity = ActivityDetails::activity($this->record, $key);
return view('filament.activity-details', [
'activity' => $activity ?? new Activity($key, 'Schritt', ActivityState::NotApplicable),
'events' => ActivityDetails::events($this->record, $key),
'facts' => ActivityDetails::showsFacts($key) ? ActivityDetails::facts($this->record->loadMissing('guest')) : null,
]);
})
->extraModalFooterActions(fn (array $arguments): array => array_values(array_filter([
ActivityDetails::showsFacts((string) ($arguments['key'] ?? '')) && $this->record->internal_kind !== InternalKind::Block
? Action::make('correctFacts')->label('Angaben korrigieren')->color('primary')->action(fn () => $this->replaceMountedAction('provideContact'))
: null,
($step = ActivityDetails::activity($this->record, (string) ($arguments['key'] ?? ''))?->action) !== null && $step !== 'provideContact'
? Action::make('doStep')->label('Diesen Schritt ausführen')->action(fn () => $this->replaceMountedAction($step))
: null,
])));
}
/**
* v0.11 data request: send the prepared question (or ask now although the case is set to asking by hand).
*/
private function approveDataRequestAction(): Action
{
return Action::make('approveDataRequest')
->label('Rückfrage an den Gast senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->openDataRequest()?->status, [DataRequest::DRAFT, DataRequest::MANUAL], true) && filled($this->record->guest?->email))
->modalHeading('Fehlende Angaben beim Gast anfragen')
->modalDescription(function (): string {
$request = $this->record->openDataRequest();
$state = $this->record->clarificationState();
return 'Der Gast erhält eine E-Mail mit einem persönlichen Link und wird gebeten um: '.implode(', ', CaseRequirements::labels((array) $request?->fields)).'. '
.match ($state['state']) {
'active' => 'Die Mail nennt die vorläufige Reservierung bis '.$state['until']->format('d.m.Y, H:i').' Uhr.',
'expired' => 'Die Mail sagt, dass die vorläufige Reservierung abgelaufen ist.',
default => $this->record->isBinding() ? 'Die Mail sagt, dass die Buchung verbindlich bleibt.' : 'Die Mail sagt, dass der Zeitraum noch nicht reserviert ist.',
}
.(RequestCaseData::mayGoOutAutomatically() ? '' : ' Hinweis: Der Text der Rückfrage ist noch eine Arbeitsfassung (So arbeite ich › Dokumente); mit „Senden“ bestätigen Sie ihn für diesen Vorgang.');
})
->modalSubmitActionLabel('Senden')
->action(function (RequestCaseData $requests): void {
$request = $this->record->openDataRequest();
$sent = $request !== null && $requests->approve($request);
$this->record->refresh();
$sent
? Notification::make()->title('Rückfrage gesendet')->success()->send()
: Notification::make()->title('Nicht gesendet')->body('Bitte die E-Mail-Adresse des Gastes prüfen – oder es fehlt inzwischen nichts mehr.')->danger()->send();
});
}
private function stopDataRequestAction(): Action
{
return Action::make('stopDataRequest')
->label('Rückfrage beenden')
->icon(Heroicon::OutlinedNoSymbol)
->color('gray')
->visible(fn (): bool => $this->record->openDataRequest() !== null)
->requiresConfirmation()
->modalDescription('Es gehen keine Erinnerungen und Folgefragen mehr hinaus. Die fehlenden Angaben tragen Sie dann selbst ein.')
->action(function (RequestCaseData $requests): void {
$requests->close($this->record->openDataRequest(), DataRequest::STOPPED, 'von Ihnen beendet');
$this->record->refresh();
Notification::make()->title('Rückfrage beendet')->success()->send();
});
}
private function requestContactAction(): Action
{
return Action::make('requestContact')
->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->visible(fn (): bool => ! $this->record->isInternal() && 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');
});
}
/**
* V2.1: the landlord states that the portal confirmed the booking (e.g. seen in the portal's own interface). The steps that
* wait for it go on; the booking itself was binding from the start.
*/
private function confirmPortalAction(): Action
{
return Action::make('confirmPortal')
->label('Bestätigung des Portals festhalten')
->icon(Heroicon::OutlinedCheckBadge)
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->awaitsPortalConfirmation() && PortalConfirmation::evidence($this->record) === null)
->modalDescription('Das Portal hat die Buchung bestätigt (z. B. in seiner Oberfläche gesehen). Unterlagen und Nachrichten, die darauf warten, gehen dann weiter. Die Buchung bleibt wie sie ist.')
->schema([Textarea::make('note')->label('Woran haben Sie das gesehen?')->rows(2)->maxLength(500)])
->action(function (array $data): void {
PortalConfirmation::confirm($this->record, CaseLog::actor(), $data['note'] ?? null);
app(ProcessRunner::class)->advance($this->record->fresh(), 'portal.mail');
$this->record->refresh();
Notification::make()->title('Bestätigung festgehalten')->success()->send();
});
}
/**
* V2.1: the short booking information to the guest, sent by hand (also where the automatic dispatch is off).
*/
private function sendBookingNoticeAction(): Action
{
return Action::make('sendBookingNotice')
->label('Buchungsinformation an den Gast senden')
->icon(Heroicon::OutlinedEnvelope)
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->bookingNotice() !== BookingNoticeMode::Off && ! SendBookingNotice::sent($this->record) && filled($this->record->guest?->email))
->requiresConfirmation()
->modalDescription('Der Gast erhält eine kurze Information über seine Buchung – ohne Vertrag.')
->action(function (SendBookingNotice $notice): void {
try {
$notice->handle($this->record->fresh());
} catch (ReservationException $exception) {
Notification::make()->title('Nicht gesendet')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
Notification::make()->title('Buchungsinformation gesendet')->success()->send();
});
}
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();
});
}
/**
* What the portal shows about the booking (package 8): the guest's total as the agreed price and – optional, folded
* away – its positions, commission, announced payouts, instalments and what the guest paid to the portal.
*/
private function portalPriceAction(): Action
{
return Action::make('portalPrice')
->label('Preis laut Portal eintragen')
->icon(Heroicon::OutlinedCurrencyEuro)
->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true))
->modalHeading(fn (): string => 'Beträge laut '.($this->record->processChannel()?->name ?? 'Portal'))
->modalDescription('Der Gesamtpreis, den der Gast beim Portal gebucht hat, wird so übernommen und nicht neu berechnet. Einzelheiten nur eintragen, wenn das Portal sie zeigt – nichts schätzen. Abweichende Angaben (z. B. zwei verschiedene Auszahlungsbeträge) einfach beide eintragen.')
->modalWidth('4xl')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests, 'stated_on' => today()->toDateString(), 'amounts' => [], 'paid' => []])
->schema([
Section::make()->columns(3)->schema([
EuroInput::make('portal_total')->label('Gesamtpreis des Gastes laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
DatePicker::make('stated_on')->label('Stand der Angaben')->required(),
]),
Section::make('Einzelheiten laut Portal (optional)')->collapsed()->schema([
Repeater::make('amounts')->label('Positionen und Angaben')->addActionLabel('Angabe hinzufügen')->columns(4)->defaultItems(0)->schema([
Select::make('kind')->label('Art')->options(AmountKind::class)->required()->columnSpan(2),
TextInput::make('label')->label('Bezeichnung laut Portal')->placeholder('z. B. Gebühren und Steuern')->maxLength(150),
EuroInput::make('amount')->label('Betrag')->minValue(null)->required(),
DatePicker::make('due_on')->label('fällig am (bei Raten)'),
TextInput::make('note')->label('Notiz')->maxLength(500)->columnSpan(3),
]),
Repeater::make('paid')->label('Vom Gast laut Portal bereits bezahlt')->addActionLabel('Zahlung laut Portal hinzufügen')->columns(2)->defaultItems(0)->schema([
EuroInput::make('amount')->label('Betrag')->required(),
DatePicker::make('paid_on')->label('bezahlt am')->required(),
]),
]),
])
->action(function (array $data, RecordPortalAmounts $amounts): void {
if (filled($data['guests'] ?? null)) {
$this->record->update(['guests' => (int) $data['guests']]);
}
$amounts->handle(
$this->record->fresh(),
(int) $data['portal_total'],
array_map(fn (array $row): array => [...$row, 'amount' => (int) $row['amount']], array_values((array) ($data['amounts'] ?? []))),
array_map(fn (array $row): array => ['amount' => (int) $row['amount'], 'paid_on' => (string) $row['paid_on']], array_values((array) ($data['paid'] ?? []))),
$this->record->processChannel()?->name ?? 'Portal',
CarbonImmutable::parse($data['stated_on']),
auth()->user()?->name,
);
$this->record->refresh();
$blockers = app(CaseAutomation::class)->documentBlockers($this->record);
Notification::make()->title('Beträge gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
});
}
/**
* "Ändern" of a booking or internal case (package 5): dates, guests, services and price with the consequences shown
* before saving; either recorded as already agreed with the guest, or proposed to the guest for consent.
*/
private function changeAction(): Action
{
$own = fn (): bool => ! $this->record->isInternal() && ! $this->record->caseType()->isExternallyBinding();
return Action::make('change')
->label(fn (): string => $this->record->isInternal() ? 'Ändern oder verlängern …' : 'Buchung ändern …')
->icon(Heroicon::OutlinedPencil)
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->portal_cancellation_requested_at === null)
->modalHeading(fn (): string => $this->record->isInternal() ? 'Zeitraum oder Angaben ändern' : 'Buchung ändern')
->modalDescription('Tragen Sie ein, was sich ändert. Unten sehen Sie vor dem Speichern, was daraus folgt.')
->modalSubmitActionLabel('Speichern')
->modalWidth('4xl')
->fillForm(fn (): array => [
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all(),
'rent' => $this->record->isInternal() ? PrivateStayPrice::rentOf($this->record->quote) : null,
'tourist_tax_persons' => $this->record->tourist_tax_persons,
'way' => 'agreed',
'requested_by' => $this->record->caseType()->isExternallyBinding() ? 'portal' : 'guest',
'basis' => $this->record->caseType()->isExternallyBinding() ? ChangeBasis::Portal->value : ChangeBasis::Phone->value,
'agreed_at' => now()->format('Y-m-d H:i'),
'effective_on' => today()->toDateString(),
'send_confirmation' => false,
])
->schema(fn (): array => [
Section::make()->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise / Beginn')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise / Ende')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->live(onBlur: true)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block),
]),
Repeater::make('items')->label('Zusatzleistungen')->columns(2)->defaultItems(0)->addActionLabel('Leistung hinzufügen')->live()
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! $this->record->caseType()->isExternallyBinding())
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->where('property_id', $this->record->property_id)->orderBy('name')->pluck('name', 'id')->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
]),
Section::make('Preis')->columns(2)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block)->schema([
EuroInput::make('portal_total')->label('Neuer Gesamtpreis laut Portal')->helperText('Leer lassen, wenn das Portal den Preis nicht geändert hat.')->live(onBlur: true)
->visible(fn (): bool => $this->record->caseType()->isExternallyBinding()),
EuroInput::make('agreed_total')->label('Vereinbarter Gesamtpreis (optional)')->helperText('Leer lassen: Der Preis wird aus Ihren Preisen neu berechnet.')->live(onBlur: true)
->visible($own),
EuroInput::make('rent')->label('Vereinbarte Miete')->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
TextInput::make('tourist_tax_persons')->label('Kurabgabe: Personen')->integer()->minValue(0)->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
]),
View::make('filament.change-preview')->viewData(fn (Get $get): array => ['preview' => app(ChangeBooking::class)->preview($this->record, $this->changeData(self::formState($get, ['arrival', 'departure', 'guests', 'items', 'portal_total', 'agreed_total', 'rent', 'tourist_tax_persons'])))]),
Section::make('Grundlage')->columns(2)->visible(fn (): bool => ! $this->record->isInternal())->schema([
Radio::make('way')->label('Wie kommt die Änderung zustande?')->columnSpanFull()->live()->required()->options(fn (): array => array_filter([
'agreed' => 'Mit dem Gast bereits vereinbart – jetzt eintragen',
'propose' => $own() && filled($this->record->guest?->email) ? 'Dem Gast vorschlagen – wird erst mit seiner Zustimmung wirksam' : null,
])),
Select::make('requested_by')->label('Wer möchte die Änderung?')->options(BookingChange::REQUESTERS)->required(),
Select::make('basis')->label('Wie vereinbart?')->options(collect(ChangeBasis::cases())->reject(fn (ChangeBasis $basis): bool => in_array($basis, [ChangeBasis::GuestLink, ChangeBasis::NotNeeded], true))->mapWithKeys(fn (ChangeBasis $basis): array => [$basis->value => $basis->getLabel()])->all())
->visible(fn (Get $get): bool => $get('way') === 'agreed')->required(fn (Get $get): bool => $get('way') === 'agreed'),
DateTimePicker::make('agreed_at')->label('Vereinbart am')->seconds(false)->visible(fn (Get $get): bool => $get('way') === 'agreed'),
DatePicker::make('effective_on')->label('Wirksam ab'),
Toggle::make('send_confirmation')->label('Bestätigung der Änderung an den Gast senden')->visible(fn (Get $get): bool => $get('way') === 'agreed' && filled($this->record->guest?->email)),
]),
Textarea::make('reason')->label('Grund')->required()->rows(2),
])
->action(function (array $data, ChangeBooking $changes): void {
$meta = [
'requested_by' => $this->record->isInternal() ? 'landlord' : ($data['requested_by'] ?? 'landlord'),
'reason' => (string) $data['reason'],
'basis' => $this->record->isInternal() ? ChangeBasis::NotNeeded : ChangeBasis::from((string) ($data['basis'] ?? ChangeBasis::Phone->value)),
'agreed_at' => $data['agreed_at'] ?? null,
'effective_on' => $data['effective_on'] ?? null,
'send_confirmation' => (bool) ($data['send_confirmation'] ?? false),
];
$this->runWorkflow(fn () => ($data['way'] ?? 'agreed') === 'propose' && ! $this->record->isInternal()
? $changes->propose($this->record, $this->changeData($data), $meta, auth()->user()?->name)
: $changes->apply($this->record, $this->changeData($data), $meta, auth()->user()?->name), ($data['way'] ?? 'agreed') === 'propose' ? 'Vorschlag an den Gast gesendet' : 'Änderung gespeichert');
});
}
/**
* A booking binding on a portal is only cancelled here once the cancellation is effective on the portal.
*/
private function confirmPortalCancellationAction(): Action
{
$reported = fn (): bool => BookingTask::query()->where('booking_id', $this->record->id)->where('kind', BookingTaskKind::PortalCancellationReported)->where('status', BookingTaskStatus::Open)->exists();
return Action::make('confirmPortalCancellation')
->label(fn (): string => $reported() ? 'Stornierung übernehmen …' : 'Stornierung bestätigen …')
->icon(Heroicon::OutlinedCheckBadge)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->caseType()->isExternallyBinding()
&& ($this->record->portal_cancellation_requested_at !== null || $reported()))
->modalHeading('Ist die Stornierung im Portal wirksam?')
->modalDescription(fn (): string => 'Erst jetzt wird der Vorgang storniert und der Zeitraum frei. Bitte vorher im Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ nachsehen. Bleibt die Buchung im Portal bestehen, die Aufgabe einfach im Reiter „Aufgaben“ erledigen.')
->modalSubmitActionLabel('Storniert – übernehmen')
->fillForm(fn (): array => ['initiated_by' => $reported() ? 'portal' : 'landlord'])
->schema([
Radio::make('initiated_by')->label('Wer hat storniert?')->options(CancelBooking::INITIATORS)->required(),
Textarea::make('reason')->label('Grund / Hinweis')->rows(2),
Checkbox::make('effective')->label('Die Stornierung ist im Portal wirksam (geprüft).')->accepted(),
])
->action(fn (array $data, CancelBooking $cancel) => $this->runWorkflow(fn () => $cancel->confirmOnPortal($this->record, (string) auth()->user()?->name, $data['initiated_by'], $data['reason'] ?? null), 'Buchung storniert'));
}
private function withdrawChangeAction(): Action
{
return Action::make('withdrawChange')
->label('Änderungsvorschlag zurückziehen')
->icon(Heroicon::OutlinedArrowUturnLeft)
->visible(fn (): bool => $this->record->changes()->where('status', ChangeStatus::Proposed)->exists())
->requiresConfirmation()
->action(function (ChangeBooking $changes): void {
$changes->withdraw($this->record->changes()->where('status', ChangeStatus::Proposed)->firstOrFail(), auth()->user()?->name);
Notification::make()->title('Vorschlag zurückgezogen')->success()->send();
});
}
/**
* Form data of the change dialog as changes for {@see ChangeBooking}.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function changeData(array $data): array
{
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
if (filled($item['extra_id'] ?? null)) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) ($item['quantity'] ?? 1));
}
}
return array_filter([
'arrival' => $data['arrival'] ?? null,
'departure' => $data['departure'] ?? null,
'guests' => filled($data['guests'] ?? null) ? (int) $data['guests'] : null,
'extras' => $this->record->internal_kind === InternalKind::Block || $this->record->caseType()->isExternallyBinding() ? null : $extras,
'portal_total' => filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
'agreed_total' => filled($data['agreed_total'] ?? null) ? (int) $data['agreed_total'] : null,
'rent' => $this->record->isInternal() && filled($data['rent'] ?? null) ? (int) $data['rent'] : null,
'tourist_tax_persons' => $this->record->isInternal() && filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null,
], fn ($value): bool => $value !== null);
}
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 => ! $this->record->isInternal() && ! 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
{
// Own use, private stays and blocks have nothing that could run by itself.
if ($this->record->isInternal() || 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)
|| $this->record->portal_cancellation_requested_at !== null) {
return null;
}
if ($this->record->isInternal()) {
$label = EndInternalCase::label($this->record);
return Action::make('end')
->label($this->record->internal_kind === InternalKind::Block ? 'Sperre aufheben …' : 'Aufenthalt absagen …')
->icon(Heroicon::OutlinedStopCircle)
->color('danger')
->outlined()
->modalHeading($label)
->modalDescription('Keine Stornierung: Es entstehen keine Kosten und keine Mails. Der Zeitraum wird frei, die Portale werden wieder freigegeben.')
->modalSubmitActionLabel($this->record->internal_kind === InternalKind::Block ? 'Aufheben' : 'Absagen')
->schema([Textarea::make('reason')->label('Grund')->required()->rows(2)])
->action(fn (array $data, EndInternalCase $end) => $this->runWorkflow(fn () => $end->handle($this->record, trim((string) $data['reason']), auth()->user()?->name), $label));
}
$binding = $this->record->isBinding();
$external = $binding && $this->record->caseType()->isExternallyBinding();
$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(match (true) {
$external => 'Gebucht wurde beim Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ – storniert wird dort. Hier entsteht die Aufgabe, die Stornierung im Portal zu veranlassen; der Vorgang bleibt gebucht, bis Sie bestätigen, dass sie dort wirksam ist. Nichts wird still gelöscht.',
$binding => 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel und eine mögliche Erstattung bleiben als Aufgaben offen.',
default => 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.',
})
->modalSubmitActionLabel($external ? 'Stornierung veranlassen' : ($binding ? 'Stornieren' : 'Beenden'))
->schema(array_values(array_filter([
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options($external ? CancelBooking::INITIATORS : ['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
Textarea::make('reason')->label('Grund')->required()->rows(2),
$external ? null : Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding && ! $external ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
])))
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $external, $hasEmail): void {
$notify = ! $external && $hasEmail && (bool) ($data['notify'] ?? false);
$reason = trim((string) $data['reason']);
try {
$informed = CaseLog::context(fn () => $binding
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'], $reason)
: $decline->handle($this->record, $notify), reason: $reason);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
$notification = Notification::make()->title(match (true) {
$external => 'Stornierung im Portal veranlassen',
$binding => 'Buchung storniert',
default => '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();
}
}