Antwortart (Auskunft/Angebot) und Reservierung sind entkoppelt (neue Einstellung inquiry_answer; pre_reservation bleibt die Reservierungsstrategie). Anlass-bezogene Absender für Anreise-Information und Bewertungsbitte; Schablonen liefern Standardwerte unterhalb aller einstellbaren Ebenen. A1/A2 bleiben Voreinstellungen und Altfassungen. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
300 lines
19 KiB
PHP
300 lines
19 KiB
PHP
<?php
|
||
|
||
namespace App\Filament\Resources\Bookings\Pages\Concerns;
|
||
|
||
use App\Actions\CloseStay;
|
||
use App\Actions\DecideBookingWish;
|
||
use App\Actions\PrepareStays;
|
||
use App\Actions\SendInformation;
|
||
use App\Actions\SendOffer;
|
||
use App\Availability\AvailabilityChecker;
|
||
use App\Enums\BookingStatus;
|
||
use App\Enums\BookingTaskKind;
|
||
use App\Enums\BookingTaskStatus;
|
||
use App\Enums\DocumentKind;
|
||
use App\Enums\InquiryAnswer;
|
||
use App\Enums\IntakeKind;
|
||
use App\Enums\Responsibility;
|
||
use App\Exceptions\ReservationException;
|
||
use App\Filament\Forms\DocumentCompositionFields;
|
||
use App\Models\Booking;
|
||
use App\Models\BookingTask;
|
||
use App\Pricing\CaseMoney;
|
||
use App\Pricing\StayRequest;
|
||
use App\Process\CaseClosure;
|
||
use App\Process\CaseLog;
|
||
use App\Support\Money;
|
||
use Filament\Actions\Action;
|
||
use Filament\Forms\Components\DatePicker;
|
||
use Filament\Forms\Components\DateTimePicker;
|
||
use Filament\Forms\Components\Hidden;
|
||
use Filament\Forms\Components\Radio;
|
||
use Filament\Forms\Components\Select;
|
||
use Filament\Forms\Components\Textarea;
|
||
use Filament\Forms\Components\TextInput;
|
||
use Filament\Notifications\Notification;
|
||
use Filament\Schemas\Components\Section;
|
||
use Filament\Schemas\Components\Text;
|
||
use Filament\Schemas\Components\Utilities\Get;
|
||
use Filament\Support\Icons\Heroicon;
|
||
use Throwable;
|
||
|
||
/**
|
||
* Case page actions of packages 7 and 9: the information "unter Vorbehalt" and the decision on a booking wish; arrival
|
||
* details, tasks of the stay (done, handed over, newly noted), closing the stay and settling the case commercially.
|
||
*
|
||
* @property Booking $record
|
||
*/
|
||
trait HandlesWishAndStay
|
||
{
|
||
private function sendInformationAction(): Action
|
||
{
|
||
return Action::make('sendInformation')
|
||
->label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden')
|
||
->icon(Heroicon::OutlinedPaperAirplane)
|
||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking
|
||
&& $this->record->process()->inquiryAnswer() === InquiryAnswer::Information && $this->record->offer_version === 0 && ! $this->record->isHoldActive())
|
||
->modalHeading('Unverbindliche Auskunft an den Gast')
|
||
->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.')
|
||
->modalSubmitActionLabel('Senden')
|
||
->modalWidth('4xl')
|
||
->fillForm(fn (): array => [
|
||
'expected_version' => $this->record->information_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,
|
||
])
|
||
->schema([
|
||
Hidden::make('expected_version'),
|
||
...DocumentCompositionFields::make($this->record, DocumentKind::Information, 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']))),
|
||
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
|
||
Section::make('Anpassen')->description('Zeitraum, Preis und wie lange der Gast die Buchung anfragen kann.')->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),
|
||
]),
|
||
DateTimePicker::make('valid_until')->label('Buchung anfragen bis')->helperText('Der Zeitraum bleibt bis dahin trotzdem frei buchbar für andere.')->seconds(false)->after('now')->required()->live(onBlur: true),
|
||
]),
|
||
])
|
||
->action(fn (array $data, SendInformation $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Auskunft gesendet'));
|
||
}
|
||
|
||
private function decideWishAction(): Action
|
||
{
|
||
return Action::make('decideWish')
|
||
->label('Buchungswunsch bestätigen oder absagen …')
|
||
->icon(Heroicon::OutlinedCheckCircle)
|
||
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved && $this->record->wish_at !== null)
|
||
->modalHeading('Buchungswunsch des Gastes')
|
||
->modalDescription(fn (): string => 'Angefragt am '.$this->record->wish_at?->format('d.m.Y, H:i').' Uhr. Bei „Bestätigen“ wird die Verfügbarkeit noch einmal geprüft; der Gast erhält die Buchungsbestätigung mit dem Mietvertrag.')
|
||
->modalSubmitActionLabel('Ausführen')
|
||
->schema(fn (): array => [
|
||
Text::make($this->wishCheckText()),
|
||
Radio::make('decision')->label('Entscheidung')->required()->default('confirm')->live()->options(array_filter([
|
||
'confirm' => 'Bestätigen zum Preis der Auskunft ('.Money::format((int) $this->record->total).')',
|
||
'confirm_today' => $this->todaysTotal() !== null && $this->todaysTotal() < (int) $this->record->total ? 'Bestätigen zum heutigen, niedrigeren Preis ('.Money::format((int) $this->todaysTotal()).')' : null,
|
||
'decline' => 'Absagen – der Gast erhält eine freundliche Absage',
|
||
])),
|
||
Textarea::make('reason')->label('Grund (nur für den Verlauf)')->rows(2)->visible(fn (Get $get): bool => $get('decision') === 'decline'),
|
||
])
|
||
->action(function (array $data, DecideBookingWish $decide): void {
|
||
$this->runWorkflow(fn () => match ($data['decision']) {
|
||
'decline' => $decide->decline($this->record, $data['reason'] ?? null),
|
||
default => $decide->confirm($this->record, $data['decision'] === 'confirm_today'),
|
||
}, $data['decision'] === 'decline' ? 'Abgesagt' : 'Buchung bestätigt');
|
||
});
|
||
}
|
||
|
||
private function arrivalDetailsAction(): Action
|
||
{
|
||
return Action::make('arrivalDetails')
|
||
->label('Anreisedaten eintragen')
|
||
->icon(Heroicon::OutlinedClock)
|
||
->visible(fn (): bool => $this->record->isBinding() && ! $this->record->isInternal() && $this->record->departure->isFuture())
|
||
->modalHeading('Anreisedaten')
|
||
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Was fehlt, steht in der Aufgabe; nur Bekanntes eintragen.')
|
||
->fillForm(fn (): array => ['arrival_time' => $this->record->arrival_time, 'email' => $this->record->guest?->email, 'phone' => $this->record->guest?->phone])
|
||
->schema([
|
||
TextInput::make('arrival_time')->label('Anreisezeit')->placeholder('z. B. gegen 16 Uhr')->maxLength(40),
|
||
TextInput::make('phone')->label('Telefon des Gastes')->tel()->maxLength(50)->visible(fn (): bool => $this->record->guest !== null),
|
||
TextInput::make('email')->label('E-Mail des Gastes')->email()->maxLength(255)->visible(fn (): bool => $this->record->guest !== null),
|
||
])
|
||
->action(function (array $data): void {
|
||
$this->record->update(['arrival_time' => filled($data['arrival_time'] ?? null) ? trim((string) $data['arrival_time']) : null]);
|
||
if ($this->record->guest !== null) {
|
||
$this->record->guest->update(array_filter(['phone' => $data['phone'] ?? null, 'email' => isset($data['email']) ? mb_strtolower(trim((string) $data['email'])) : null], fn ($value): bool => filled($value)));
|
||
}
|
||
app(PrepareStays::class)->handle();
|
||
$this->record->refresh();
|
||
Notification::make()->title('Gespeichert')->success()->send();
|
||
});
|
||
}
|
||
|
||
private function completeTaskAction(): Action
|
||
{
|
||
return Action::make('completeTask')
|
||
->label('Aufgabe erledigen …')
|
||
->icon(Heroicon::OutlinedCheck)
|
||
->visible(fn (): bool => $this->openTasks() !== [])
|
||
->modalHeading('Aufgabe erledigen')
|
||
->modalDescription('Erledigt oder an jemanden übergeben (z. B. Reinigung, Portal, Steuerberater). Die Notiz steht im Verlauf.')
|
||
->fillForm(fn (): array => ['task' => array_key_first($this->openTasks()), 'outcome' => 'done'])
|
||
->schema([
|
||
Select::make('task')->label('Aufgabe')->options(fn (): array => $this->openTasks())->required(),
|
||
Radio::make('outcome')->label('Ergebnis')->required()->options([
|
||
'done' => 'Erledigt',
|
||
'handed_over' => 'Übergeben – jemand anderes kümmert sich',
|
||
'dismissed' => 'Entfällt',
|
||
])->live(),
|
||
TextInput::make('handed_to')->label('Übergeben an')->maxLength(120)->required(fn (Get $get): bool => $get('outcome') === 'handed_over')->visible(fn (Get $get): bool => $get('outcome') === 'handed_over'),
|
||
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
|
||
])
|
||
->action(function (array $data): void {
|
||
$task = BookingTask::query()->where('booking_id', $this->record->id)->whereKey($data['task'])->where('status', BookingTaskStatus::Open)->first();
|
||
if ($task === null) {
|
||
Notification::make()->title('Diese Aufgabe ist schon erledigt.')->warning()->send();
|
||
|
||
return;
|
||
}
|
||
$note = trim(implode(' · ', array_filter([$data['outcome'] === 'handed_over' ? 'Übergeben an '.$data['handed_to'] : null, $data['note'] ?? null])));
|
||
if ($data['outcome'] === 'dismissed') {
|
||
$task->update(['status' => BookingTaskStatus::Dismissed, 'note' => $note !== '' ? $note : $task->note, 'completed_by' => CaseLog::actor(), 'completed_at' => now()]);
|
||
} else {
|
||
if ($data['outcome'] === 'handed_over') {
|
||
$task->responsible = (string) $data['handed_to'];
|
||
}
|
||
$task->complete(CaseLog::actor(), $note !== '' ? $note : null);
|
||
}
|
||
$this->record->refresh();
|
||
Notification::make()->title('Aufgabe vermerkt')->success()->send();
|
||
});
|
||
}
|
||
|
||
private function addTaskAction(): Action
|
||
{
|
||
return Action::make('addTask')
|
||
->label('Abweichung oder Aufgabe festhalten …')
|
||
->icon(Heroicon::OutlinedPencilSquare)
|
||
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying(), BookingStatus::Cancelled], true))
|
||
->modalHeading('Abweichung oder Aufgabe festhalten')
|
||
->modalDescription('Zum Aufenthalt (z. B. späte Anreise, defekte Kaffeemaschine, Schaden) – als Aufgabe am Vorgang, keine eigene Verwaltung.')
|
||
->schema([
|
||
Radio::make('kind')->label('Art')->required()->default(BookingTaskKind::Issue->value)->options([
|
||
BookingTaskKind::Issue->value => 'Abweichung oder Problem beim Aufenthalt – muss vor dem Abschluss des Aufenthalts geklärt sein',
|
||
BookingTaskKind::Service->value => 'Leistung vorbereiten (z. B. Kinderbett, zusätzliche Reinigung)',
|
||
BookingTaskKind::FollowUp->value => 'Folgeaufgabe nach dem Aufenthalt (z. B. Schaden abrechnen, Reparatur) – hält den Abschluss nicht auf',
|
||
]),
|
||
TextInput::make('title')->label('Was?')->required()->maxLength(200),
|
||
TextInput::make('responsible')->label('Wer kümmert sich? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120),
|
||
DatePicker::make('due_on')->label('Bis wann? (optional)'),
|
||
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
|
||
])
|
||
->action(function (array $data): void {
|
||
BookingTask::openOnce($this->record, BookingTaskKind::from($data['kind']), 'manual:'.now()->format('YmdHisv'), [
|
||
'title' => trim((string) $data['title']),
|
||
'responsible' => filled($data['responsible'] ?? null) ? trim((string) $data['responsible']) : null,
|
||
'due_on' => $data['due_on'] ?? null,
|
||
'note' => $data['note'] ?? null,
|
||
]);
|
||
$this->record->refresh();
|
||
Notification::make()->title('Festgehalten')->success()->send();
|
||
});
|
||
}
|
||
|
||
private function closeStayAction(): Action
|
||
{
|
||
return Action::make('closeStay')
|
||
->label(fn (): string => $this->record->isInternal() ? 'Abschließen …' : 'Aufenthalt abschließen …')
|
||
->icon(Heroicon::OutlinedFlag)
|
||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true) && ! $this->record->departure->isFuture())
|
||
->modalHeading('Aufenthalt abschließen')
|
||
->modalDescription(fn (): string => ($blockers = CaseClosure::stayBlockers($this->record))->isEmpty()
|
||
? 'Für den Aufenthalt ist nichts mehr offen. Offene Zahlungen oder Auszahlungen bleiben als kaufmännische Punkte am Vorgang.'
|
||
: 'Noch offen für den Aufenthalt: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', ').'. Mit dem Abschluss werden sie als erledigt bzw. übergeben vermerkt.')
|
||
->schema([Textarea::make('note')->label('Notiz (z. B. „Reinigung erledigt, Schlüssel zurück“)')->rows(2)->maxLength(500)])
|
||
->action(fn (array $data, CloseStay $close) => $this->runWorkflow(fn () => $close->byHand($this->record, CaseLog::actor(), $data['note'] ?? null), 'Aufenthalt abgeschlossen'));
|
||
}
|
||
|
||
private function settleAction(): Action
|
||
{
|
||
return Action::make('settle')
|
||
->label('Kaufmännisch abschließen …')
|
||
->icon(Heroicon::OutlinedBanknotes)
|
||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null)
|
||
->modalHeading('Kaufmännisch abschließen')
|
||
->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).')
|
||
->schema([
|
||
// Decision O5: with portal collection an open payout needs its financial clarification, not only a reason.
|
||
Select::make('clarification')->label('Wie ist die Auszahlung geklärt?')
|
||
->options(CaseClosure::PAYOUT_CLARIFICATIONS)
|
||
->visible(fn (): bool => $this->payoutOpen())
|
||
->required(fn (): bool => $this->payoutOpen())
|
||
->helperText('Eine Meldung des Portals über die Auszahlung ist kein Nachweis des Geldeingangs. „Als offene Forderung weiterführen“ legt eine Aufgabe an; der Vorgang bleibt kaufmännisch offen.'),
|
||
Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500),
|
||
])
|
||
->action(function (array $data): void {
|
||
try {
|
||
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor(), $data['clarification'] ?? null);
|
||
} catch (ReservationException $exception) {
|
||
Notification::make()->title('Nicht abgeschlossen')->body($exception->getMessage())->danger()->send();
|
||
|
||
return;
|
||
}
|
||
$this->record->refresh();
|
||
Notification::make()->title($this->record->settled_at !== null ? 'Kaufmännisch abgeschlossen' : 'Als offene Forderung weitergeführt')->success()->send();
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Whether the portal's payout is open or deviating (decision O5).
|
||
*/
|
||
private function payoutOpen(): bool
|
||
{
|
||
return CaseMoney::of($this->record)->collector() === Responsibility::Portal
|
||
&& collect(CaseClosure::commercialPoints($this->record))->contains(fn (string $point): bool => str_contains($point, 'Auszahlung'));
|
||
}
|
||
|
||
/**
|
||
* Open tasks the landlord can settle on the page (not the ones with an action of their own).
|
||
*
|
||
* @return array<int, string>
|
||
*/
|
||
private function openTasks(): array
|
||
{
|
||
return BookingTask::query()->where('booking_id', $this->record->id)->where('status', BookingTaskStatus::Open)
|
||
->whereNotIn('kind', [BookingTaskKind::BookingWish, BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
|
||
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get()
|
||
->mapWithKeys(fn (BookingTask $task): array => [$task->id => $task->label().($task->due_on ? ' (fällig '.$task->due_on->format('d.m.Y').')' : '')])->all();
|
||
}
|
||
|
||
private function wishCheckText(): string
|
||
{
|
||
$wish = (array) ($this->record->wish ?? []);
|
||
$findings = (array) ($wish['findings'] ?? []);
|
||
$available = app(AvailabilityChecker::class)->isAvailable($this->record->property, $this->record->arrival, $this->record->departure, ignore: $this->record);
|
||
|
||
return ($available ? 'Der Zeitraum ist im Moment frei. ' : 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. ')
|
||
.($findings === [] ? 'Bei der Prüfung des Wunsches war alles in Ordnung.' : 'Bei der Prüfung des Wunsches fiel auf: '.implode(' ', $findings));
|
||
}
|
||
|
||
private function todaysTotal(): ?int
|
||
{
|
||
try {
|
||
return app(SendOffer::class)->quoteFor($this->record, new StayRequest($this->record->arrival, $this->record->departure, $this->record->guests, $this->record->extras ?? [], $this->record->promo_code), (int) $this->record->price_adjustment, (string) ($this->record->price_adjustment_label ?: 'Zuschlag'))->total();
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
}
|
||
}
|