diff --git a/app/Actions/OpenPortalFile.php b/app/Actions/OpenPortalFile.php new file mode 100644 index 0000000..393cf05 --- /dev/null +++ b/app/Actions/OpenPortalFile.php @@ -0,0 +1,91 @@ +whereKey($block->property_id)->lockForUpdate()->firstOrFail(); + $block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail(); + + if (! in_array($block->source, ['channel', 'email'], true) || $block->channel_id === null) { + throw new ReservationException('Eine Akte gibt es nur für Reservierungen aus einem Portalkalender.'); + } + if ($block->occupationKind() === OccupationKind::Block) { + throw new ReservationException('Eine Sperrzeit ist keine Reservierung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.'); + } + if ($block->is_representation && $block->linked_booking_id !== null) { + return Booking::query()->findOrFail($block->linked_booking_id); + } + if ($block->is_representation) { + throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Die Akte gehört an die führende Belegung.'); + } + + $property = $block->property; + $channel = $block->channel; + $fields = (array) ($block->ical_interpretation['fields'] ?? []); + $guest = $block->guest ?? Guest::query()->create([ + 'first_name' => filled($fields['guest_first_name'] ?? null) ? (string) $fields['guest_first_name'] : 'Gast', + 'last_name' => '('.$channel->name.')', + 'email' => '', + 'tenant_id' => app(TenantContext::class)->id(), + ]); + + $stay = new StayRequest(CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), min(2, $property->max_guests)); + $booking = $property->bookings()->create([ + 'guest_id' => $guest->id, + 'status' => BookingStatus::Reserved, + 'source' => 'portal', + 'origin_channel_id' => $block->origin_channel_id ?? $channel->id, + 'portal_reference' => $fields['booking_reference'] ?? null, + 'arrival' => $stay->arrival->toDateString(), + 'departure' => $stay->departure->toDateString(), + 'guests' => $stay->guests, + 'hold_expires_at' => null, + 'internal_notes' => 'Akte aus dem Portalkalender „'.$channel->name.'“ angelegt. Personenzahl und Preis sind nicht bekannt – bitte den Portalpreis erfassen.', + ...$this->price->unknownColumns($property, $stay), + ]); + + $block->forceFill([ + 'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null, + 'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(), + 'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest->id, + 'review_note' => 'Akte angelegt; die Buchung führt diese Belegung.', + ])->save(); + + app(ConfirmBooking::class)->bind($booking); + app(ReconcileChannelRepresentations::class)->handle($property); + + return $booking->refresh(); + }); + } +} diff --git a/app/Actions/RecordPortalBooking.php b/app/Actions/RecordPortalBooking.php index f9460b4..e420d75 100644 --- a/app/Actions/RecordPortalBooking.php +++ b/app/Actions/RecordPortalBooking.php @@ -2,14 +2,12 @@ namespace App\Actions; -use App\Enums\QuoteLineType; use App\Exceptions\ReservationException; use App\Models\Booking; use App\Models\Channel; use App\Models\Property; -use App\Pricing\PriceCalculator; +use App\Pricing\PortalPrice; use App\Pricing\QuoteException; -use App\Pricing\QuoteLine; use App\Pricing\StayRequest; use Illuminate\Support\Facades\DB; @@ -34,7 +32,7 @@ class RecordPortalBooking public function __construct( private CreateReservation $create, private ConfirmBooking $confirm, - private PriceCalculator $calculator, + private PortalPrice $price, ) {} /** @@ -60,7 +58,7 @@ public function handle(Property $property, Channel $channel, StayRequest $stay, $changes['guest_confirmed_at'] = now(); } if ($portalTotal !== null) { - $changes += $this->priceOf($property, $stay, $portalTotal); + $changes += $this->price->columns($property, $stay, $portalTotal); } $booking->update($changes); @@ -76,32 +74,4 @@ public function handle(Property $property, Channel $channel, StayRequest $stay, return $booking->refresh(); } - - /** - * Price columns for a booking whose portal price differs from our own calculation: the difference becomes an - * adjustment line, so the quote still adds up to what the portal charged. - * - * @return array - * - * @throws QuoteException - */ - private function priceOf(Property $property, StayRequest $stay, int $portalTotal): array - { - $quote = $this->calculator->calculate($property, $stay); - $difference = $portalTotal - $quote->total(); - if ($difference === 0) { - return []; - } - - $difference = max($difference, -$quote->rent()); - $quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, 'Abweichung Portalpreis', 1, $difference, $difference)); - - return [ - 'price_adjustment' => $difference, - 'price_adjustment_label' => 'Abweichung Portalpreis', - 'quote' => $quote->toArray(), - 'total' => $quote->total(), - 'deposit' => $quote->deposit(), - ]; - } } diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index 651b99e..0245c6c 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -2,6 +2,7 @@ namespace App\Filament\Resources\Bookings\Schemas; +use App\Documents\OfferTerms; use App\Models\Booking; use App\Support\BookingProgress; use App\Support\Money; @@ -17,19 +18,59 @@ class BookingInfolist { /** - * The steps of the process as a row of chips. + * The process as a checklist: every milestone with its state and the activities that belong to it. Open + * activities name the action on this page that does them. */ private static function timeline(Booking $booking): HtmlString { - $style = [ - 'done' => 'background:#dcfce7;color:#14532d', - 'current' => 'background:#fef3c7;color:#78350f;font-weight:700', - 'todo' => 'background:#f3f4f6;color:#4b5563', - 'skipped' => 'background:#f3f4f6;color:#9ca3af;text-decoration:line-through', + $badge = [ + 'done' => ['✓', '#16a34a', 'erledigt'], + 'current' => ['●', '#d97706', 'jetzt'], + 'todo' => ['○', '#9ca3af', 'später'], + 'skipped' => ['–', '#9ca3af', 'entfällt'], ]; - $icon = ['done' => '✓ ', 'current' => '● ', 'todo' => '', 'skipped' => '']; - return new HtmlString('
'.collect(BookingProgress::steps($booking))->map(fn (array $step): string => ''.$icon[$step['state']].e($step['label']).($step['detail'] ? ' · '.e($step['detail']) : '').'')->implode('').'
'); + $rows = collect(BookingProgress::steps($booking))->map(function (array $step) use ($badge): string { + [$icon, $color, $word] = $badge[$step['state']]; + $activities = collect($step['activities'])->map(fn (array $activity): string => '
  • '.($activity['done'] ? '✓ ' : '○ ').e($activity['label']).($activity['action'] && $step['state'] !== 'skipped' ? ' → Aktion „'.e($activity['action']).'“' : '').'
  • ')->implode(''); + + return '
    ' + .'
    '.$icon.'
    ' + .'
    '.e($step['label']).($step['detail'] ? ' · '.e($step['detail']).'' : '').'
    ' + .($activities !== '' ? '
      '.$activities.'
    ' : '').'
    '; + })->implode(''); + + return new HtmlString('
    '.$rows.'
    '); + } + + /** + * What has happened so far, oldest first. + */ + private static function chronicle(Booking $booking): HtmlString + { + $rows = collect(BookingProgress::history($booking))->map(fn (array $event): string => '
  • '.$event['at']->format('d.m.Y H:i').' · '.e($event['label']).'
  • ')->implode(''); + + return new HtmlString(''); + } + + /** + * The standard process that applies to this booking: which template (with cancellation rule and annexes) comes from + * the portal and booking type, and whether payments become tasks. + */ + private static function setup(Booking $booking): string + { + $channel = $booking->importChannel ?? $booking->originChannel; + $template = OfferTerms::templateFor($booking); + $policy = $template?->cancellationPolicy; + $annexes = $template?->annexesFor($booking)->map(fn ($annex) => $annex->name)->implode(', '); + + return collect([ + $channel ? 'Portal: '.$channel->name : 'Eigene Buchung (Webseite / manuell)', + 'Vertragsvorlage: '.($template ? $template->label() : 'Texte der Webseite'), + 'Stornoregel: '.($policy ? $policy->name : 'keine hinterlegt'), + 'Anlagen: '.($annexes ?: 'keine'), + 'Zahlungsaufgaben: '.($booking->wantsPaymentTasks() ? 'ja' : 'nein (läuft über das Portal)'), + ])->implode(' · '); } public static function configure(Schema $schema): Schema @@ -46,11 +87,20 @@ public static function configure(Schema $schema): Schema ->state(fn (Booking $record): string => BookingProgress::next($record)['text']) ->color(fn (Booking $record): string => BookingProgress::next($record)['color']) ->weight('bold'), + TextEntry::make('setup') + ->label('Standardprozess (aus Portal und Buchungstyp)') + ->state(fn (Booking $record): string => self::setup($record)) + ->columnSpanFull(), TextEntry::make('steps') - ->label('Verlauf') + ->label('Ablauf: Meilensteine und Aktivitäten') ->state(fn (Booking $record): HtmlString => self::timeline($record)) ->html() ->columnSpanFull(), + TextEntry::make('chronicle') + ->label('Bisheriger Verlauf') + ->state(fn (Booking $record): HtmlString => self::chronicle($record)) + ->html() + ->columnSpanFull(), ]), Grid::make(1) ->columnSpan(2) diff --git a/app/Filament/Resources/Bookings/Tables/BookingsTable.php b/app/Filament/Resources/Bookings/Tables/BookingsTable.php index 6ba19ea..77b78b2 100644 --- a/app/Filament/Resources/Bookings/Tables/BookingsTable.php +++ b/app/Filament/Resources/Bookings/Tables/BookingsTable.php @@ -102,6 +102,6 @@ public static function configure(Table $table, ?int $guestId = null): Table Filter::make('without_guest')->label('Gastzuordnung offen'), ]) ->recordUrl(fn (array $record): string => $record['url']) - ->recordActions([Action::make('view')->label(fn (array $record): string => $record['record_type'] === 'booking' ? 'Akte öffnen' : 'Details')->icon('heroicon-o-folder-open')->button()->color('primary')->url(fn (array $record): string => $record['url'])]); + ->recordActions([Action::make('view')->label(fn (array $record): string => $record['record_type'] === 'booking' ? 'Akte öffnen' : ($record['kind'] === 'block' ? 'Details' : 'Akte anlegen'))->icon('heroicon-o-folder-open')->button()->color('primary')->url(fn (array $record): string => $record['url'])]); } } diff --git a/app/Filament/Resources/Channels/Schemas/ChannelForm.php b/app/Filament/Resources/Channels/Schemas/ChannelForm.php index 6e8d22b..df5c9db 100644 --- a/app/Filament/Resources/Channels/Schemas/ChannelForm.php +++ b/app/Filament/Resources/Channels/Schemas/ChannelForm.php @@ -8,6 +8,7 @@ use App\Enums\ChannelExportMode; use App\Enums\ChannelStatus; use App\Models\Channel; +use App\Models\ContractAnnex; use App\Models\ContractTemplate; use App\Models\Property; use App\Support\CurrentProperty; @@ -18,6 +19,7 @@ use Filament\Forms\Components\Toggle; use Filament\Infolists\Components\TextEntry; use Filament\Schemas\Components\Group; +use Filament\Schemas\Components\Section; use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Schema; @@ -51,24 +53,32 @@ public static function configure(Schema $schema, bool $selectProperty = false): Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(), Select::make('booking_model')->label('Buchungsmodell')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required() ->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'), - Select::make('contract_template_id') - ->label('Vertragsvorlage für Anfragen / Angebote über dieses Portal') - ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) - ->placeholder('Standard der Wohnung') - ->helperText('Für Angebote zu Buchungen, die über dieses Portal kommen und dessen Vorgaben (z. B. Stornofristen) entsprechen müssen.'), - Select::make('contract_template_reservation_id') - ->label('Vertragsvorlage für Buchungen, die beim Portal verbindlich sind') - ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) - ->placeholder('wie bei Anfragen') - ->helperText('Z. B. der FeWo-direkt-Vertrag für Direktbuchungen (Zahlung läuft über das Portal).'), - Toggle::make('payment_tasks_inquiry') - ->label('Zahlungsaufgaben bei Anfragen über dieses Portal') - ->helperText('Fällige Anzahlungen/Restzahlungen erscheinen als Aufgabe (Mails an Gäste gehen nie automatisch).') - ->default(true), - Toggle::make('payment_tasks_reservation') - ->label('Zahlungsaufgaben bei Reservierungen über dieses Portal') - ->helperText('Aus, wenn das Portal das Geld einzieht und mahnt (z. B. FeWo-direkt Online-Buchung).') - ->default(false), + Section::make('Standardprozess für Buchungen über dieses Portal') + ->description('Hier legen Sie fest, was bei einer Buchung über dieses Portal gilt – getrennt nach Buchungstyp. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Vertragsanlagen mit (Menü Einrichtung › Vertragsvorlagen). Der Ablauf selbst (Kontaktdaten, Vertrag, Zahlung, Anreise) steht in der Akte jeder Buchung.') + ->columns(2) + ->columnSpanFull() + ->schema([ + Select::make('contract_template_id') + ->label('Anfrage über dieses Portal: Vertragsvorlage') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) + ->placeholder('Standard der Wohnung') + ->live() + ->helperText(fn (Get $get): string => self::templateSummary($get('contract_template_id'), 'Wir antworten persönlich, Angebot und Vertrag kommen von uns. ')), + Select::make('contract_template_reservation_id') + ->label('Buchung beim Portal verbindlich: Vertragsvorlage') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) + ->placeholder('wie bei Anfragen') + ->live() + ->helperText(fn (Get $get): string => self::templateSummary($get('contract_template_reservation_id') ?? $get('contract_template_id'), 'Das Portal hat die Buchung schon verbindlich gemacht, wir senden den Vertrag. ')), + Toggle::make('payment_tasks_inquiry') + ->label('Anfrage über dieses Portal: Zahlungsaufgaben anlegen') + ->helperText('Fällige Anzahlungen/Restzahlungen erscheinen als Aufgabe (Mails an Gäste gehen nie automatisch).') + ->default(true), + Toggle::make('payment_tasks_reservation') + ->label('Buchung beim Portal verbindlich: Zahlungsaufgaben anlegen') + ->helperText('Aus, wenn das Portal das Geld einzieht und mahnt (z. B. FeWo-direkt Online-Buchung).') + ->default(false), + ]), Select::make('connector') ->label('Kalenderanbindung') ->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.') @@ -114,4 +124,19 @@ public static function configure(Schema $schema, bool $selectProperty = false): ->columnSpanFull(), ]); } + + /** + * What a contract template brings along, shown under the template choice. + */ + private static function templateSummary(mixed $templateId, string $intro): string + { + $template = filled($templateId) ? ContractTemplate::query()->with('cancellationPolicy')->find($templateId) : null; + if ($template === null) { + return $intro.'Ohne Auswahl gilt die Vorlage der Wohnung bzw. die Texte der Webseite.'; + } + + $annexes = ContractAnnex::query()->whereIn('id', (array) ($template->annex_ids ?? []))->orderBy('name')->pluck('name')->implode(', '); + + return $intro.'Die Vorlage bringt mit: Stornoregel '.($template->cancellationPolicy?->name ?? '– keine –').' · Anlagen: '.($annexes ?: 'keine').'.'; + } } diff --git a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php index 054ca7a..5e2acd4 100644 --- a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php +++ b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php @@ -3,7 +3,9 @@ namespace App\Filament\Resources\PortalOccupations; use App\Actions\ClassifyPortalOccupation; +use App\Actions\OpenPortalFile; use App\Enums\OccupationKind; +use App\Exceptions\ReservationException; use App\Filament\Actions\AssignGuestAction; use App\Filament\Concerns\FollowsAdminMode; use App\Filament\Concerns\SelectsRecordProperty; @@ -78,18 +80,61 @@ public static function table(Table $table): Table TextColumn::make('channel.name')->label('Importkanal'), TextColumn::make('property.name')->label('Wohnung')->toggleable(), TextColumn::make('needs_review')->label('Prüffall')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->description(fn (BlockedPeriod $record): ?string => $record->review_note), - ])->recordActions([ViewAction::make(), ActionGroup::make(static::occupationActions())->label('Weitere Aktionen')]); + ])->recordActions([Action::make('fileLink')->label('Akte anlegen')->icon(Heroicon::OutlinedFolderPlus)->button()->color('primary')->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), static::showFileAction()->button(), ViewAction::make(), ActionGroup::make(static::occupationActions(withFile: false))->label('Weitere Aktionen')]); } - public static function occupationActions(): array + public static function occupationActions(bool $withFile = true): array { return [ + ...($withFile ? [static::openFileAction(), static::showFileAction()] : []), AssignGuestAction::make(), static::classificationAction(), ...BlockedPeriodResource::portalActions(), ]; } + /** + * Opens the booking file (workflow, contract, payments, tasks) for a reservation from a portal calendar. + */ + public static function openFileAction(): Action + { + return Action::make('openFile')->label('Akte anlegen')->icon(Heroicon::OutlinedFolderPlus)->color('primary') + ->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record)) + ->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) + ->requiresConfirmation() + ->modalHeading('Akte für diese Reservierung anlegen') + ->modalDescription('Aus der Kalenderbelegung wird eine Buchung mit Ablauf: Kontaktdaten, Vertrag, Zahlungen, Anreise, Storno. Der Zeitraum bleibt durchgehend belegt. Gast, Personenzahl und Preis sind noch unbekannt und werden in der Akte ergänzt.') + ->action(function (BlockedPeriod $record, OpenPortalFile $open) { + try { + $booking = $open->handle($record); + } catch (ReservationException $exception) { + Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); + + return null; + } + + Notification::make()->title('Akte angelegt')->success()->send(); + + return redirect(BookingResource::getUrl('view', ['record' => $booking])); + }); + } + + public static function showFileAction(): Action + { + return Action::make('showFile')->label('Akte öffnen')->icon(Heroicon::OutlinedFolderOpen)->color('primary') + ->visible(fn (BlockedPeriod $record): bool => $record->linked_booking_id !== null) + ->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : null); + } + + /** + * Whether the calendar entry is a reservation that can still get its own booking file. + */ + public static function canOpenFile(BlockedPeriod $record): bool + { + return in_array($record->source, ['channel', 'email'], true) && ! $record->trashed() && ! $record->is_representation + && $record->channel_id !== null && $record->occupationKind() !== OccupationKind::Block; + } + public static function classificationAction(): Action { return Action::make('classify')->label('Einordnen: Reservierung, Sperrzeit oder unbekannt') diff --git a/app/Pricing/PortalPrice.php b/app/Pricing/PortalPrice.php new file mode 100644 index 0000000..3944bfd --- /dev/null +++ b/app/Pricing/PortalPrice.php @@ -0,0 +1,74 @@ + booking columns (quote, total, deposit, price_adjustment, ...) + */ + public function columns(Property $property, StayRequest $stay, int $portalTotal): array + { + try { + $quote = $this->calculator->calculate($property, $stay); + } catch (QuoteException) { + return $this->columnsOf($this->standalone($property, $stay, $portalTotal), null); + } + + $difference = max($portalTotal - $quote->total(), -$quote->rent()); + if ($difference === 0) { + return $this->columnsOf($quote, null); + } + + return $this->columnsOf($quote->withLine(new QuoteLine(QuoteLineType::Adjustment, self::LABEL, 1, $difference, $difference)), $difference); + } + + /** + * Quote for a stay without a known portal price: our calculation, or an empty quote when it is not possible. + * + * @return array + */ + public function unknownColumns(Property $property, StayRequest $stay): array + { + try { + return $this->columnsOf($this->calculator->calculate($property, $stay), null); + } catch (QuoteException) { + return $this->columnsOf($this->standalone($property, $stay, 0), null); + } + } + + private function standalone(Property $property, StayRequest $stay, int $total): PriceQuote + { + $lines = $total > 0 ? [new QuoteLine(QuoteLineType::Accommodation, 'Preis laut Portal', 1, $total, $total)] : []; + + return new PriceQuote($stay->arrival, $stay->departure, $stay->guests, $lines, $property->deposit_percent, CarbonImmutable::instance($stay->arrival)->subDays($property->balance_due_days_before_arrival)); + } + + /** + * @return array + */ + private function columnsOf(PriceQuote $quote, ?int $adjustment): array + { + return [ + 'quote' => $quote->toArray(), + 'total' => $quote->total(), + 'deposit' => $quote->deposit(), + 'balance_due_on' => $quote->balanceDueOn->toDateString(), + 'price_adjustment' => $adjustment, + 'price_adjustment_label' => $adjustment !== null ? self::LABEL : null, + ]; + } +} diff --git a/app/Support/BookingProgress.php b/app/Support/BookingProgress.php index ab67fac..59c048a 100644 --- a/app/Support/BookingProgress.php +++ b/app/Support/BookingProgress.php @@ -7,6 +7,7 @@ use App\Enums\BookingTaskStatus; use App\Enums\ChannelBookingModel; use App\Models\Booking; +use App\Models\BookingMessage; use App\Models\BookingTask; use App\Models\Cancellation; use Carbon\CarbonImmutable; @@ -48,7 +49,10 @@ public static function kindLabel(Booking $booking): string } /** - * @return list state: done | current | todo | skipped + * The milestones of the process with the activities that belong to each. An activity names the action on the + * booking page that does it ("action"), so the landlord sees what was done, what is open and where to do it. + * + * @return list}> */ public static function steps(Booking $booking): array { @@ -56,12 +60,20 @@ public static function steps(Booking $booking): array $kind = self::kind($booking); $closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true); $binding = in_array($booking->status, BookingStatus::occupying(), true); + $hasEmail = filled($booking->guest?->email); + $activity = fn (string $label, bool $done, ?string $action = null): array => ['label' => $label, 'done' => $done, 'action' => $done ? null : $action]; $steps = []; - $steps[] = ['label' => 'Anfrage / Eingang', 'state' => 'done', 'detail' => $booking->created_at?->format('d.m.Y')]; + $steps[] = ['label' => 'Anfrage / Eingang', 'state' => 'done', 'detail' => $booking->created_at?->format('d.m.Y'), 'activities' => [ + $activity($kind === self::OWN ? 'Anfrage über die Webseite eingegangen' : 'Vorgang angelegt ('.$booking->bookingChannelLabel().')', true), + ]]; if (in_array($kind, [self::PORTAL_BOOKING, self::PORTAL_INQUIRY], true)) { - $steps[] = ['label' => 'Kontaktdaten des Gastes', 'state' => filled($booking->guest?->email) ? 'done' : ($closed ? 'skipped' : 'current'), 'detail' => filled($booking->guest?->email) ? null : ($booking->contact_requested_at ? 'erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlen noch')]; + $asked = $booking->contact_requested_at !== null; + $steps[] = ['label' => 'Gast & Kontaktdaten', 'state' => $hasEmail ? 'done' : ($closed ? 'skipped' : 'current'), 'detail' => $hasEmail ? null : ($asked ? 'erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlen noch'), 'activities' => [ + $activity('Gast um Kontaktdaten bitten', $hasEmail || $asked, 'Gast um Kontaktdaten bitten'), + $activity('Kontaktdaten eintragen (Name, E-Mail, Anschrift)', $hasEmail, 'Kontaktdaten eintragen'), + ]]; } $needsOffer = in_array($kind, [self::OWN, self::PORTAL_INQUIRY, self::MANUAL], true); @@ -70,32 +82,85 @@ public static function steps(Booking $booking): array 'label' => 'Angebot', 'state' => $booking->offer_version > 0 || $binding ? 'done' : ($closed ? 'skipped' : 'current'), 'detail' => $booking->offer_version > 0 ? 'Version '.$booking->offer_version.', '.$booking->offer_sent_at?->format('d.m.Y') : null, + 'activities' => [$activity('Angebot mit Vertragsentwurf an den Gast senden', $booking->offer_version > 0 || $binding, 'Angebot senden')], ]; } $steps[] = [ - 'label' => $needsOffer ? 'Annahme / Vertrag' : 'Vertrag senden', + 'label' => $needsOffer ? 'Annahme / Vertrag' : 'Bestätigung / Vertrag', 'state' => $binding ? ($booking->confirmation_sent_at !== null || $booking->accepted_at !== null || $needsOffer ? 'done' : 'current') : ($closed ? 'skipped' : ($booking->status === BookingStatus::OfferSent ? 'current' : 'todo')), 'detail' => $booking->accepted_at ? 'angenommen '.$booking->accepted_at->format('d.m.Y') : ($booking->confirmation_sent_at ? 'Vertrag gesendet '.$booking->confirmation_sent_at->format('d.m.Y') : null), + 'activities' => array_values(array_filter([ + $needsOffer ? $activity('Gast nimmt das Angebot an (oder Buchung direkt bestätigen)', $binding, 'Direkt bestätigen') : $activity('Buchung bestätigen (Zeitraum fest belegen)', $binding, 'Direkt bestätigen'), + $activity('Mietvertrag mit Anlagen an den Gast senden', $booking->confirmation_sent_at !== null, $binding ? 'Bestätigung erneut senden' : null), + $booking->guest_confirmed_at ? $activity('Gast hat die Buchung per E-Mail bestätigt', true) : null, + ])), ]; if ($booking->wantsPaymentTasks()) { $paid = $booking->paidAmount(); - $steps[] = ['label' => 'Anzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->deposit && $binding ? 'done' : ($binding ? 'current' : 'todo')), 'detail' => $booking->deposit_due_on ? 'fällig '.$booking->deposit_due_on->format('d.m.Y') : null]; - $steps[] = ['label' => 'Restzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->total && $binding ? 'done' : ($binding && $paid >= $booking->deposit ? 'current' : 'todo')), 'detail' => 'fällig '.$booking->balance_due_on?->format('d.m.Y')]; + $steps[] = ['label' => 'Anzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->deposit && $binding ? 'done' : ($binding ? 'current' : 'todo')), 'detail' => $booking->deposit_due_on ? 'fällig '.$booking->deposit_due_on->format('d.m.Y') : null, 'activities' => [ + $activity('Zahlungseingang erfassen', $paid >= $booking->deposit && $binding, 'Zahlungen (unten)'), + ]]; + $steps[] = ['label' => 'Restzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->total && $binding ? 'done' : ($binding && $paid >= $booking->deposit ? 'current' : 'todo')), 'detail' => 'fällig '.$booking->balance_due_on?->format('d.m.Y'), 'activities' => [ + $activity('Restzahlung erfassen', $paid >= $booking->total && $binding, 'Zahlungen (unten)'), + ]]; } else { - $steps[] = ['label' => 'Zahlung', 'state' => 'skipped', 'detail' => 'läuft über das Portal']; + $steps[] = ['label' => 'Zahlung', 'state' => 'skipped', 'detail' => 'läuft über das Portal', 'activities' => []]; } $arrived = ! $closed && $binding && $booking->arrival <= $today; $left = ! $closed && $binding && $booking->departure <= $today; - $steps[] = ['label' => 'Anreise', 'state' => $closed ? 'skipped' : ($arrived ? 'done' : 'todo'), 'detail' => $booking->arrival->format('d.m.Y')]; - $steps[] = ['label' => 'Vor Ort', 'state' => $closed ? 'skipped' : ($arrived && ! $left ? 'current' : ($left ? 'done' : 'todo')), 'detail' => null]; - $steps[] = ['label' => 'Abreise', 'state' => $closed ? 'skipped' : ($left ? 'done' : 'todo'), 'detail' => $booking->departure->format('d.m.Y')]; + $steps[] = ['label' => 'Anreise', 'state' => $closed ? 'skipped' : ($arrived ? 'done' : 'todo'), 'detail' => $booking->arrival->format('d.m.Y'), 'activities' => [ + $activity('Anreise-Informationen ('.$booking->property->arrival_info_days_before.' Tage vorher, automatisch)', $booking->arrival_info_sent_at !== null), + ]]; + $steps[] = ['label' => 'Vor Ort', 'state' => $closed ? 'skipped' : ($arrived && ! $left ? 'current' : ($left ? 'done' : 'todo')), 'detail' => null, 'activities' => []]; + $steps[] = ['label' => 'Abreise', 'state' => $closed ? 'skipped' : ($left ? 'done' : 'todo'), 'detail' => $booking->departure->format('d.m.Y'), 'activities' => []]; return $steps; } + /** + * What has happened so far, oldest first: milestones from the booking's own timestamps, payments and mails. + * + * @return list + */ + public static function history(Booking $booking): array + { + $events = []; + $add = function (mixed $at, string $label) use (&$events): void { + if ($at !== null) { + $events[] = ['at' => CarbonImmutable::instance($at), 'label' => $label]; + } + }; + + $add($booking->created_at, 'Vorgang angelegt ('.$booking->bookingChannelLabel().')'); + $add($booking->contact_requested_at, 'Gast um Kontaktdaten gebeten'); + $add($booking->offer_sent_at, 'Angebot Version '.$booking->offer_version.' gesendet'); + $add($booking->accepted_at, 'Angebot vom Gast angenommen'); + $add($booking->guest_confirmed_at, 'Gast hat die Buchung per E-Mail bestätigt'); + $add($booking->confirmed_at, 'Buchung verbindlich bestätigt'); + $add($booking->confirmation_sent_at, 'Bestätigung mit Mietvertrag an den Gast gesendet'); + $add($booking->confirmation_failed_at, 'Versand der Bestätigung fehlgeschlagen'); + $add($booking->arrival_info_sent_at, 'Anreise-Informationen gesendet'); + $add($booking->cancelled_at, 'Storniert'); + $add($booking->archived_at, 'Archiviert'); + + foreach ($booking->payments()->get() as $payment) { + $add($payment->paid_on ?? $payment->created_at, ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').Money::format(abs($payment->amount)).' erfasst'); + } + foreach (BookingMessage::query()->where('booking_id', $booking->id)->get() as $message) { + $add($message->sent_at, 'E-Mail: '.$message->subject.' ('.$message->audience.')'); + } + foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Done)->get() as $task) { + $add($task->completed_at, 'Aufgabe erledigt: '.$task->kind->getLabel()); + } + + usort($events, fn (array $a, array $b): int => $a['at'] <=> $b['at']); + + return $events; + } + private static function cancelledText(Booking $booking, bool $open): string { $cancellation = Cancellation::query()->where('booking_id', $booking->id)->first(); diff --git a/resources/views/filament/pages/occupancy-calendar.blade.php b/resources/views/filament/pages/occupancy-calendar.blade.php index 0114071..2335746 100644 --- a/resources/views/filament/pages/occupancy-calendar.blade.php +++ b/resources/views/filament/pages/occupancy-calendar.blade.php @@ -64,7 +64,7 @@ @endif @if (!$event['guest_assigned'] && $event['kind'] === 'reservation')Gastzuordnung offen@endif @if ($event['needs_review'])Klärung erforderlich@endif - {{ $event['record_type'] === 'booking' ? 'Akte öffnen →' : 'Details →' }} + {{ $event['record_type'] === 'booking' ? 'Akte öffnen →' : ($event['kind'] === 'block' ? 'Details →' : 'Akte anlegen →') }} @endforeach @foreach ($day['departures'] as $event) @@ -95,7 +95,7 @@ @endif {{ $event['review_note'] ?? ($event['kind'] === 'block' ? $event['reason'] : null) }}@if ($event['representations'])
    {{ $event['representations'] }} zugeordnete Kalenderdarstellung(en)@endif - {{ $event['record_type'] === 'booking' ? 'Akte öffnen' : 'Details' }} + {{ $event['record_type'] === 'booking' ? 'Akte öffnen' : ($event['kind'] === 'block' ? 'Details' : 'Akte anlegen') }} @empty Keine Vorgänge in diesem Zeitraum. diff --git a/tests/Feature/PortalBookingTest.php b/tests/Feature/PortalBookingTest.php index 541eb36..552d2ee 100644 --- a/tests/Feature/PortalBookingTest.php +++ b/tests/Feature/PortalBookingTest.php @@ -2,10 +2,12 @@ namespace Tests\Feature; +use App\Actions\OpenPortalFile; use App\Actions\ProvideGuestContact; use App\Actions\RecordPortalBooking; use App\Actions\ResolveChannelOccupation; use App\Actions\SetBookingStatus; +use App\Availability\AvailabilityChecker; use App\Enums\BookingStatus; use App\Enums\ChannelBookingModel; use App\Enums\OccupationKind; @@ -13,6 +15,7 @@ use App\Filament\Resources\Bookings\Pages\CreateBooking; use App\Filament\Resources\Bookings\Pages\ListBookings; use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation; use App\Mail\BookingConfirmed; use App\Models\BlockedPeriod; use App\Models\Booking; @@ -215,6 +218,58 @@ public function test_an_independent_occupation_with_a_booking_channel_is_no_long $this->assertSame(OccupationKind::Reservation, $block->fresh()->occupation_kind); } + public function test_a_portal_reservation_from_the_calendar_gets_a_booking_file_and_stays_occupied(): void + { + $block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u2', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Reservation]); + $checker = app(AvailabilityChecker::class); + $this->assertFalse($checker->isAvailable($this->property, CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14'))); + + $booking = app(OpenPortalFile::class)->handle($block); + + $this->assertSame(BookingStatus::Confirmed, $booking->status); + $this->assertSame($this->portal->id, $booking->origin_channel_id); + $this->assertSame(BookingProgress::PORTAL_BOOKING, BookingProgress::kind($booking)); + $this->assertSame('', $booking->guest->email); + $this->assertTrue($block->fresh()->is_representation); + $this->assertSame($booking->id, $block->fresh()->linked_booking_id); + $this->assertFalse($checker->isAvailable($this->property, CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14'))); + $this->assertSame($booking->id, app(OpenPortalFile::class)->handle($block->fresh())->id); + $this->assertSame(1, Booking::query()->count()); + } + + public function test_a_blocked_period_gets_no_booking_file(): void + { + $block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u3', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Block]); + + $this->expectException(ReservationException::class); + app(OpenPortalFile::class)->handle($block); + } + + public function test_the_occupation_page_offers_the_file_and_leads_to_the_booking(): void + { + $block = BlockedPeriod::factory()->for($this->property)->create(['channel_id' => $this->portal->id, 'source' => 'channel', 'external_uid' => 'u4', 'starts_on' => '2026-12-10', 'ends_on' => '2026-12-14', 'occupation_kind' => OccupationKind::Reservation]); + $this->actingAs(User::factory()->create()); + + Livewire::test(ViewPortalOccupation::class, ['record' => $block->getRouteKey()])->callAction('openFile')->assertRedirect(); + + $booking = Booking::query()->sole(); + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->assertSee('Ablauf: Meilensteine und Aktivitäten') + ->assertSee('Bisheriger Verlauf') + ->assertSee('Standardprozess') + ->assertSee('Kontaktdaten eintragen'); + } + + public function test_every_milestone_lists_its_activities_and_the_history_records_what_happened(): void + { + $booking = $this->record(RecordPortalBooking::CONFIRM); + + $steps = collect(BookingProgress::steps($booking))->keyBy('label'); + $this->assertFalse($steps['Gast & Kontaktdaten']['activities'][1]['done']); + $this->assertSame('Kontaktdaten eintragen', $steps['Gast & Kontaktdaten']['activities'][1]['action']); + $this->assertSame(['Vorgang angelegt (FeWo-direkt)', 'Buchung verbindlich bestätigt'], array_column(BookingProgress::history($booking), 'label')); + } + private function record(string $process, ?int $total = null, ?string $reference = null, string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking { return app(RecordPortalBooking::class)->handle(