diff --git a/app/Actions/ProcessPortalMail.php b/app/Actions/ProcessPortalMail.php index df9dc6a..333ccb0 100644 --- a/app/Actions/ProcessPortalMail.php +++ b/app/Actions/ProcessPortalMail.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Channels\ConflictDetector; +use App\Channels\Intake\PortalIntake; use App\Channels\Mail\ParsedPortalMail; use App\Channels\Mail\PortalMail; use App\Channels\Mail\PortalMailParser; @@ -12,6 +13,7 @@ use App\Mail\PortalMailNotification; use App\Models\BlockedPeriod; use App\Models\Channel; +use App\Models\IntakeObservation; use App\Models\PortalEmail; use App\Support\Settings; use App\Tenancy\TenantFeatures; @@ -75,6 +77,9 @@ public function handle(PortalMail $mail): ?PortalEmail ]); }); + // One intake for all channels (package 4): bookings, requests and cancellations reach their case. + rescue(fn () => $this->intake($channel, $parsed, $record)); + if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) { rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record))); } @@ -86,6 +91,17 @@ public function handle(PortalMail $mail): ?PortalEmail return $record; } + private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void + { + $intake = app(PortalIntake::class); + match ($parsed->type) { + PortalEmailType::Booking => $record->blocked_period_id !== null ? $intake->process(BlockedPeriod::query()->findOrFail($record->blocked_period_id), IntakeObservation::SOURCE_MAIL) : null, + PortalEmailType::Cancellation => $intake->cancellationMail($channel, $parsed, $record), + PortalEmailType::Inquiry => $intake->inquiryMail($channel, $parsed, $record), + PortalEmailType::Unknown => null, + }; + } + /** * Channels list the sender addresses or domains of their notification e-mails in settings.email_senders. */ @@ -177,6 +193,11 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array default => null, }; + // A block that belongs to a case is never released by a mail: the case leads, the landlord decides (E-019). + if ($block && $block->linked_booking_id !== null) { + return [PortalEmailStatus::NeedsReview, $block, 'Stornierung zu einem gebuchten Vorgang gemeldet – nichts automatisch freigegeben; Aufgabe am Vorgang prüfen.']; + } + if ($block) { $block->delete(); diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php index 2d97a56..4da5859 100644 --- a/app/Actions/SyncChannel.php +++ b/app/Actions/SyncChannel.php @@ -5,6 +5,7 @@ use App\Channels\ChannelSyncException; use App\Channels\ConflictDetector; use App\Channels\ExternalPeriod; +use App\Channels\Intake\PortalIntake; use App\Enums\ChannelEchoBehavior; use App\Models\BlockedPeriod; use App\Models\Booking; @@ -135,6 +136,8 @@ public function handle(Channel $channel): ChannelSyncLog 'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save(); }); app(ReportChannelConflicts::class)->handle($channel, $conflicts); + // One intake for all channels (package 4); a failure there never fails the sync itself. + rescue(fn () => app(PortalIntake::class)->afterSync($channel->fresh())); return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts, 'conflicts' => count($conflicts), 'warnings' => $warnings, diff --git a/app/Actions/TakeOverExternalBooking.php b/app/Actions/TakeOverExternalBooking.php index 8e0c476..ac248d2 100644 --- a/app/Actions/TakeOverExternalBooking.php +++ b/app/Actions/TakeOverExternalBooking.php @@ -5,6 +5,7 @@ use App\Enums\BookingStatus; use App\Enums\IntakeKind; use App\Enums\OccupationKind; +use App\Enums\ProcessingMode; use App\Exceptions\ReservationException; use App\Models\BlockedPeriod; use App\Models\Booking; @@ -31,7 +32,7 @@ class TakeOverExternalBooking public function __construct(private ConfirmBooking $confirm, private PortalPrice $price) {} /** - * @param array{guest?: ?array, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool} $facts + * @param array{guest?: ?array, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool, processing_mode?: ?ProcessingMode} $facts * * @throws ReservationException */ @@ -73,6 +74,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar 'hold_expires_at' => null, 'guest_confirmed_at' => ($facts['guest_confirmed'] ?? false) ? now() : null, 'internal_notes' => filled($facts['notes'] ?? null) ? trim((string) $facts['notes']) : null, + 'processing_mode' => $facts['processing_mode'] ?? null, ...$this->price->columns($property, $arrival, $departure, $guests, $portalTotal, $channel->name), ]); diff --git a/app/Actions/TakeOverPortalInquiry.php b/app/Actions/TakeOverPortalInquiry.php new file mode 100644 index 0000000..882912a --- /dev/null +++ b/app/Actions/TakeOverPortalInquiry.php @@ -0,0 +1,63 @@ +property; + if ($departure->lessThanOrEqualTo($arrival)) { + throw new ReservationException('Die Abreise muss nach der Anreise liegen.'); + } + + $booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $reference, $notes, $processingMode): Booking { + $property->newQuery()->whereKey($property->id)->lockForUpdate()->firstOrFail(); + if (! $this->availability->isAvailable($property, $arrival, $departure)) { + throw ReservationException::notAvailable(); + } + + $profile = $this->settings->resolve($property, $channel, IntakeKind::Inquiry); + + return $property->bookings()->create([ + 'status' => BookingStatus::Reserved, + 'source' => 'portal', + 'intake' => IntakeKind::Inquiry, + 'origin_channel_id' => $channel->id, + 'portal_reference' => $reference, + 'arrival' => $arrival->toDateString(), + 'departure' => $departure->toDateString(), + 'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null, + 'processing_mode' => $processingMode, + 'internal_notes' => $notes, + ]); + }); + + app(CaseAutomation::class)->advance($booking); + + return $booking->refresh(); + } +} diff --git a/app/Channels/Intake/IntakeDecision.php b/app/Channels/Intake/IntakeDecision.php new file mode 100644 index 0000000..bffd948 --- /dev/null +++ b/app/Channels/Intake/IntakeDecision.php @@ -0,0 +1,39 @@ + $reasons why the intake decided so + * @param list $missing what the new case will not know yet + */ + public function __construct( + public readonly IntakeOutcome $outcome, + public readonly array $reasons = [], + public readonly ?Booking $booking = null, + public readonly ?CaseType $caseType = null, + public readonly array $missing = [], + public readonly ?string $reference = null, + ) {} + + public function withBooking(Booking $booking): self + { + return new self($this->outcome, $this->reasons, $booking, $this->caseType ?? $booking->case_type, $this->missing, $this->reference); + } + + /** + * @param list $reasons + */ + public function as(IntakeOutcome $outcome, array $reasons): self + { + return new self($outcome, $reasons, $this->booking, $this->caseType, $this->missing, $this->reference); + } +} diff --git a/app/Channels/Intake/PortalIntake.php b/app/Channels/Intake/PortalIntake.php new file mode 100644 index 0000000..4507bda --- /dev/null +++ b/app/Channels/Intake/PortalIntake.php @@ -0,0 +1,489 @@ +loadMissing(['channel', 'property', 'canonicalBlock', 'linkedBooking']); + $channel = $block->channel; + $reference = self::reference($block); + + if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference); + } + if ($block->trashed()) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Nicht mehr im Kalender des Portals.'], reference: $reference); + } + if ($block->linked_booking_id !== null && $block->linkedBooking !== null) { + return new IntakeDecision(IntakeOutcome::Link, ['Bereits dem Vorgang zugeordnet.'], $block->linkedBooking, reference: $reference); + } + if ($block->is_representation) { + $leaderCase = $block->canonicalBlock?->linkedBooking; + + return $leaderCase !== null + ? new IntakeDecision(IntakeOutcome::Link, ['Spiegelung einer Belegung, die zu diesem Vorgang gehört.'], $leaderCase, reference: $reference) + : new IntakeDecision(IntakeOutcome::Ignore, ['Spiegelung einer anderen Belegung, keine eigene Buchung.'], reference: $reference); + } + + if ($reference !== null && ($case = $this->caseByReference($channel, $reference)) !== null) { + return new IntakeDecision(IntakeOutcome::Link, ['Gleiche Buchungsnummer '.$reference.' wie der Vorgang.'], $case, reference: $reference); + } + + if ($block->ends_on->lessThanOrEqualTo(CarbonImmutable::today())) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $reference); + } + if ($block->occupationKind() === OccupationKind::Block) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Als Sperrzeit eingeordnet (z. B. Spiegelung, eigene Nutzung oder Wartung).'], reference: $reference); + } + if ($block->is_private) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Als private Belegung eingeordnet.'], reference: $reference); + } + + $origin = $block->origin_channel_id; + if ($origin !== null && $origin !== $channel->id) { + $case = $this->caseWithSameNights($block, $origin); + + return $case !== null + ? new IntakeDecision(IntakeOutcome::Link, ['Laut Kalender über ein anderes Portal gebucht; dort gibt es den Vorgang mit genau diesen Nächten.'], $case, reference: $reference) + : new IntakeDecision(IntakeOutcome::Clarify, ['Laut Kalender über ein anderes Portal gebucht – der Vorgang entsteht dort, nicht hier.'], reference: $reference); + } + + $case = $this->caseWithSameNights($block, $channel->id); + if ($case !== null) { + return filled($case->portal_reference) && $reference !== null && $case->portal_reference !== $reference + ? new IntakeDecision(IntakeOutcome::Clarify, ['Gleiche Nächte wie Vorgang '.$case->reference.', aber andere Buchungsnummer ('.$reference.' / '.$case->portal_reference.').'], reference: $reference) + : new IntakeDecision(IntakeOutcome::Link, ['Dasselbe Portal mit genau denselben Nächten wie Vorgang '.$case->reference.'.'], $case, reference: $reference); + } + + $overlap = Booking::query()->occupying()->where('property_id', $block->property_id)->overlapping($block->starts_on, $block->ends_on)->first(); + if ($overlap !== null) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Überschneidet sich mit Vorgang '.$overlap->reference.' ('.$overlap->arrival->format('d.m.').'–'.$overlap->departure->format('d.m.Y').'), ohne dieselbe Buchung zu sein.'], reference: $reference); + } + $sameChannelOverlap = $channel->blockedPeriods()->occupying()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists(); + if ($sameChannelOverlap) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Weitere Einträge desselben Portals überschneiden sich – keine Zusammenführung nach Terminen.'], reference: $reference); + } + + $certainty = $this->certainty($block, $reference); + if ($certainty !== null) { + return new IntakeDecision(IntakeOutcome::Clarify, [$certainty], reference: $reference); + } + if ($channel->booking_model === ChannelBookingModel::Inquiry) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Über dieses Portal kommen laut Einstellung nur Anfragen – eine feste Buchung bitte bestätigen.'], reference: $reference); + } + + $profile = $this->settings->resolve($block->property, $channel, IntakeKind::Booking); + $fields = (array) ($block->ical_interpretation['fields'] ?? []); + + return new IntakeDecision( + IntakeOutcome::Create, + [$block->source === 'email' ? 'Buchungsmail von '.$channel->name.' mit Zeitraum und Buchungsnummer.' : 'Kalendereintrag nach Regel „'.($block->ical_interpretation['rule'] ?? 'persönlich eingeordnet').'“ als Buchung bei '.$channel->name.' erkannt.'], + caseType: $profile->caseType, + missing: array_values(array_filter([ + blank($fields['guest_full_name'] ?? null) ? 'Name des Gastes' : 'Name des Gastes (nur als Hinweis aus dem Kalender)', + 'E-Mail-Adresse des Gastes', + 'Personenzahl', + 'Gesamtpreis laut Portal', + $reference === null ? 'Buchungsnummer' : null, + ])), + reference: $reference, + ); + } + + /** + * Judges an entry and acts as the channel allows: records what was recognised and – only when the channel creates + * cases – creates the case, links the entry to its case or marks it for clarification. + */ + public function process(BlockedPeriod $block, string $source): IntakeDecision + { + $channel = $block->channel; + $mode = $channel?->case_intake ?? CaseIntakeMode::Off; + if (! $mode->records()) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']); + } + + $decision = $this->evaluate($block); + $applied = false; + + if ($mode->creates()) { + [$decision, $applied] = match ($decision->outcome) { + IntakeOutcome::Create => $this->create($block, $decision, $mode, $source), + IntakeOutcome::Link => [$decision, $this->link($block, $decision->booking, $decision->reasons[0] ?? '')], + IntakeOutcome::Clarify => [$decision, $this->flag($block, $decision->reasons[0] ?? '')], + default => [$decision, false], + }; + } + + $this->record($channel, $mode, $source, $decision, $applied, $block, null, $block->starts_on, $block->ends_on); + + return $decision; + } + + /** + * Takes over an existing portal entry by an explicit run of the landlord or operator (stock adoption), whatever the + * channel's switch says: certain bookings become cases (released by hand, never automatic), entries of known cases + * are linked, everything else is only reported. + */ + public function adopt(BlockedPeriod $block): IntakeDecision + { + $decision = $this->evaluate($block); + $applied = false; + + if ($decision->outcome === IntakeOutcome::Create) { + [$decision, $applied] = $this->create($block, $decision, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION); + } elseif ($decision->outcome === IntakeOutcome::Link) { + $applied = $this->link($block, $decision->booking, $decision->reasons[0] ?? ''); + } + + $this->record($block->channel, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION, $decision, $applied, $block, null, $block->starts_on, $block->ends_on); + + return $decision; + } + + /** + * After a calendar sync: new or changed entries of the channel go through the intake; entries of known cases that + * disappeared or show other nights become reports on the case. + */ + public function afterSync(Channel $channel): void + { + $mode = $channel->case_intake ?? CaseIntakeMode::Off; + if (! $mode->records()) { + return; + } + + $open = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id') + ->where('is_representation', false)->whereDate('ends_on', '>', CarbonImmutable::today())->orderBy('starts_on')->get(); + foreach ($open as $block) { + $this->process($block, IntakeObservation::SOURCE_CALENDAR); + } + + $linked = $channel->blockedPeriods()->withTrashed()->with('linkedBooking')->where('source', 'channel')->whereNotNull('linked_booking_id') + ->whereHas('linkedBooking', fn ($query) => $query->whereIn('status', BookingStatus::occupying())->whereDate('departure', '>', CarbonImmutable::today()))->get(); + foreach ($linked as $block) { + $case = $block->linkedBooking; + if ($block->trashed()) { + $this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, 'Der Eintrag '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').' ist aus dem Kalender von '.$channel->name.' verschwunden. Das kann eine Stornierung sein, ist aber kein Nachweis – bitte im Portal prüfen.', 'gone:'.$block->id, IntakeObservation::SOURCE_CALENDAR, $block); + } elseif (! $block->starts_on->equalTo($case->arrival) || ! $block->ends_on->equalTo($case->departure)) { + $this->report($channel, $mode, $case, IntakeOutcome::ChangeSignal, 'Der Kalender von '.$channel->name.' meldet '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').', der Vorgang hat '.$case->arrival->format('d.m.').'–'.$case->departure->format('d.m.Y').'. Bitte prüfen, ob die Buchung im Portal geändert wurde.', 'dates:'.$block->id.':'.$block->starts_on->toDateString().':'.$block->ends_on->toDateString(), IntakeObservation::SOURCE_CALENDAR, $block); + } + } + } + + /** + * A portal e-mail reporting a cancellation: the case learns about it as a task; nothing is cancelled. + * + * @return Booking|null the case the report belongs to + */ + public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): ?Booking + { + $case = $parsed->reference !== null ? $this->caseByReference($channel, $parsed->reference) : null; + $mode = $channel->case_intake ?? CaseIntakeMode::Off; + if ($case === null || ! $case->isBinding()) { + $this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, new IntakeDecision(IntakeOutcome::Clarify, [$parsed->reference === null ? 'Stornierungsmail ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : 'Kein gebuchter Vorgang mit der Buchungsnummer '.$parsed->reference.'.'], reference: $parsed->reference), false, null, $mail, $parsed->startsOn, $parsed->endsOn); + + return null; + } + + $this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, $channel->name.' meldet eine Stornierung (E-Mail „'.$mail->subject.'“). Bitte prüfen Sie die Buchung und die nächsten Schritte.', 'mail:'.$mail->message_id, IntakeObservation::SOURCE_MAIL, null, $mail); + + return $case; + } + + /** + * A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates + * cases; otherwise only recorded. + */ + public function inquiryMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): IntakeDecision + { + $mode = $channel->case_intake ?? CaseIntakeMode::Off; + if (! $mode->records()) { + return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']); + } + + $profile = $this->settings->resolve($channel->property, $channel, IntakeKind::Inquiry); + $decision = match (true) { + ! $parsed->hasPeriod() => new IntakeDecision(IntakeOutcome::Clarify, ['Anfrage erkannt, aber An- und Abreise nicht sicher lesbar.'], reference: $parsed->reference), + $parsed->reference !== null && ($case = $this->caseByReference($channel, $parsed->reference)) !== null => new IntakeDecision(IntakeOutcome::Link, ['Gleiche Anfragenummer '.$parsed->reference.' wie der Vorgang.'], $case, reference: $parsed->reference), + $parsed->endsOn->lessThanOrEqualTo(CarbonImmutable::today()) => new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $parsed->reference), + default => new IntakeDecision(IntakeOutcome::Inquiry, ['Anfrage-Mail von '.$channel->name.' mit Zeitraum.'], caseType: $profile->caseType, missing: ['Name und E-Mail-Adresse des Gastes', 'Personenzahl'], reference: $parsed->reference), + }; + + $applied = false; + if ($mode->creates() && $decision->outcome === IntakeOutcome::Inquiry) { + try { + $case = $this->inquiry->handle($channel, $parsed->startsOn, $parsed->endsOn, $parsed->reference, 'Automatisch aus der Anfrage-Mail von '.$channel->name.' übernommen („'.$mail->subject.'“).', $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null); + CaseLog::record($case, 'intake', 'Automatisch aus der Anfrage-Mail von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => IntakeObservation::SOURCE_MAIL, 'message_id' => $mail->message_id]); + $decision = $decision->withBooking($case); + $applied = true; + } catch (ReservationException|QuoteException $exception) { + $decision = $decision->as(IntakeOutcome::Clarify, ['Anfrage nicht automatisch übernommen: '.$exception->getMessage()]); + } + } + + $this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, $decision, $applied, null, $mail, $parsed->startsOn, $parsed->endsOn); + + return $decision; + } + + /** + * The portal's booking reference of an entry: extracted by the calendar rules, or the one of a booking e-mail. + */ + public static function reference(BlockedPeriod $block): ?string + { + $fromRules = $block->ical_interpretation['fields']['booking_reference'] ?? null; + if (filled($fromRules)) { + return trim((string) $fromRules); + } + + if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) { + $reference = substr((string) $block->external_uid, 6); + + // Mails without a reference got a random identifier, which is no booking reference. + return preg_match('/^[0-9a-f]{32}$/', $reference) === 1 ? null : $reference; + } + + return null; + } + + /** + * The case of a portal booking with this reference: on the case itself or on an entry that belongs to a case. + */ + public function caseByReference(Channel $channel, string $reference): ?Booking + { + $case = Booking::query()->where('portal_reference', $reference) + ->where(fn ($query) => $query->where('origin_channel_id', $channel->id)->orWhere('import_channel_id', $channel->id)) + ->orderBy('id')->first(); + if ($case !== null) { + return $case; + } + + $linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id') + ->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id'); + + return $linked !== null ? Booking::query()->find($linked) : null; + } + + /** + * The one occupying case of this portal with exactly these nights (more than one: none – that is for a person). + */ + private function caseWithSameNights(BlockedPeriod $block, int $channelId): ?Booking + { + /** @var Collection $cases */ + $cases = Booking::query()->occupying()->where('property_id', $block->property_id) + ->whereDate('arrival', $block->starts_on)->whereDate('departure', $block->ends_on) + ->where(fn ($query) => $query->where('origin_channel_id', $channelId)->orWhere('import_channel_id', $channelId)) + ->get(); + + return $cases->count() === 1 ? $cases->first() : null; + } + + /** + * Null when the entry is certainly a booking of its portal, otherwise why not. + */ + private function certainty(BlockedPeriod $block, ?string $reference): ?string + { + if ($block->needs_review && ! in_array($block->review_note, [ReconcileChannelRepresentations::OVERLAP_NOTE], true)) { + return 'Prüfhinweis am Eintrag: '.($block->review_note ?? 'bitte prüfen').'.'; + } + + if ($block->source === 'email') { + return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null; + } + + // Classified by the landlord as a reservation booked at this portal. + if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) { + return null; + } + + $interpretation = (array) ($block->ical_interpretation ?? []); + if (! ($interpretation['matched'] ?? false)) { + return 'Kein Kalendermerkmal erkannt – eine reine Belegt-Meldung ist kein Nachweis einer Buchung.'; + } + if (($interpretation['event_type'] ?? null) !== 'portal_reservation') { + return 'Die Regel „'.($interpretation['rule'] ?? '').'“ ordnet den Eintrag nicht als Buchung ein.'; + } + if (($interpretation['representation'] ?? null) !== 'leading_candidate' || $block->origin_channel_id !== $block->channel_id) { + return 'Die Regel erkennt eine Reservierung, aber nicht sicher als Buchung bei diesem Portal.'; + } + + return null; + } + + /** + * @return array{IntakeDecision, bool} + */ + private function create(BlockedPeriod $block, IntakeDecision $decision, CaseIntakeMode $mode, string $source): array + { + $channel = $block->channel; + $fields = (array) ($block->ical_interpretation['fields'] ?? []); + $name = trim((string) ($fields['guest_full_name'] ?? $fields['guest_first_name'] ?? '')); + $origin = match ($source) { + IntakeObservation::SOURCE_MAIL => 'der Buchungsmail', + IntakeObservation::SOURCE_ADOPTION => 'dem Bestand der Portalbelegungen', + default => 'dem Kalender', + }; + + try { + $case = $this->takeOver->handle($block->property, $channel, CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), [ + 'portal_reference' => $decision->reference, + 'notes' => 'Automatisch aus '.$origin.' von '.$channel->name.' übernommen.'.($name !== '' ? ' Name laut Portal: '.$name.'.' : ''), + 'processing_mode' => $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null, + ], $block); + } catch (ReservationException $exception) { + $this->flag($block, 'Nicht automatisch übernommen: '.$exception->getMessage()); + + return [$decision->as(IntakeOutcome::Clarify, ['Nicht automatisch übernommen: '.$exception->getMessage()]), false]; + } + + CaseLog::record($case, 'intake', 'Automatisch aus '.$origin.' von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => $source, 'blocked_period_id' => $block->id, 'reference' => $decision->reference]); + + return [$decision->withBooking($case), true]; + } + + /** + * Makes the entry a mirror of its case (the case leads availability and export). + */ + private function link(BlockedPeriod $block, ?Booking $case, string $reason): bool + { + if ($case === null || $block->linked_booking_id === $case->id || $block->is_representation) { + return false; + } + + $block->forceFill([ + 'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null, + 'linked_booking_id' => $case->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(), + 'occupation_kind' => OccupationKind::Reservation, 'review_note' => self::LINK_NOTE, + ])->save(); + app(ReconcileChannelRepresentations::class)->handle($block->property); + CaseLog::record($case, 'intake', 'Weitere Quelle zugeordnet: '.($block->source === 'email' ? 'E-Mail' : 'Kalender').' von '.$block->channel?->name.' ('.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').')', $reason, actor: CaseLog::SYSTEM, data: ['blocked_period_id' => $block->id]); + + return true; + } + + /** + * Puts an uncertain entry in front of the landlord ("Zu erledigen") with the reason. + */ + private function flag(BlockedPeriod $block, string $reason): bool + { + if ($block->needs_review || $block->reviewed_at !== null) { + return false; + } + + $block->forceFill(['needs_review' => true, 'review_note' => mb_substr($reason, 0, 250)])->saveQuietly(); + + return true; + } + + /** + * A report of the portal about a known case: a task and an entry in the history – once per report. + */ + private function report(Channel $channel, CaseIntakeMode $mode, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source, ?BlockedPeriod $block = null, ?PortalEmail $mail = null): void + { + $fingerprint = hash('sha256', $channel->id.'|signal|'.$key); + $known = $case->events()->where('type', 'portal_signal')->get()->contains(fn ($event): bool => ($event->data['fingerprint'] ?? null) === $fingerprint); + $applied = false; + + if ($mode->creates() && ! $known) { + $kind = $outcome === IntakeOutcome::CancellationSignal ? BookingTaskKind::PortalCancellationReported : BookingTaskKind::PortalChangeReported; + $task = BookingTask::query()->firstOrNew(['booking_id' => $case->id, 'kind' => $kind]); + $task->forceFill(['tenant_id' => $case->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'note' => mb_substr($message, 0, 1000), 'completed_by' => null, 'completed_at' => null])->save(); + CaseLog::record($case, 'portal_signal', $message, actor: $channel->name, data: ['fingerprint' => $fingerprint, 'source' => $source]); + $applied = true; + } + + $this->record($channel, $mode, $source, new IntakeDecision($outcome, [$message], $case, $case->case_type), $applied, $block, $mail, $block?->starts_on ?? $case->arrival, $block?->ends_on ?? $case->departure, $key); + } + + /** + * Records the decision once per event and result (repeated syncs and mails add nothing). + */ + private function record(?Channel $channel, CaseIntakeMode $mode, string $source, IntakeDecision $decision, bool $applied, ?BlockedPeriod $block, ?PortalEmail $mail, mixed $startsOn, mixed $endsOn, ?string $key = null): void + { + if ($channel === null || ! $mode->records()) { + return; + } + + $fingerprint = hash('sha256', implode('|', [ + $channel->id, $mode->value, $decision->outcome->value, $key ?? '', + $block?->id ?? '', $mail?->message_id ?? '', $decision->booking?->id ?? '', + $startsOn instanceof \DateTimeInterface ? $startsOn->format('Y-m-d') : (string) $startsOn, + $endsOn instanceof \DateTimeInterface ? $endsOn->format('Y-m-d') : (string) $endsOn, + ])); + + try { + $observation = IntakeObservation::query()->firstOrNew(['fingerprint' => $fingerprint]); + if ($observation->exists) { + return; + } + $observation->fill([ + 'channel_id' => $channel->id, 'blocked_period_id' => $block?->id, 'portal_email_id' => $mail?->id, + 'booking_id' => $decision->booking?->id, 'source' => $source, 'mode' => $mode, 'outcome' => $decision->outcome, + 'applied' => $applied, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference, + 'starts_on' => $startsOn, 'ends_on' => $endsOn, 'reasons' => $decision->reasons, 'missing' => $decision->missing, + 'occurred_at' => now(), + ]); + $observation->tenant_id = $channel->tenant_id; + $observation->save(); + } catch (Throwable $exception) { + // The record must never stop the intake itself. + report($exception); + } + } +} diff --git a/app/Console/Commands/AdoptPortalOccupations.php b/app/Console/Commands/AdoptPortalOccupations.php new file mode 100644 index 0000000..f72fb39 --- /dev/null +++ b/app/Console/Commands/AdoptPortalOccupations.php @@ -0,0 +1,123 @@ +option('revert'))) { + return $this->revert((string) $this->option('revert')); + } + + $apply = (bool) $this->option('apply'); + $report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => [], 'channel_task_ids' => []]; + $firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id'); + + $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void { + $channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get(); + foreach ($channels as $channel) { + $entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id') + ->where('is_representation', false)->whereDate('ends_on', '>', today())->orderBy('starts_on')->get(); + foreach ($entries as $entry) { + $before = collect(self::RESTORED)->mapWithKeys(fn (string $field): array => [$field => $entry->getRawOriginal($field)])->all(); + $decision = $apply ? $intake->adopt($entry) : $intake->evaluate($entry); + $created = $apply && $decision->outcome === IntakeOutcome::Create && $decision->booking !== null; + $report['entries'][] = [ + 'tenant' => $tenant->id, 'channel' => $channel->name, 'blocked_period_id' => $entry->id, + 'period' => $entry->starts_on->format('d.m.Y').'–'.$entry->ends_on->format('d.m.Y'), + 'outcome' => $decision->outcome->value, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference, + 'booking_id' => $decision->booking?->id, 'created' => $created, 'reasons' => $decision->reasons, 'before' => $before, + ]; + } + } + }); + + if ($apply) { + $report['channel_task_ids'] = ChannelTask::query()->withoutGlobalScopes()->where('id', '>', $firstTask)->pluck('id')->all(); + } + + $this->table(['Kanal', 'Zeitraum', 'Ergebnis', 'Art', 'Nr.', 'Vorgang', 'Begründung'], array_map(fn (array $entry): array => [ + $entry['channel'], $entry['period'], IntakeOutcome::from($entry['outcome'])->getLabel(), strtoupper((string) $entry['case_type']), $entry['reference'] ?? '–', + $entry['booking_id'] ? '#'.$entry['booking_id'].($entry['created'] ? ' (neu)' : '') : '–', implode(' ', $entry['reasons']), + ], $report['entries'])); + + $path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'.json'; + for ($number = 2; Storage::disk('local')->exists($path); $number++) { + $path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'-'.$number.'.json'; + } + Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + $counts = collect($report['entries'])->countBy('outcome'); + $this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.$counts->map(fn (int $count, string $outcome): string => IntakeOutcome::from($outcome)->getLabel().' '.$count)->implode(', ')); + $this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : '')); + + return self::SUCCESS; + } + + /** + * Takes an adoption back: cases created by it are removed again as long as nothing has happened with them (no + * document, no payment), and every entry gets its former state. Cases with activity are reported, not touched. + */ + private function revert(string $path): int + { + if (! Storage::disk('local')->exists($path)) { + $this->error('Bericht nicht gefunden: '.$path); + + return self::FAILURE; + } + + $report = json_decode((string) Storage::disk('local')->get($path), true); + if (! ($report['apply'] ?? false)) { + $this->info('Das war eine Vorschau – es gibt nichts zurückzunehmen.'); + + return self::SUCCESS; + } + + $kept = []; + foreach ((array) $report['entries'] as $entry) { + $block = BlockedPeriod::query()->withoutGlobalScopes()->withTrashed()->find($entry['blocked_period_id']); + $case = ($entry['created'] ?? false) ? Booking::query()->withoutGlobalScopes()->find($entry['booking_id']) : null; + if ($case !== null && ($case->contract_path !== null || $case->confirmation_sent_at !== null || $case->payments()->withoutGlobalScopes()->exists())) { + $kept[] = $case->reference; + + continue; + } + // The entry first gets its former state (it may point to the case), then the case created by the run goes. + if ($block !== null && in_array($entry['outcome'], [IntakeOutcome::Create->value, IntakeOutcome::Link->value], true)) { + $block->forceFill((array) $entry['before'])->saveQuietly(); + } + $case?->delete(); + } + + ChannelTask::query()->withoutGlobalScopes()->whereKey((array) ($report['channel_task_ids'] ?? []))->where('status', ChannelTaskStatus::Open) + ->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Bestandsübernahme zurückgenommen.']); + + $this->info('Zurückgenommen.'.($kept === [] ? '' : ' Nicht entfernt, weil schon bearbeitet: '.implode(', ', $kept))); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/IntakeReport.php b/app/Console/Commands/IntakeReport.php new file mode 100644 index 0000000..e9c16c0 --- /dev/null +++ b/app/Console/Commands/IntakeReport.php @@ -0,0 +1,41 @@ +each(function (Tenant $tenant): void { + $observations = IntakeObservation::query()->with(['channel', 'booking']) + ->where('occurred_at', '>=', now()->subDays((int) $this->option('days')))->orderBy('occurred_at')->get(); + + $this->line("{$tenant->name}: ".$observations->count().' Einträge'); + $this->table(['Wann', 'Portal', 'Quelle', 'Zeitraum', 'Ergebnis', 'Ausgeführt', 'Vorgang', 'Begründung'], $observations->map(fn (IntakeObservation $observation): array => [ + $observation->occurred_at->format('d.m. H:i'), + $observation->channel?->name, + $observation->sourceLabel(), + $observation->starts_on ? $observation->starts_on->format('d.m.').'–'.$observation->ends_on?->format('d.m.Y') : '–', + $observation->outcome->getLabel(), + $observation->applied ? 'ja' : 'nur protokolliert', + $observation->booking?->reference ?? '–', + implode(' ', (array) $observation->reasons), + ])->all()); + + $wouldCreate = $observations->filter(fn (IntakeObservation $observation): bool => ! $observation->applied && in_array($observation->outcome, [IntakeOutcome::Create, IntakeOutcome::Inquiry], true))->count(); + $this->info("Wären entstanden (Beobachten): {$wouldCreate}"); + }); + + return self::SUCCESS; + } +} diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index c5c056f..2aa98ca 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -17,6 +17,8 @@ enum BookingTaskKind: string implements HasLabel case CancellationRequest = 'cancellation_request'; case CancellationFee = 'cancellation_fee'; case PortalCancellation = 'portal_cancellation'; + case PortalCancellationReported = 'portal_cancel_reported'; + case PortalChangeReported = 'portal_change_reported'; public function getLabel(): string { @@ -27,12 +29,14 @@ public function getLabel(): string self::CancellationRequest => 'Stornierungswunsch des Gastes', self::CancellationFee => 'Stornokosten prüfen und abrechnen', self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen', + self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen', + self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen', }; } public function isPayment(): bool { - return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation], true); + return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported], true); } /** @@ -46,7 +50,7 @@ public function reminder(): ?array self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'], self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'], self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'], - self::CancellationRequest, self::CancellationFee, self::PortalCancellation => null, + self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported => null, }; } } diff --git a/app/Enums/CaseIntakeMode.php b/app/Enums/CaseIntakeMode.php new file mode 100644 index 0000000..591d4ee --- /dev/null +++ b/app/Enums/CaseIntakeMode.php @@ -0,0 +1,50 @@ + 'Aus – Sie übernehmen Buchungen selbst', + self::Observe => 'Beobachten – nur protokollieren, was entstehen würde', + self::Create => 'Vorgänge anlegen – die nächsten Schritte geben Sie frei', + self::Continue => 'Vorgänge anlegen und nach Ihren Einstellungen weiterbearbeiten', + }; + } + + public function getDescription(): string + { + return match ($this) { + self::Off => 'Erkannte Buchungen erscheinen als Klärungsfall; nichts entsteht automatisch.', + self::Observe => 'Es entsteht nichts. Das Eingangsprotokoll zeigt, welche Vorgänge entstanden wären und warum.', + self::Create => 'Sicher erkannte Buchungen werden zum Vorgang; Sie geben jeden weiteren Schritt frei.', + self::Continue => 'Wie „anlegen“; danach laufen die Vorgänge automatisch oder mit Freigabe – wie unter „So arbeite ich“ eingestellt.', + }; + } + + public function records(): bool + { + return $this !== self::Off; + } + + public function creates(): bool + { + return in_array($this, [self::Create, self::Continue], true); + } +} diff --git a/app/Enums/ChannelTaskProof.php b/app/Enums/ChannelTaskProof.php new file mode 100644 index 0000000..171aa12 --- /dev/null +++ b/app/Enums/ChannelTaskProof.php @@ -0,0 +1,54 @@ + 'veranlasst', + self::Observed => 'im Portal gesehen', + self::Confirmed => 'Wirksamkeit bestätigt', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Initiated => 'warning', + self::Observed => 'info', + self::Confirmed => 'success', + }; + } + + /** + * The choice the landlord reads when completing a task. + */ + public function question(bool $block = true): string + { + $what = $block ? 'gesperrt' : 'freigegeben'; + + return match ($this) { + self::Initiated => "Ich habe den Zeitraum im Portal {$what}.", + self::Observed => "… und im Kalender des Portals gesehen, dass er {$what} ist.", + self::Confirmed => 'Das Portal hat es bestätigt (z. B. Bestätigung oder Testanfrage abgelehnt).', + }; + } +} diff --git a/app/Enums/IntakeOutcome.php b/app/Enums/IntakeOutcome.php new file mode 100644 index 0000000..44dc67c --- /dev/null +++ b/app/Enums/IntakeOutcome.php @@ -0,0 +1,56 @@ + 'Neuer Vorgang (Buchung)', + self::Inquiry => 'Neuer Vorgang (Anfrage)', + self::Link => 'Gehört zu vorhandenem Vorgang', + self::Clarify => 'Klärung nötig', + self::Ignore => 'Keine Buchung', + self::CancellationSignal => 'Portal meldet Stornierung', + self::ChangeSignal => 'Portal meldet Änderung', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Create, self::Inquiry => 'success', + self::Link, self::Ignore => 'gray', + self::Clarify => 'warning', + self::CancellationSignal, self::ChangeSignal => 'danger', + }; + } +} diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index b5e259e..53bfd7e 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -9,7 +9,9 @@ use App\Enums\ProcessingMode; use App\Enums\ProcessSetting; use App\Enums\Responsibility; +use App\Models\BlockedPeriod; use App\Models\Booking; +use App\Models\IntakeObservation; use App\Models\User; use App\Process\CaseActivities; use App\Process\CaseAutomation; @@ -123,6 +125,7 @@ public static function configure(Schema $schema): Schema TextEntry::make('status')->label('Status')->badge(), TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()), TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'), + TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(), TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(), TextEntry::make('hold_expires_at')->label('Reserviert bis')->dateTime('d.m.Y, H:i')->placeholder('–'), TextEntry::make('offer_hash')->label('Angebot (Prüfsumme)')->state(fn (Booking $record): ?string => $record->offer_version > 0 ? 'Version '.$record->offer_version.' · '.substr((string) $record->offer_hash, 0, 16) : null)->placeholder('–'), @@ -161,6 +164,22 @@ private static function nextStep(Booking $booking): HtmlString .'
'.$mode.'
'); } + /** + * Every portal entry (calendar or e-mail) that belongs to the case, and what the intake recorded about it. + */ + private static function sources(Booking $booking): HtmlString + { + $lines = BlockedPeriod::query()->withTrashed()->with('channel')->where('linked_booking_id', $booking->id)->orderBy('id')->get() + ->map(fn (BlockedPeriod $entry): string => e(($entry->source === 'email' ? 'E-Mail' : 'Kalender').' von '.($entry->channel?->name ?? '–').': '.$entry->starts_on->format('d.m.').'–'.$entry->ends_on->format('d.m.Y') + .($entry->trashed() ? ' · nicht mehr im Kalender' : '').($entry->starts_on->equalTo($booking->arrival) && $entry->ends_on->equalTo($booking->departure) ? '' : ' · abweichende Termine').' · Kennung '.$entry->external_uid)); + $observations = IntakeObservation::query()->with('channel')->where('booking_id', $booking->id)->orderBy('occurred_at')->get() + ->map(fn (IntakeObservation $observation): string => e($observation->occurred_at->format('d.m.Y H:i').' · '.$observation->sourceLabel().' '.$observation->channel?->name.' · '.$observation->outcome->getLabel().($observation->applied ? '' : ' (nur protokolliert)'))); + + $html = $lines->isEmpty() ? 'Keine Portaleinträge zugeordnet.' : $lines->implode('
'); + + return new HtmlString($observations->isEmpty() ? $html : $html.'
Eingang: '.$observations->implode('
').'
'); + } + /** * The documents made for the case, as recorded when they were created (kind, template, date). */ diff --git a/app/Filament/Resources/ChannelTasks/Tables/ChannelTasksTable.php b/app/Filament/Resources/ChannelTasks/Tables/ChannelTasksTable.php index eb7990c..0efd3e8 100644 --- a/app/Filament/Resources/ChannelTasks/Tables/ChannelTasksTable.php +++ b/app/Filament/Resources/ChannelTasks/Tables/ChannelTasksTable.php @@ -2,9 +2,13 @@ namespace App\Filament\Resources\ChannelTasks\Tables; +use App\Enums\ChannelTaskAction; +use App\Enums\ChannelTaskProof; use App\Enums\ChannelTaskStatus; use App\Models\ChannelTask; use Filament\Actions\Action; +use Filament\Forms\Components\Radio; +use Filament\Forms\Components\Textarea; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\SelectFilter; @@ -24,6 +28,8 @@ public static function configure(Table $table): Table TextColumn::make('reason')->label('Anlass')->wrap(), TextColumn::make('status')->label('Status')->badge() ->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null), + TextColumn::make('proof')->label('Nachweis')->state(fn (ChannelTask $record): string => $record->proofLabel()) + ->description(fn (ChannelTask $record): ?string => $record->proof_by ? "{$record->proof_by}, {$record->proof_at?->format('d.m. H:i')}" : null)->wrap(), TextColumn::make('created_at')->label('Seit')->since(), TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true), ]) @@ -45,7 +51,26 @@ public static function configure(Table $table): Table ->icon(Heroicon::OutlinedCheck) ->color('success') ->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open) - ->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)), + ->modalHeading(fn (ChannelTask $record): string => ($record->action === ChannelTaskAction::Block ? 'Sperre in ' : 'Freigabe in ').$record->channel->name.' erledigt') + ->modalDescription('Was können Sie sagen? Ein bereitgestellter Kalender beweist nicht, dass das Portal ihn schon übernommen hat.') + ->fillForm(['proof' => ChannelTaskProof::Initiated->value]) + ->schema(fn (ChannelTask $record): array => [ + Radio::make('proof')->hiddenLabel()->required() + ->options(collect(ChannelTaskProof::cases())->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()), + Textarea::make('note')->label('Notiz (optional)')->placeholder('z. B. „im Vermieterkalender rot markiert“')->rows(2), + ]) + ->action(fn (ChannelTask $record, array $data) => $record->complete(auth()->user()->name, ChannelTaskProof::from($data['proof']), $data['note'] ?? null)), + Action::make('prove') + ->label('Nachweis ergänzen') + ->icon(Heroicon::OutlinedShieldCheck) + ->color('gray') + ->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Done && $record->proof !== ChannelTaskProof::Confirmed) + ->schema(fn (ChannelTask $record): array => [ + Radio::make('proof')->hiddenLabel()->required() + ->options(collect([ChannelTaskProof::Observed, ChannelTaskProof::Confirmed])->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()), + Textarea::make('note')->label('Notiz (optional)')->rows(2), + ]) + ->action(fn (ChannelTask $record, array $data) => $record->prove(ChannelTaskProof::from($data['proof']), auth()->user()->name, $data['note'] ?? null)), Action::make('dismiss') ->label('Verwerfen') ->icon(Heroicon::OutlinedXMark) diff --git a/app/Filament/Resources/Channels/Schemas/ChannelForm.php b/app/Filament/Resources/Channels/Schemas/ChannelForm.php index 115a7e8..5f5ebdf 100644 --- a/app/Filament/Resources/Channels/Schemas/ChannelForm.php +++ b/app/Filament/Resources/Channels/Schemas/ChannelForm.php @@ -3,6 +3,7 @@ namespace App\Filament\Resources\Channels\Schemas; use App\Channels\ChannelRegistry; +use App\Enums\CaseIntakeMode; use App\Enums\ChannelBookingModel; use App\Enums\ChannelEchoBehavior; use App\Enums\ChannelExportMode; @@ -55,6 +56,13 @@ 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('Was kommt über dieses Portal?')->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('case_intake') + ->label('Erkannte Buchungen automatisch als Vorgang übernehmen?') + ->options(CaseIntakeMode::class) + ->default(CaseIntakeMode::Off) + ->required() + ->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.') + ->columnSpanFull(), ...self::processSections(), Select::make('connector') ->label('Kalenderanbindung') diff --git a/app/Filament/Resources/IntakeObservations/IntakeObservationResource.php b/app/Filament/Resources/IntakeObservations/IntakeObservationResource.php new file mode 100644 index 0000000..72ae55f --- /dev/null +++ b/app/Filament/Resources/IntakeObservations/IntakeObservationResource.php @@ -0,0 +1,83 @@ +description('Was über die Portale hereinkam und was daraus wurde. „Nur protokolliert“ heißt: Das Portal steht auf „Beobachten“ (oder es war nichts zu tun) – es ist nichts entstanden.') + ->defaultSort('occurred_at', 'desc') + ->modifyQueryUsing(fn ($query) => $query->with(['channel', 'booking'])) + ->columns([ + TextColumn::make('occurred_at')->label('Wann')->dateTime('d.m.Y H:i')->sortable(), + TextColumn::make('channel.name')->label('Portal')->description(fn (IntakeObservation $record): string => $record->sourceLabel()), + TextColumn::make('period')->label('Zeitraum')->state(fn (IntakeObservation $record): ?string => $record->starts_on ? $record->starts_on->format('d.m.').'–'.$record->ends_on?->format('d.m.Y') : null)->placeholder('–'), + TextColumn::make('outcome')->label('Ergebnis')->badge()->description(fn (IntakeObservation $record): string => implode(' ', (array) $record->reasons))->wrap(), + TextColumn::make('case_type')->label('Art')->formatStateUsing(fn (?string $state): string => strtoupper((string) $state))->placeholder('–'), + IconColumn::make('applied')->label('Ausgeführt')->boolean()->tooltip('Ja: Vorgang angelegt, zugeordnet, Aufgabe erstellt oder zur Klärung vorgelegt. Nein: nur protokolliert.'), + TextColumn::make('mode')->label('Einstellung')->formatStateUsing(fn (CaseIntakeMode $state): string => match ($state) { + CaseIntakeMode::Observe => 'Beobachten', + CaseIntakeMode::Create => 'Anlegen', + CaseIntakeMode::Continue => 'Anlegen + weiter', + CaseIntakeMode::Off => 'Aus', + })->toggleable(), + TextColumn::make('reference')->label('Buchungsnr.')->placeholder('–')->toggleable(), + TextColumn::make('booking.reference')->label('Vorgang')->placeholder('–') + ->url(fn (IntakeObservation $record): ?string => $record->booking ? BookingResource::getUrl('view', ['record' => $record->booking]) : null), + TextColumn::make('missing')->label('Fehlt noch')->state(fn (IntakeObservation $record): string => implode(', ', (array) $record->missing))->placeholder('–')->wrap()->toggleable(isToggledHiddenByDefault: true), + ]) + ->filters([ + SelectFilter::make('channel_id')->label('Portal')->options(fn (): array => Channel::query()->orderBy('name')->pluck('name', 'id')->all()), + SelectFilter::make('outcome')->label('Ergebnis')->options(IntakeOutcome::class), + SelectFilter::make('applied')->label('Ausgeführt')->options(['1' => 'ja', '0' => 'nur protokolliert']), + ]); + } + + public static function getPages(): array + { + return ['index' => ListIntakeObservations::route('/')]; + } +} diff --git a/app/Filament/Resources/IntakeObservations/Pages/ListIntakeObservations.php b/app/Filament/Resources/IntakeObservations/Pages/ListIntakeObservations.php new file mode 100644 index 0000000..4b68fa5 --- /dev/null +++ b/app/Filament/Resources/IntakeObservations/Pages/ListIntakeObservations.php @@ -0,0 +1,11 @@ +label('Weitere Möglichkeiten')->icon(Heroicon::OutlinedEllipsisHorizontal)->button()->color('gray')]; } } diff --git a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php index 8092f0f..29059c5 100644 --- a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php +++ b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php @@ -4,6 +4,7 @@ use App\Actions\ClassifyPortalOccupation; use App\Actions\OpenPortalFile; +use App\Actions\ResolveChannelOccupation; use App\Enums\OccupationKind; use App\Exceptions\ReservationException; use App\Filament\Actions\AssignGuestAction; @@ -15,11 +16,13 @@ use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations; use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation; use App\Models\BlockedPeriod; +use App\Models\Booking; use App\Models\Channel; use BackedEnum; use Filament\Actions\Action; use Filament\Actions\ActionGroup; use Filament\Actions\ViewAction; +use Filament\Forms\Components\Radio; use Filament\Forms\Components\Select; use Filament\Infolists\Components\TextEntry; use Filament\Notifications\Notification; @@ -80,19 +83,85 @@ 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([Action::make('fileLink')->label('Als Buchung übernehmen')->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')]); + ])->recordActions([Action::make('clarifyLink')->label('Klären')->icon(Heroicon::OutlinedQuestionMarkCircle)->button()->color('warning')->visible(fn (BlockedPeriod $record): bool => static::isUnclear($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), Action::make('fileLink')->label('Als Buchung übernehmen')->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(bool $withFile = true): array { return [ - ...($withFile ? [static::openFileAction(), static::showFileAction()] : []), + ...($withFile ? [static::clarifyAction(), static::openFileAction(), static::showFileAction()] : []), AssignGuestAction::make(), static::classificationAction(), ...BlockedPeriodResource::portalActions(), ]; } + /** + * Whether the entry still waits for the landlord's answer (it is listed under "Zu erledigen"). + */ + public static function isUnclear(BlockedPeriod $record): bool + { + return ! $record->trashed() && BlockedPeriod::query()->unclear()->whereKey($record->id)->exists(); + } + + /** + * The one question for an unclear portal entry, in plain words: is it a booking (then it becomes a case), does it + * belong to a case that already exists, or is it no booking at all? The detailed tools stay under "Weitere". + */ + public static function clarifyAction(): Action + { + return Action::make('clarify')->label('Klären: Was ist das?')->icon(Heroicon::OutlinedQuestionMarkCircle)->color('primary') + ->visible(fn (BlockedPeriod $record): bool => static::isUnclear($record) && ! $record->is_representation) + ->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) + ->modalHeading(fn (BlockedPeriod $record): string => 'Belegung von '.($record->channel?->name ?? 'einem Portal').' am '.$record->starts_on->format('d.m.').'–'.$record->ends_on->format('d.m.Y')) + ->modalDescription(fn (BlockedPeriod $record): string => 'Für diesen Zeitraum wurde eine Belegung gemeldet. Bitte wählen Sie, was es ist.'.($record->review_note ? ' Hinweis: '.$record->review_note : '')) + ->modalSubmitActionLabel('Übernehmen') + ->schema(fn (BlockedPeriod $record): array => [ + Radio::make('answer')->hiddenLabel()->required()->live()->options(array_filter([ + 'booking' => static::canOpenFile($record) ? 'Eine Buchung über '.($record->channel?->name ?? 'das Portal').' – als Vorgang übernehmen' : null, + 'case' => static::sameNightCases($record) !== [] ? 'Gehört zu einem Vorgang, der schon da ist' : null, + 'block' => 'Keine Buchung: Sperre, eigene Nutzung oder Spiegelung eines anderen Portals', + ])), + Select::make('booking_id')->label('Vorgang')->options(fn (): array => static::sameNightCases($record)) + ->visible(fn (Get $get): bool => $get('answer') === 'case')->required(fn (Get $get): bool => $get('answer') === 'case'), + ]) + ->action(function (BlockedPeriod $record, array $data, OpenPortalFile $open, ResolveChannelOccupation $resolve, ClassifyPortalOccupation $classify) { + try { + if ($data['answer'] === 'booking') { + $booking = $open->handle($record); + Notification::make()->title('Als Buchung übernommen')->success()->send(); + + return redirect(BookingResource::getUrl('view', ['record' => $booking])); + } + if ($data['answer'] === 'case') { + $resolve->handle($record, 'booking', (int) $data['booking_id']); + Notification::make()->title('Dem Vorgang zugeordnet')->success()->send(); + + return null; + } + $classify->handle($record, OccupationKind::Block); + $record->refresh()->forceFill(['needs_review' => false, 'reviewed_at' => now(), 'review_note' => 'Persönlich als Sperre eingeordnet.'])->save(); + Notification::make()->title('Als Sperre eingeordnet')->success()->send(); + } catch (ReservationException $exception) { + Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); + } + + return null; + }); + } + + /** + * Cases of the same property with exactly these nights (the only ones the entry may belong to). + * + * @return array + */ + public static function sameNightCases(BlockedPeriod $record): array + { + return Booking::query()->occupying()->with('guest')->where('property_id', $record->property_id) + ->whereDate('arrival', $record->starts_on)->whereDate('departure', $record->ends_on)->get() + ->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->bookingChannelLabel()])->all(); + } + /** * Takes a reservation from a portal calendar over as a case (no second, manual "file"). */ diff --git a/app/Models/Channel.php b/app/Models/Channel.php index 95c6d42..18b2b5b 100644 --- a/app/Models/Channel.php +++ b/app/Models/Channel.php @@ -4,6 +4,7 @@ use App\Channels\ChannelRegistry; use App\Channels\Contracts\ChannelConnector; +use App\Enums\CaseIntakeMode; use App\Enums\ChannelBookingModel; use App\Enums\ChannelEchoBehavior; use App\Enums\ChannelExportMode; @@ -26,7 +27,7 @@ * A sales channel (portal) of a property. Our system leads: occupations are imported from the * channel and every channel gets its own export feed without its own occupations. */ -#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides'])] +#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides', 'case_intake'])] #[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])] class Channel extends Model { @@ -36,7 +37,7 @@ class Channel extends Model protected $attributes = [ 'status' => 'setup', 'booking_model' => 'mixed', 'import_enabled' => false, 'export_enabled' => false, 'export_mode' => 'test', - 'echo_behavior' => 'unverified', + 'echo_behavior' => 'unverified', 'case_intake' => 'off', ]; protected static function booted(): void @@ -63,6 +64,7 @@ protected function casts(): array return [ 'settings' => 'array', 'process_overrides' => 'array', + 'case_intake' => CaseIntakeMode::class, 'ical_analysis' => 'encrypted:array', 'ical_analyzed_at' => 'immutable_datetime', 'ical_rules' => 'array', diff --git a/app/Models/ChannelTask.php b/app/Models/ChannelTask.php index abcb0a3..1faea35 100644 --- a/app/Models/ChannelTask.php +++ b/app/Models/ChannelTask.php @@ -4,6 +4,7 @@ use App\Availability\AvailabilityChecker; use App\Enums\ChannelTaskAction; +use App\Enums\ChannelTaskProof; use App\Enums\ChannelTaskStatus; use App\Models\Concerns\BelongsToTenant; use Database\Factories\ChannelTaskFactory; @@ -18,7 +19,7 @@ * A change that has to be made by hand (or by an external automation) on a portal that * cannot be kept in sync fast enough by calendar feeds, e.g. because of instant booking. */ -#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error'])] +#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error', 'proof', 'proof_note', 'proof_at', 'proof_by'])] class ChannelTask extends Model { /** @use HasFactory */ @@ -39,6 +40,8 @@ protected function casts(): array 'completed_at' => 'immutable_datetime', 'reminded_at' => 'immutable_datetime', 'automation_sent_at' => 'immutable_datetime', + 'proof' => ChannelTaskProof::class, + 'proof_at' => 'immutable_datetime', ]; } @@ -60,7 +63,10 @@ protected function open(Builder $query): Builder return $query->where('status', ChannelTaskStatus::Open); } - public function complete(string $completedBy): void + /** + * Completes the task with the proof the person can give (at least: the change was made or started). + */ + public function complete(string $completedBy, ChannelTaskProof $proof = ChannelTaskProof::Initiated, ?string $note = null): void { if ($this->status !== ChannelTaskStatus::Open) { return; @@ -74,9 +80,38 @@ public function complete(string $completedBy): void 'status' => ChannelTaskStatus::Done, 'completed_by' => $completedBy, 'completed_at' => now(), + 'proof' => $proof, + 'proof_note' => filled($note) ? trim($note) : null, + 'proof_at' => now(), + 'proof_by' => $completedBy, ]); } + /** + * Raises the proof of a completed task (e.g. the block was later seen in the portal); never lowers it. + */ + public function prove(ChannelTaskProof $proof, string $by, ?string $note = null): void + { + $order = array_flip(array_map(fn (ChannelTaskProof $case): string => $case->value, ChannelTaskProof::cases())); + if ($this->status !== ChannelTaskStatus::Done || ($this->proof !== null && $order[$proof->value] <= $order[$this->proof->value])) { + return; + } + + $this->update(['proof' => $proof, 'proof_note' => filled($note) ? trim($note) : $this->proof_note, 'proof_at' => now(), 'proof_by' => $by]); + } + + /** + * The state of the task in plain words, including how far it is proven. + */ + public function proofLabel(): string + { + return match ($this->status) { + ChannelTaskStatus::Open => 'noch offen', + ChannelTaskStatus::Dismissed => 'verworfen', + ChannelTaskStatus::Done => ($this->proof ?? ChannelTaskProof::Initiated)->getLabel().($this->proof_note ? ' ('.$this->proof_note.')' : ''), + }; + } + /** * Human readable period, e.g. "14.06.2027 – 21.06.2027". */ diff --git a/app/Models/IntakeObservation.php b/app/Models/IntakeObservation.php new file mode 100644 index 0000000..6c11e06 --- /dev/null +++ b/app/Models/IntakeObservation.php @@ -0,0 +1,72 @@ + + */ + protected function casts(): array + { + return [ + 'mode' => CaseIntakeMode::class, + 'outcome' => IntakeOutcome::class, + 'applied' => 'boolean', + 'starts_on' => 'immutable_date', + 'ends_on' => 'immutable_date', + 'reasons' => 'array', + 'missing' => 'array', + 'occurred_at' => 'immutable_datetime', + ]; + } + + /** @return BelongsTo */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } + + /** @return BelongsTo */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } + + /** @return BelongsTo */ + public function blockedPeriod(): BelongsTo + { + return $this->belongsTo(BlockedPeriod::class)->withTrashed(); + } + + public function sourceLabel(): string + { + return match ($this->source) { + self::SOURCE_MAIL => 'Portal-E-Mail', + self::SOURCE_ADOPTION => 'Bestandsübernahme', + default => 'Portalkalender', + }; + } +} diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index 0fd063b..e19d1ea 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -27,6 +27,9 @@ class CaseActivities /** Activities that are listed on their own in the work list (they are not "the" next step of a case). */ private const LISTED_SEPARATELY = ['channel_block']; + /** Activities that are the next step whatever else is open. */ + private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported']; + /** * @return list */ @@ -110,7 +113,7 @@ public static function for(Booking $booking): array } foreach (self::channelTasks($booking) as $task) { - $activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period(), url: ChannelTaskResource::getUrl()); + $activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl()); } if ($profile->payments() === Responsibility::Portal) { @@ -157,7 +160,11 @@ public static function for(Booking $booking): array */ public static function next(Booking $booking): ?Activity { - foreach (self::for($booking) as $activity) { + $activities = self::for($booking); + // A report of the portal (cancellation, other dates) comes before everything else on the case. + usort($activities, fn (Activity $a, Activity $b): int => (int) in_array($b->key, self::URGENT, true) <=> (int) in_array($a->key, self::URGENT, true)); + + foreach ($activities as $activity) { if ($activity->state->needsAction() && ! in_array($activity->key, self::LISTED_SEPARATELY, true)) { return $activity; } diff --git a/app/Process/WorkList.php b/app/Process/WorkList.php index e2ce222..61e2f5a 100644 --- a/app/Process/WorkList.php +++ b/app/Process/WorkList.php @@ -62,8 +62,8 @@ public static function items(): array foreach (BlockedPeriod::query()->unclear()->with(['channel', 'property'])->whereDate('ends_on', '>=', today())->orderBy('starts_on')->get() as $occupation) { $items[] = [ - 'title' => 'Unbekannte Belegung von '.($occupation->channel?->name ?? 'einem Portal').' – was ist das?', - 'detail' => $occupation->starts_on->format('d.m.').'–'.$occupation->ends_on->format('d.m.Y').' · '.$occupation->property?->name, + 'title' => 'Belegung von '.($occupation->channel?->name ?? 'einem Portal').' klären', + 'detail' => 'Für den Zeitraum '.$occupation->starts_on->format('d.m.').'–'.$occupation->ends_on->format('d.m.Y').' wurde eine Belegung von '.($occupation->channel?->name ?? 'einem Portal').' gemeldet. Bitte klären Sie, um welche Art von Belegung es sich handelt. · '.$occupation->property?->name, 'url' => PortalOccupationResource::getUrl('view', ['record' => $occupation]), 'button' => 'Klären', 'tone' => 'warning', diff --git a/database/migrations/2026_11_03_090000_create_case_intake.php b/database/migrations/2026_11_03_090000_create_case_intake.php new file mode 100644 index 0000000..245ceea --- /dev/null +++ b/database/migrations/2026_11_03_090000_create_case_intake.php @@ -0,0 +1,62 @@ +string('case_intake', 12)->default('off'); + }); + + Schema::create('intake_observations', function (Blueprint $table): void { + $table->id(); + $table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete(); + $table->foreignId('channel_id')->constrained()->cascadeOnDelete(); + $table->foreignId('blocked_period_id')->nullable()->constrained()->nullOnDelete(); + $table->foreignId('portal_email_id')->nullable()->constrained()->nullOnDelete(); + $table->foreignId('booking_id')->nullable()->constrained()->nullOnDelete(); + $table->string('fingerprint', 64); + $table->string('source', 12); + $table->string('mode', 12); + $table->string('outcome', 20); + $table->boolean('applied')->default(false); + $table->string('case_type', 4)->nullable(); + $table->date('starts_on')->nullable(); + $table->date('ends_on')->nullable(); + $table->string('reference', 100)->nullable(); + $table->json('reasons')->nullable(); + $table->json('missing')->nullable(); + $table->timestamp('occurred_at'); + $table->timestamps(); + $table->unique(['tenant_id', 'fingerprint']); + $table->index(['channel_id', 'occurred_at']); + }); + + Schema::table('channel_tasks', function (Blueprint $table): void { + $table->string('proof', 12)->nullable(); + $table->text('proof_note')->nullable(); + $table->timestamp('proof_at')->nullable(); + $table->string('proof_by')->nullable(); + }); + } + + public function down(): void + { + Schema::table('channel_tasks', function (Blueprint $table): void { + $table->dropColumn(['proof', 'proof_note', 'proof_at', 'proof_by']); + }); + Schema::dropIfExists('intake_observations'); + Schema::table('channels', function (Blueprint $table): void { + $table->dropColumn('case_intake'); + }); + } +}; diff --git a/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md b/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md new file mode 100644 index 0000000..a1dec39 --- /dev/null +++ b/docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md @@ -0,0 +1,224 @@ +# Umsetzungsergebnis Paket 4: Ein Eingang für alle Kanäle + +Stand: 03.11.2026 · Branch `feature/eingang` (aufbauend auf `cf11c8a`, Pakete 1–3) · Grundlage: [UMSETZUNGSPLAN_v0.10](UMSETZUNGSPLAN_v0.10.md) §4.3, §5.5, Abnahmekriterien 4.1–4.7. Die normative Prozessarchitektur v0.10 wurde nicht verändert. + +> Hinweis: Der Auftrag kam abgeschnitten an (Abschnitt 11 endet mitten im Satz). Umgesetzt wurde alles bis dahin. Dokumentation und Bericht folgen dem Muster der Pakete 1–3. + +--- + +## 1. Implementierungsstand + +Paket 4 ist umgesetzt. Alle Abnahmekriterien 4.1–4.7 sind durch Tests belegt, die Oberflächen wurden im Browser geprüft. **Kein Portal ist automatisch aktiviert:** Jeder Kanal steht auf „Aus“, auch nach der Migration. Die Aktivierung auf Produktion ist nicht Teil des Auftrags. + +| Bereich | Stand | +|---|---| +| Ein Eingang für Kalender, Buchungs-, Anfrage- und Stornomails (`App\Channels\Intake\PortalIntake`) | umgesetzt | +| Automatische Vorgänge nur bei sicherer Erkennung; unsichere Fälle werden geklärt | umgesetzt | +| Dublettenregel: Referenz → gleiches Portal mit gleichen Nächten → Spiegelung; keine Zusammenführung nach Überschneidung | umgesetzt | +| Schalter je Kanal: Aus / Beobachten / Anlegen / Anlegen und weiterbearbeiten | umgesetzt | +| Eingangsprotokoll (Expertenansicht und Befehl) | umgesetzt | +| Portalstorno und -änderung als Aufgabe am Vorgang, nie stille Stornierung | umgesetzt | +| Sperrnachweis in drei Stufen | umgesetzt | +| Bestandsübernahme mit Vorschau, Bericht, Wiederholbarkeit, Rücknahme | umgesetzt | +| A2-Portalanfrage aus der Anfrage-Mail | umgesetzt | +| Rückbau von „Ungeklärte Belegungen“ und `AssignOccupationGuest` | teilweise (siehe §7) | + +Tests: **662 grün** (vorher 648; 14 neue in `CaseIntakeTest`), Pint sauber. + +--- + +## 2. Umgesetzte Geschäftsfunktionen + +**Sicher erkannte Buchung → Vorgang ohne Klick.** +- *Quellen:* eine Buchungsmail des Portals mit Zeitraum und Buchungsnummer, oder ein Kalendereintrag, den die Regeln des Kanals als Reservierung dieses Portals erkennen bzw. den die Vermieterin so eingeordnet hat. +- *Ergebnis:* ein Vorgang „Gebucht über FeWo-direkt“ mit Ursprungskanal, Buchungsnummer und Abwicklungsprofil; die Vorgangsart ergibt sich aus dem Profil (A3/A4/A5). +- *Was nicht entsteht:* kein Angebot, keine Annahme, kein eigener Preis. Gast, Personen und Preis bleiben „noch nicht bekannt“; ein Name aus dem Kalender steht nur als Hinweis in der Notiz. +- *Nächste Schritte:* Die Aktivitäten aus Paket 2 übernehmen, z. B. „Kontaktdaten eintragen“, „Gesamtpreis laut Portal eintragen“, „Buchungsunterlagen prüfen und senden“. + +**Derselbe Fall auf mehreren Wegen bleibt ein Vorgang.** +- Kommt die Buchung zuerst per Mail und dann im Kalender, wird der Kalendereintrag dem Vorgang zugeordnet. Ebenso die Spiegelung bei einem anderen Portal. +- Wiederholte Abgleiche und Mails erzeugen nichts doppelt. +- Unterschiedliche Buchungsnummern oder nur überlappende Termine werden **nie** zusammengeführt, sondern geklärt. + +**Unklare Belegung.** +- Unter „Zu erledigen“ steht: „Belegung von FeWo-direkt klären – Für den Zeitraum 26.11.–29.11.2026 wurde eine Belegung von FeWo-direkt gemeldet. Bitte klären Sie, um welche Art von Belegung es sich handelt.“ +- Der Knopf „Klären: Was ist das?“ bietet drei Antworten: + - Buchung über das Portal: Der Vorgang entsteht. + - Gehört zu einem vorhandenen Vorgang: nur Vorgänge mit genau diesen Nächten. + - Keine Buchung: Sperre, eigene Nutzung oder Spiegelung. +- Die bisherigen Detailwerkzeuge liegen unter „Weitere Möglichkeiten“. + +**Portalanfrage (A2).** Eine Anfrage-Mail des Portals wird zum Vorgang „Anfrage über FeWo-direkt“ mit Zeitraum und Anfragenummer. Gast und Personen bleiben unbekannt, der Vorgang fragt sie gezielt ab und läuft danach wie A1. Ob der Zeitraum reserviert wird, folgt der Einstellung für Anfragen dieses Portals. + +**Portalstorno und -änderung.** +- *Auslöser:* + - Stornomail mit Buchungsnummer eines gebuchten Vorgangs; + - Kalendereintrag eines gebuchten Vorgangs, der verschwunden ist (erst nach zwei bestätigenden Abgleichen); + - abweichende Termine im Kalender. +- *Folgen am Vorgang:* + - Aufgabe „Das Portal meldet eine Stornierung – bitte prüfen“ bzw. „… eine Änderung …“; + - Eintrag im Verlauf mit dem Portal als Quelle; + - die Aufgabe wird zum nächsten Schritt des Vorgangs. +- *Was nicht passiert:* Der Vorgang bleibt gebucht und der Zeitraum belegt. Ein mit dem Vorgang verbundener Mail-Eintrag wird nicht mehr freigegeben. Über „Stornieren …“ (Paket 2) gelangt die Vermieterin in den Stornoweg. +- Jede Meldung zählt einmal. Zwei verschiedene Mails sind zwei Meldungen; derselbe verschwundene Eintrag bleibt eine. + +**Sperrnachweis.** +- „Erledigt“ bei einer Portalaufgabe fragt, was die Person sagen kann: + - „Ich habe den Zeitraum im Portal gesperrt“ (*veranlasst*); + - „… und im Kalender des Portals gesehen“ (*im Portal gesehen*); + - „Das Portal hat es bestätigt“ (*Wirksamkeit bestätigt*); + - optional mit Notiz. +- „Nachweis ergänzen“ hebt die Stufe später an, senkt sie aber nie. +- Die Vorgangsseite zeigt die Stufe, z. B. „In Ostseeklar sperren · 07.12.–14.12.2026 · im Portal gesehen (im Kalender rot)“. +- Eine erledigte Automatisierung gilt nur als *veranlasst*. + +--- + +## 3. Nachweise zu den Abnahmekriterien + +| ID | Kriterium | Nachweis (`tests/Feature/CaseIntakeTest.php`) | Ergebnis | +|---|---|---|---| +| 4.1 | A3 Destination Solutions manuell; gebucht ohne Angebot/Annahme; Sperraufgaben, Unterlagen, Zahlung durch uns, Portalpreis | `test_a_destination_solutions_booking_is_entered_by_hand_and_handled_by_us`: A3, bestätigt, Angebotsversion 0, Preis 840,00 €, Zahlungsaufgaben aktiv, „In Ostseeklar sperren“, „Buchungsunterlagen prüfen und senden“ | **erfüllt** | +| 4.2 | FeWo-direkt-Mail → Vorgang ohne Klick; späterer iCal-Eintrag → kein zweiter; Zahlung „über das Portal“, keine eigenen Mahnungen | `test_a_booking_mail_becomes_a_case_and_the_later_calendar_entry_joins_it` | **erfüllt**. Fehlende Postanschrift erzeugt keine Aufgabe; die E-Mail-Adresse wird nur verlangt, weil eigene Unterlagen sie brauchen. | +| 4.3 | iCal-Eintrag ohne Erkennung → kein Vorgang, Aufgabe „Was ist das?“, Antwort „Buchung“ legt ihn an | `test_an_unrecognised_calendar_entry_is_clarified_and_the_answer_booking_creates_the_case` | **erfüllt** | +| 4.4 | Stornomail oder verschwundener iCal-Eintrag → „Stornierung prüfen“, Vorgang bleibt gebucht | `test_a_cancellation_mail_reaches_the_case_as_a_task_and_cancels_nothing`, `test_a_disappeared_or_changed_calendar_entry_is_reported_once_and_nothing_is_released` | **erfüllt** | +| 4.5 | „In Portal X sperren“, Erledigen mit Stufe und Notiz, Vorgangsseite zeigt Nachweisgrad | `test_portal_blocks_state_how_far_they_are_proven` | **erfüllt** | +| 4.6 | Beobachtungsmodus: keine Vorgänge, Bericht über das, was entstanden wäre | `test_observing_creates_nothing_and_reports_what_would_have_been_created` (`channels:intake-report`) | **erfüllt** | +| 4.7 | A2-Portalanfrage mit unvollständigen Daten → Anfrage, fordert fehlende Daten | `test_a_portal_request_becomes_a_request_that_asks_for_the_missing_data` | **erfüllt** | + +Weitere Tests: +- Kalender mehrfach gelesen ergibt genau einen Vorgang und einen Protokolleintrag. +- Gleiches Portal mit gleichen Nächten wird dem vorhandenen Vorgang zugeordnet. +- Fremdportal-Reservierung und überlappende Reservierung werden nie zum Vorgang. +- Ein nicht eingeschalteter Kanal verhält sich wie bisher; neue Kanäle starten auf „Aus“. +- „Anlegen und weiterbearbeiten“ versendet trotzdem keine unfreigegebenen Unterlagen. +- Bestandsübernahme: Vorschau, Anwendung, Wiederholung ohne Dublette, Rücknahme. + +--- + +## 4. Technische Umsetzung + +| Baustein | Inhalt | +|---|---| +| `App\Channels\Intake\PortalIntake` (neu) | `evaluate()` bewertet ohne Änderung; `process()` handelt nach Kanalschalter; `afterSync()` nach jedem Kalenderabgleich; `cancellationMail()`, `inquiryMail()`; `adopt()` für die Bestandsübernahme. Ergebnisse als `IntakeDecision` mit Begründung und fehlenden Angaben. | +| `App\Enums\CaseIntakeMode`, `IntakeOutcome`, `ChannelTaskProof` (neu) | Schalter je Kanal, Ergebnis eines Eingangs, Nachweisstufe | +| `App\Models\IntakeObservation` (neu) | Eingangsprotokoll; ein Eintrag je Ereignis und Ergebnis (Fingerabdruck, eindeutig je Mandant) | +| `App\Actions\TakeOverPortalInquiry` (neu) | A2-Anfrage mit unbekannten Angaben, Reservierung nach Kanalprofil | +| `TakeOverExternalBooking` | Neues Feld `processing_mode`. Automatisch angelegte Vorgänge laufen bei „Anlegen“ mit Freigabe, bei „Anlegen und weiterbearbeiten“ nach Profil. | +| `SyncChannel` | Ruft nach erfolgreichem Abgleich `afterSync()` auf, gekapselt mit `rescue()`. Ein Fehler im Eingang lässt den 5-Minuten-Abgleich nie scheitern. | +| `ProcessPortalMail` | Leitet Buchung, Anfrage und Storno an den Eingang. Ein mit einem Vorgang verbundener Mail-Eintrag wird durch eine Stornomail nicht mehr freigegeben (Status „Bitte prüfen“). | +| `BookingTaskKind` | `PortalCancellationReported`, `PortalChangeReported`. Je Vorgang und Art eine Aufgabe; eine neue Meldung öffnet sie wieder. | +| `ChannelTask` | `proof`, `proof_note`, `proof_at`, `proof_by`; `complete()` mit Stufe; `prove()` hebt nur an; `proofLabel()` | +| `CaseActivities` | Portalmeldungen haben Vorrang als nächster Schritt; Sperraufgaben zeigen ihren Nachweis. | +| Oberfläche | Kanalformular „Erkannte Buchungen automatisch als Vorgang übernehmen?“; Klärdialog an der Portalbelegung; Dialoge „Erledigt“ und „Nachweis ergänzen“ bei Portalaufgaben; Eingangsprotokoll unter System (Expertenansicht); Vorgangsseite, technischer Abschnitt „Quellen und Kalenderdarstellungen“ | +| Befehle | `channels:intake-report {--days}`; `channels:adopt-occupations {--channel=*} {--apply} {--revert=}` | +| Migration | `2026_11_03_090000_create_case_intake`, rein additiv: `channels.case_intake` (Standard `off`), Tabelle `intake_observations`, Nachweisspalten an `channel_tasks` | + +**Wann ein Eintrag als sicher gilt.** +- Mail: Typ „Buchung“ mit Zeitraum *und* Buchungsnummer. Ohne Nummer wird geklärt, weil sich ein späterer Kalendereintrag sonst nicht sicher zuordnen lässt. +- Kalender: Die Regel erkennt „Portalreservierung“, „Kandidat für führende Belegung“ und Ursprung „dieses Portal“; oder die Vermieterin hat den Eintrag als Reservierung dieses Portals eingeordnet. + +**Was immer geklärt wird.** +- Belegt-Meldungen ohne Regel +- Spiegelungen fremder Portale +- Überschneidung mit einem Vorgang oder mit weiteren Einträgen desselben Portals +- Prüfhinweise am Eintrag +- „Was kommt über dieses Portal?“ = „nur Anfragen“ + +**Was nie ein Vorgang wird.** Einträge, die als Sperrzeit oder privat eingeordnet sind, sowie Vergangenes. + +**Zuordnung nach Terminen.** Nur innerhalb *desselben* Portals, bei *genau* gleichen Nächten und *genau einem* passenden Vorgang ohne widersprechende Buchungsnummer. Ein Portal kann dieselben Nächte nicht zweimal vergeben, deshalb ist das keine Datumsheuristik im Sinn des Auftrags. + +**Mandantentrennung.** Alle Abfragen laufen über den Mandantenbereich der Modelle; das Protokoll ist je Mandant eindeutig. + +--- + +## 5. Aktivierung, Automatik und externe Kommunikation + +**Schalter je Kanal** (Kanäle › Portal bearbeiten): + +| Stufe | Wirkung | +|---|---| +| Aus (Standard, auch für alle bestehenden Kanäle) | Wie bisher. Erkannte Buchungen erscheinen als Klärungsfall; es wird nichts protokolliert. | +| Beobachten | Es entsteht nichts und es wird nichts geändert. Das Eingangsprotokoll zeigt Ergebnis, Vorgangsart, Zuordnung, fehlende Angaben und Begründung. | +| Anlegen | Vorgänge, Zuordnungen, Klärungen und Meldungsaufgaben entstehen. Neue Vorgänge stehen auf „Sie geben frei“. | +| Anlegen und weiterbearbeiten | Wie „Anlegen“; die neuen Vorgänge folgen der Einstellung unter „So arbeite ich“. | + +**Externe Kommunikation.** Kein automatisch angelegter Vorgang versendet etwas, das nicht freigegeben ist. Buchungsunterlagen extern gehen erst raus, wenn beides vorliegt: +- die Buchungsunterlagen sind freigegeben; +- die Portalvorlage ist freigegeben und als Wiedergabe der Portalbedingungen bestätigt. + +Das ist der Freigabeschutz aus Paket 3. Bei „Anlegen“ gibt die Vermieterin zusätzlich jeden Schritt selbst frei. Zahlungsaufforderungen entstehen nur, wenn wir laut Profil für die Zahlung zuständig sind. + +**Meldungen zu bekannten Vorgängen** (Storno, Änderung) erzeugen Aufgaben nur bei „Anlegen“ oder „Anlegen und weiterbearbeiten“. Bei „Beobachten“ werden sie nur protokolliert. Bei „Aus“ bleibt es wie bisher: Die Portalmail wird als „Bitte prüfen“ gemeldet. + +**Vermeidung unnötiger Aufgaben.** +- Ein verschwundener Eintrag zählt erst, wenn der Abgleich ihn nach zwei bestätigenden Läufen entfernt. +- Bei ungewöhnlich vielen fehlenden Einträgen wird nichts entfernt. +- Unveränderte Wiederholungen erzeugen weder Aufgaben noch Verlaufseinträge. +- Fehlgeschlagene Abgleiche lösen keine Meldungen aus. + +--- + +## 6. Ergebnisse der Tests und der visuellen Prüfung + +**Tests:** 662 Tests, 3636 Zusicherungen, alle grün. Pint sauber. Die bestehenden Kanal-, Mail-, Spiegelungs- und Klärungstests (129) laufen unverändert; nur ein Listentitel unter „Zu erledigen“ wurde angepasst. + +**Browser:** Chromium über Playwright, lokaler Server, **Kopie** der lokalen Datenbank im Scratchpad, Anmeldung mit Zwei-Faktor-Code, Kanal „FeWo-direkt“ auf „Anlegen“. Geprüft: +- **„Zu erledigen“:** + - „Belegung von FeWo-direkt klären“ mit dem Klartextsatz; + - „Das Portal meldet eine Stornierung – bitte prüfen“ am automatisch angelegten Vorgang; + - „In Ostseeklar sperren“; + - „Buchungsunterlagen prüfen und senden“ mit den Prüfpunkten aus Paket 3. +- **Klärdialog:** zwei passende Antworten, die dritte („vorhandener Vorgang“) erscheint nur bei Vorgängen mit gleichen Nächten. +- **Dialog „Erledigt“** mit den drei Nachweisstufen und Notiz. +- **Eingangsprotokoll** mit Klärung, Neuer Vorgang und Stornomeldung. Daraufhin habe ich die Begründung unter das Ergebnis verlegt, weil sie in der breiten Tabelle abgeschnitten war. + +Keine Konsolenfehler. Die lokale Arbeitsdatenbank blieb unberührt. + +**Nicht geprüft:** echte Portalmails und echte Feeds von FeWo-direkt; Tablet und Smartphone; MariaDB. + +--- + +## 7. Rückwärtskompatibilität und verbleibende Risiken + +**Kompatibilität:** +- Ohne Einschalten ändert sich nichts. Die einzige sichtbare Änderung für alle sind der neue Klärdialog und der Titel unter „Zu erledigen“. +- Bestehende Vorgänge, Preise, Dokumente und Spiegelungen bleiben unverändert. +- Die Bestandsübernahme ändert nur mit `--apply` etwas. Sie legt Vorgänge mit Freigabe an und schreibt einen Bericht nach `storage/app/private/intake-adoptions/`. +- `--revert=` stellt die Einträge wieder her und entfernt die Vorgänge des Laufs, sofern mit ihnen noch nichts geschehen ist (kein Dokument, keine Zahlung). Offene Sperraufgaben des Laufs werden verworfen. +- Vor `--apply` auf echten Daten zusätzlich eine Datenbanksicherung ziehen. + +**Nicht vollständig zurückgebaut:** +- „Gast zuordnen“ an der Portalbelegung (`AssignOccupationGuest`) und die Liste „Portalbelegungen & Klärung“ bestehen in der Expertenansicht weiter. Die einfache Ansicht braucht sie nicht mehr. Der vollständige Rückbau gehört in einen eigenen Schritt, weil viele bestehende Tests und der Belegungsplan darauf aufbauen. +- `OpenPortalFile` bleibt als Baustein der Antwort „Buchung“. + +**Risiken:** +- *Erkennung realer Mails:* nur an Testmustern geprüft (Annahme §8.5 des Plans). Deshalb zuerst „Beobachten“ und das Protokoll mit echten Fällen abgleichen. +- *Kalenderregeln:* Die Sicherheit der iCal-Übernahme hängt an der Regel des Kanals („Portalreservierung, führend, dieses Portal“). Eine zu weit gefasste Regel würde falsche Vorgänge erzeugen. Auch dafür ist der Beobachtungsmodus da. +- *Buchungsmails ohne Nummer* werden geklärt, nicht übernommen. Liefert ein Portal nie Nummern, bleibt dort die Klärung. +- *Last im 5-Minuten-Abgleich:* `afterSync()` läuft je Kanal über dessen offene Einträge. Bei wenigen Wohnungen ist das unkritisch, und ein Fehler bricht den Abgleich nicht ab. +- Sperraufgaben entstehen wie bisher für jede belegende Sperre, auch für unklare Einträge. Das ist unverändert und gewollt, damit nichts doppelt vermietet wird. +- Die Migration ist auf MariaDB noch nicht geprüft. + +--- + +## 8. Offene Punkte und erforderliche Entscheidungen + +| Was | Wer | Wirkung bis dahin | +|---|---|---| +| Je Portal entscheiden, wann von „Aus“ auf „Beobachten“ und danach auf „Anlegen“ umgestellt wird | Betreiber | Alles wie bisher | +| Kalenderregeln je Portal prüfen: Liefert der Feed Buchungsnummer oder Gastnamen? (§8.3: „Erkennt die iCal-Regel sicher?“) | Betreiber, Kanaleinrichtung | Ohne Regel nur Klärung | +| Absenderadressen der Portalmails eintragen, Mail-Eingang einschalten | Betreiber | Keine Mail-Übernahme | +| Freigaben aus Paket 3 (Buchungsunterlagen, FeWo-direkt-Vorlage FW-01) | Betreiber | Unterlagen nur von Hand mit Bestätigung | +| Bestandsübernahme auf Test, dann Produktion (`--apply`, mit Sicherung) | Betreiber | Bestehende Belegungen bleiben Klärungsfälle | + +Grundsatzentscheidungen wurden nicht getroffen; B1 und B3–B5 bleiben offen. + +--- + +## 9. Empfehlung für die nächsten Schritte + +1. **Pakete 1–4 auf dem Testsystem** ausrollen. Danach FeWo-direkt auf „Beobachten“ stellen, nach einigen echten Buchungen `channels:intake-report` prüfen und erst dann auf „Anlegen“. +2. **Paket 5 (Änderung, Storno, kontrollierter Abbruch)** schließt direkt an: Die Aufgaben „Das Portal meldet eine Stornierung/Änderung“ sind die Einstiege. Paket 5 kann sie um „Stornierung übernehmen“ (Initiator „Gast über Portal“) und die Stornobestätigung als Dokumentart erweitern. +3. Danach den Rückbau der Expertenwerkzeuge an Portalbelegungen (§7) und die Bedienprobe mit der Vermieterin. diff --git a/docs/STATUS.md b/docs/STATUS.md index d982543..4522b21 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,7 @@ # Projektstand +**Ein Eingang für alle Kanäle – Paket 4 der Prozessarchitektur v0.10 (03.11.2026, Branch `feature/eingang`, nicht ausgeliefert):** Portalbuchungen und -anfragen kommen über einen Eingang (`App\Channels\Intake\PortalIntake`, aufgerufen nach jedem Kalenderabgleich und aus `ProcessPortalMail`): sicher erkannte Buchungen (Buchungsmail mit Nummer, Kalenderregel „Reservierung dieses Portals“) werden zum Vorgang ohne Angebot/Annahme, Anfrage-Mails zur A2-Anfrage; Dubletten über Buchungsnummer → gleiches Portal mit gleichen Nächten → Spiegelung, nie nach bloßer Überschneidung; Unsicheres wird unter „Zu erledigen“ geklärt („Klären: Was ist das?“). Stornomail, verschwundener oder geänderter Kalendereintrag eines gebuchten Vorgangs → Aufgabe am Vorgang, keine stille Stornierung. Schalter je Kanal `channels.case_intake` (Aus = Standard, Beobachten, Anlegen, Anlegen + weiter); Eingangsprotokoll (System › Eingangsprotokoll, `channels:intake-report`); Bestandsübernahme `channels:adopt-occupations` (Vorschau, `--apply`, `--revert`). Portalaufgaben mit Nachweisstufe (veranlasst / im Portal gesehen / bestätigt). **662 Tests grün**, Browserprüfung durchgeführt. Ergebnis und Aktivierungsweg: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md). + **Dokumentenzusammenstellung und Vorlagensteuerung – Paket 3 der Prozessarchitektur v0.10 (02.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Vor jedem Dokument dieselbe Zusammenstellung (`App\Documents\DocumentComposer`, Ansicht `filament/document-composition`): Empfänger, Zeitraum, Preis mit Herkunft, Leistungen, Stornoregel, Vorlage mit Herkunft, Anlagen, Hinweise (fehlt / bitte prüfen / Info), E-Mail- und PDF-Vorschau. Dokumentart je Vorgang automatisch (`App\Enums\DocumentKind`): Anfrage → Angebot mit Annahmelink, eigene Buchung → Bestätigung mit Mietvertrag, beim Portal verbindlich (A3/A4) → **Buchungsunterlagen ohne Annahmelink** (`BookingDocumentation`). Unterlagen verbindlicher Vorgänge nur über `SendBookingDocuments` (automatisch nur ohne Prüfpunkte, von Hand mit bestätigten Hinweisen, einmalig per Sperre); Angebote mit `expected_version` gegen Doppelversand; ohne Vorreservierung (Hold 0) kein Angebot ohne ausdrückliche Entscheidung. Vorlagen haben Freigabe und „gibt nur Portalbedingungen wieder“ (entfallen bei Textänderung); die Buchungsunterlagen extern sind eine Arbeitsfassung bis zur Freigabe unter So arbeite ich › Dokumente. **648 Tests grün**, Browserprüfung durchgeführt. Ergebnis, offene Freigaben (FeWo-direkt-Vorlage FW-01, Unterlagentext) und Empfehlung Paket 4: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md). **Vorgangskern und geführte Vorgangsbearbeitung – Pakete 1 und 2 der Prozessarchitektur v0.10 (01.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Die Buchung ist der einheitliche Vorgang (Eingangsart, Vorgangsart A1–A6, eingefrorenes Abwicklungsprofil, gespeicherter Verlauf `booking_events`); Gast, Personen und Preis dürfen unbekannt sein, keine Platzhalter-Gäste mehr. Einstellungen in Ebenen: System › **So arbeite ich** (Vermieterstandard) → Abweichung der Wohnung (Expertenansicht) → Abweichung je Portal und Buchungstyp → Vorgang (`App\Process\ProcessSettings`). Ein Übernahmeweg für beim Portal feste Buchungen (`TakeOverExternalBooking`, Portalpreis als eine Position) ersetzt „Portal-Buchung erfassen“ und die Logik von „Akte anlegen“. Startseite **„Zu erledigen“**, neue Vorgangsseite (Stand in einem Satz, „Als Nächstes“, Ablauf, Verlauf, Hauptknopf, Automatik/Freigabe, „Beenden“ nur über Storno), „Neu“-Dialog mit drei Einstiegen, Status von Hand nur im Expertenmodus. Migration übernimmt bisheriges Verhalten unverändert (Bericht `php artisan process:settings-report`). **634 Tests grün**, Pint. Ergebnis, Abnahmekriterien und offene Punkte: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P1_P2.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P1_P2.md). Vor dem Deployment: Migration auf dem Testsystem (MariaDB) prüfen, Bedienprobe mit der Vermieterin. diff --git a/tests/Feature/CaseIntakeTest.php b/tests/Feature/CaseIntakeTest.php new file mode 100644 index 0000000..c7ffcc7 --- /dev/null +++ b/tests/Feature/CaseIntakeTest.php @@ -0,0 +1,367 @@ +travelTo(CarbonImmutable::parse('2026-11-02 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + app(TenantContext::class)->set($this->property->tenant); + $this->fewo = Channel::factory()->for($this->property)->create([ + 'name' => 'FeWo-direkt', + 'booking_model' => 'portal_booking', + 'case_intake' => CaseIntakeMode::Create, + 'settings' => ['import_url' => 'https://portal.example/fewo.ics', 'email_senders' => 'fewo-direkt.de'], + 'process_overrides' => ['booking' => ['payments' => 'portal']], + ]); + $this->fewo->forceFill(['ical_active_rules' => [self::reservationRule()]])->save(); + Mail::fake(); + Storage::fake('local'); + Http::fake(fn () => Http::response($this->currentFeed)); + $this->withoutVite(); + } + + /** 4.2 */ + public function test_a_booking_mail_becomes_a_case_and_the_later_calendar_entry_joins_it(): void + { + $this->mail('Neue Buchung', self::BOOKING_MAIL); + + $case = Booking::query()->sole(); + $this->assertSame([BookingStatus::Confirmed, IntakeKind::Booking, CaseType::A4, 'HA-7X3K9Q', $this->fewo->id], [$case->status, $case->intake, $case->case_type, $case->portal_reference, $case->origin_channel_id]); + $this->assertNull($case->guest_id); + $this->assertNull($case->total); + $this->assertNull($case->guests); + $this->assertSame(ProcessingMode::Manual, $case->processing_mode); + $this->assertSame(0, $case->offer_version); + $this->assertSame('Automatisch aus der Buchungsmail von FeWo-direkt angelegt', $case->events()->where('type', 'intake')->value('summary')); + + $this->sync($this->fewo, self::feed('evt-1', 'Reservation: Nora Beispiel', 'Buchung HA-7X3K9Q', '20261207', '20261214')); + + $this->assertSame(1, Booking::query()->count()); + $entry = $this->fewo->blockedPeriods()->where('source', 'channel')->sole(); + $this->assertTrue($entry->is_representation); + $this->assertSame($case->id, $entry->linked_booking_id); + $this->assertStringContainsString('Weitere Quelle zugeordnet', (string) $case->events()->where('type', 'intake')->reorder()->orderByDesc('id')->value('summary')); + + // The portal collects the money: no payment tasks of our own; nothing went to the guest. + $this->assertFalse($case->fresh()->wantsPaymentTasks()); + $this->assertSame('läuft über das Portal', collect(CaseActivities::for($case->fresh()))->firstWhere('key', 'payment')?->detail); + Mail::assertNotSent(BookingDocumentation::class); + Mail::assertNotSent(BookingConfirmed::class); + } + + public function test_a_calendar_reservation_becomes_one_case_however_often_the_calendar_is_read(): void + { + $feed = self::feed('evt-2', 'Reservation: Nora Beispiel', 'Buchung HA-AAAAA1', '20261207', '20261214'); + + $this->sync($this->fewo, $feed); + $this->sync($this->fewo, $feed); + $this->sync($this->fewo, $feed); + + $case = Booking::query()->sole(); + $this->assertSame('HA-AAAAA1', $case->portal_reference); + $this->assertStringContainsString('Name laut Portal: Nora Beispiel', (string) $case->internal_notes); + $this->assertNull($case->guest_id, 'a name in a calendar is no guest identity'); + $this->assertSame(1, IntakeObservation::query()->where('outcome', IntakeOutcome::Create)->count()); + } + + public function test_the_same_portal_with_the_same_nights_joins_the_existing_case(): void + { + $case = app(TakeOverExternalBooking::class)->handle($this->property, $this->fewo, CarbonImmutable::parse('2026-12-07'), CarbonImmutable::parse('2026-12-14'), ['portal_total' => 90000]); + + $this->sync($this->fewo, self::feed('evt-3', 'Reservation: Nora Beispiel', '', '20261207', '20261214')); + + $this->assertSame(1, Booking::query()->count()); + $this->assertSame($case->id, $this->fewo->blockedPeriods()->sole()->linked_booking_id); + } + + /** 4.3 */ + public function test_an_unrecognised_calendar_entry_is_clarified_and_the_answer_booking_creates_the_case(): void + { + $this->sync($this->fewo, self::feed('evt-4', 'Blocked', '', '20261207', '20261214')); + + $this->assertSame(0, Booking::query()->count()); + $this->assertContains('Belegung von FeWo-direkt klären', array_column(WorkList::items(), 'title')); + $observation = IntakeObservation::query()->sole(); + $this->assertSame(IntakeOutcome::Clarify, $observation->outcome); + $this->assertStringContainsString('Belegt-Meldung ist kein Nachweis', implode(' ', $observation->reasons)); + + $this->actingAs(User::factory()->create()); + Livewire::test(ViewPortalOccupation::class, ['record' => $this->fewo->blockedPeriods()->sole()->id]) + ->callAction('clarify', ['answer' => 'booking']) + ->assertRedirect(); + + $this->assertSame(IntakeKind::Booking, Booking::query()->sole()->intake); + } + + public function test_entries_that_are_no_booking_of_this_portal_never_become_cases(): void + { + $other = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'case_intake' => CaseIntakeMode::Create, 'settings' => ['import_url' => 'https://portal.example/other.ics']]); + $other->forceFill(['ical_active_rules' => [[...self::reservationRule(), 'origin' => 'channel:'.$this->fewo->id]]])->save(); + + // Reservation booked at another portal, shown in this calendar. + $this->sync($other, self::feed('evt-5', 'Reservation: Nora Beispiel', '', '20261207', '20261214')); + // A reservation overlapping a case without being the same booking. + app(TakeOverExternalBooking::class)->handle($this->property, $this->fewo, CarbonImmutable::parse('2027-01-10'), CarbonImmutable::parse('2027-01-17')); + $this->sync($this->fewo, self::feed('evt-6', 'Reservation: Max Muster', 'Buchung HA-BBBBB2', '20270112', '20270119')); + + $this->assertSame(1, Booking::query()->count()); + $this->assertTrue($this->fewo->blockedPeriods()->where('external_uid', 'evt-6')->sole()->needs_review); + $this->assertSame(0, IntakeObservation::query()->where('outcome', IntakeOutcome::Create)->count()); + } + + /** 4.4 */ + public function test_a_cancellation_mail_reaches_the_case_as_a_task_and_cancels_nothing(): void + { + $this->mail('Neue Buchung', self::BOOKING_MAIL); + $case = Booking::query()->sole(); + + $this->mail('Buchung storniert: HA-7X3K9Q', 'Die Buchung vom 07.12.2026 bis 14.12.2026 wurde storniert.', 'msg-2'); + $this->mail('Buchung storniert: HA-7X3K9Q', 'Die Buchung vom 07.12.2026 bis 14.12.2026 wurde storniert.', 'msg-3'); + + $case->refresh(); + $this->assertSame(BookingStatus::Confirmed, $case->status); + $task = BookingTask::query()->where('booking_id', $case->id)->sole(); + $this->assertSame(BookingTaskKind::PortalCancellationReported, $task->kind); + $this->assertStringContainsString('FeWo-direkt meldet eine Stornierung', $task->note); + $this->assertSame(2, $case->events()->where('type', 'portal_signal')->count(), 'two different mails are two reports'); + $this->assertNotNull($this->fewo->blockedPeriods()->where('source', 'email')->first(), 'the mail entry of the case is not released'); + $this->assertSame('Das Portal meldet eine Stornierung – bitte prüfen', CaseActivities::next($case)?->label); + } + + /** 4.4 */ + public function test_a_disappeared_or_changed_calendar_entry_is_reported_once_and_nothing_is_released(): void + { + $feed = self::feed('evt-7', 'Reservation: Nora Beispiel', 'Buchung HA-CCCCC3', '20261207', '20261214'); + $this->sync($this->fewo, $feed); + $case = Booking::query()->sole(); + + $this->sync($this->fewo, self::feed('evt-7', 'Reservation: Nora Beispiel', 'Buchung HA-CCCCC3', '20261208', '20261214')); + $this->assertSame(BookingTaskKind::PortalChangeReported, BookingTask::query()->where('booking_id', $case->id)->sole()->kind); + + $empty = self::feed(); + $this->sync($this->fewo, $empty); + $this->assertSame(0, BookingTask::query()->where('kind', BookingTaskKind::PortalCancellationReported)->count(), 'one missing import is no report yet'); + $this->sync($this->fewo, $empty); + $this->sync($this->fewo, $empty); + + $this->assertSame(1, BookingTask::query()->where('kind', BookingTaskKind::PortalCancellationReported)->count()); + $this->assertSame(2, $case->events()->where('type', 'portal_signal')->count()); + $this->assertSame(BookingStatus::Confirmed, $case->fresh()->status); + $this->assertTrue(Booking::query()->occupying()->whereKey($case->id)->exists()); + } + + /** 4.5 */ + public function test_portal_blocks_state_how_far_they_are_proven(): void + { + $manual = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']); + $case = app(TakeOverExternalBooking::class)->handle($this->property, $this->fewo, CarbonImmutable::parse('2026-12-07'), CarbonImmutable::parse('2026-12-14')); + $task = ChannelTask::query()->where('channel_id', $manual->id)->sole(); + + $this->actingAs(User::factory()->create(['name' => 'Ingrid'])); + Livewire::test(ListChannelTasks::class) + ->callTableAction('done', $task, ['proof' => ChannelTaskProof::Initiated->value, 'note' => null]) + ->assertHasNoTableActionErrors(); + $this->assertStringContainsString('veranlasst', collect(CaseActivities::for($case))->firstWhere('key', 'channel_block')->detail); + + Livewire::test(ListChannelTasks::class) + ->filterTable('status', null) + ->callTableAction('prove', $task, ['proof' => ChannelTaskProof::Observed->value, 'note' => 'im Kalender rot']) + ->assertHasNoTableActionErrors(); + $task->refresh(); + $this->assertSame(ChannelTaskProof::Observed, $task->proof); + $this->assertStringContainsString('im Portal gesehen (im Kalender rot)', collect(CaseActivities::for($case))->firstWhere('key', 'channel_block')->detail); + + $task->prove(ChannelTaskProof::Initiated, 'Ingrid'); + $this->assertSame(ChannelTaskProof::Observed, $task->fresh()->proof, 'proof is never lowered'); + } + + /** 4.6 */ + public function test_observing_creates_nothing_and_reports_what_would_have_been_created(): void + { + $this->fewo->update(['case_intake' => CaseIntakeMode::Observe]); + + $this->mail('Neue Buchung', self::BOOKING_MAIL); + $this->sync($this->fewo, self::feed('evt-8', 'Reservation: Nora Beispiel', 'Buchung HA-DDDDD4', '20270110', '20270117')); + + $this->assertSame(0, Booking::query()->count()); + $this->assertSame(2, IntakeObservation::query()->where('outcome', IntakeOutcome::Create)->where('applied', false)->count()); + $this->artisan('channels:intake-report')->expectsOutputToContain('Wären entstanden (Beobachten): 2')->assertSuccessful(); + } + + public function test_a_channel_that_was_not_switched_on_behaves_as_before(): void + { + $this->fewo->update(['case_intake' => CaseIntakeMode::Off]); + + $this->mail('Neue Buchung', self::BOOKING_MAIL); + $this->sync($this->fewo, self::feed('evt-9', 'Reservation: Nora Beispiel', 'Buchung HA-EEEEE5', '20270110', '20270117')); + + $this->assertSame(0, Booking::query()->count()); + $this->assertSame(0, IntakeObservation::query()->count()); + $this->assertSame(CaseIntakeMode::Off, Channel::factory()->for($this->property)->create()->fresh()->case_intake, 'new channels start switched off'); + } + + /** 4.7 */ + public function test_a_portal_request_becomes_a_request_that_asks_for_the_missing_data(): void + { + $this->mail('Neue Buchungsanfrage von Max', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-FFFFF6"); + + $case = Booking::query()->sole(); + $this->assertSame([IntakeKind::Inquiry, CaseType::A2, BookingStatus::Reserved, 'HA-FFFFF6'], [$case->intake, $case->case_type, $case->status, $case->portal_reference]); + $this->assertNull($case->guest_id); + $this->assertNull($case->guests); + $this->assertNull($case->total); + $this->assertSame('provideContact', CaseActivities::next($case)?->action); + Mail::assertNotSent(OfferMade::class); + } + + public function test_cases_created_with_automatic_handling_still_send_no_unreleased_documents(): void + { + $this->fewo->update(['case_intake' => CaseIntakeMode::Continue]); + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]); + + $this->mail('Neue Buchung', self::BOOKING_MAIL); + $case = Booking::query()->sole(); + app(ProvideGuestContact::class)->handle($case, ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.org'], ProvideGuestContact::MANUAL); + $case->update(['total' => 90000]); + app(CaseAutomation::class)->advance($case->fresh()); + + $this->assertNull($case->fresh()->processing_mode); + Mail::assertNotSent(BookingDocumentation::class); + $this->assertSame('sendDocuments', CaseActivities::next($case->fresh())?->action); + } + + /** 4.1 */ + public function test_a_destination_solutions_booking_is_entered_by_hand_and_handled_by_us(): void + { + $ds = Channel::factory()->for($this->property)->create(['name' => 'Destination Solutions', 'booking_model' => 'portal_booking']); + $manual = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']); + + $case = app(TakeOverExternalBooking::class)->handle($this->property, $ds, CarbonImmutable::parse('2027-02-01'), CarbonImmutable::parse('2027-02-08'), ['portal_reference' => 'DS-1', 'portal_total' => 84000, 'guests' => 2, 'guest' => ['first_name' => 'Hans', 'last_name' => 'Gast', 'email' => 'hans@example.org']]); + + $this->assertSame([CaseType::A3, BookingStatus::Confirmed, 0, 84000], [$case->case_type, $case->status, $case->offer_version, $case->total]); + $this->assertTrue($case->wantsPaymentTasks()); + $keys = array_column(array_map(fn ($activity): array => ['key' => $activity->key], CaseActivities::for($case)), 'key'); + $this->assertContains('channel_block', $keys); + $this->assertContains('deposit', $keys); + $this->assertSame(1, ChannelTask::query()->where('channel_id', $manual->id)->count()); + $this->assertSame('sendDocuments', collect(CaseActivities::for($case))->firstWhere('key', 'documents')->action); + } + + public function test_existing_portal_entries_are_adopted_by_a_command_with_preview_report_and_revert(): void + { + $this->fewo->update(['case_intake' => CaseIntakeMode::Off]); + $this->sync($this->fewo, self::feed('evt-10', 'Reservation: Nora Beispiel', 'Buchung HA-GGGGG7', '20270110', '20270117')); + $this->assertSame(0, Booking::query()->count()); + + $this->artisan('channels:adopt-occupations')->expectsOutputToContain('Vorschau – nichts geändert')->assertSuccessful(); + $this->assertSame(0, Booking::query()->count()); + + $this->artisan('channels:adopt-occupations', ['--apply' => true])->assertSuccessful(); + $case = Booking::query()->sole(); + $this->assertSame(ProcessingMode::Manual, $case->processing_mode); + $this->assertSame($case->id, $this->fewo->blockedPeriods()->sole()->linked_booking_id); + + $this->artisan('channels:adopt-occupations', ['--apply' => true])->assertSuccessful(); + $this->assertSame(1, Booking::query()->count(), 'a repeated run adopts nothing twice'); + + $report = collect(Storage::disk('local')->files('intake-adoptions'))->first(fn (string $file): bool => ! str_contains($file, 'vorschau') && str_contains(Storage::disk('local')->get($file), '"created": true')); + $this->artisan('channels:adopt-occupations', ['--revert' => $report])->expectsOutputToContain('Zurückgenommen')->assertSuccessful(); + + $this->assertSame(0, Booking::query()->count()); + $entry = $this->fewo->blockedPeriods()->sole(); + $this->assertFalse($entry->is_representation); + $this->assertNull($entry->linked_booking_id); + } + + private function mail(string $subject, string $text, string $messageId = 'msg-1'): void + { + app(ProcessPortalMail::class)->handle(new PortalMail($messageId, 'noreply@fewo-direkt.de', $subject, $text, CarbonImmutable::now())); + } + + private function sync(Channel $channel, string $feed): void + { + $this->currentFeed = $feed; + $this->assertTrue(app(SyncChannel::class)->handle($channel->fresh())->successful); + } + + private static function reservationRule(): array + { + return ['name' => 'Buchung', 'priority' => 10, 'enabled' => true, 'case_sensitive' => false, 'match' => 'all', + 'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reservation: ']], + 'event_type' => 'portal_reservation', 'origin' => 'current', 'representation' => 'leading_candidate', + 'extractions' => [ + ['field' => 'SUMMARY', 'target' => 'guest_full_name', 'method' => 'after', 'start' => 'Reservation: '], + ['field' => 'DESCRIPTION', 'target' => 'booking_reference', 'method' => 'after', 'start' => 'Buchung '], + ]]; + } + + private static function feed(?string $uid = null, string $summary = '', string $description = '', string $start = '20261207', string $end = '20261214'): string + { + $event = $uid === null ? '' : "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261102T090000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:{$summary}\r\n".($description !== '' ? "DESCRIPTION:{$description}\r\n" : '')."END:VEVENT\r\n"; + + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic//DE\r\n{$event}END:VCALENDAR\r\n"; + } +} diff --git a/tests/Feature/GuidedCaseHandlingTest.php b/tests/Feature/GuidedCaseHandlingTest.php index e5d817f..8bb6f32 100644 --- a/tests/Feature/GuidedCaseHandlingTest.php +++ b/tests/Feature/GuidedCaseHandlingTest.php @@ -159,7 +159,7 @@ public function test_the_work_list_brings_everything_to_do_into_one_list(): void $this->assertContains('Angebot prüfen und senden', $titles); $this->assertContains('In Ostsee-Portal sperren', $titles); - $this->assertContains('Unbekannte Belegung von Ostsee-Portal – was ist das?', $titles); + $this->assertContains('Belegung von Ostsee-Portal klären', $titles); $this->assertContains('Angebot nicht zugestellt', $titles); Livewire::test(WorkListWidget::class)->assertSee('In Ostsee-Portal sperren')->assertSee('Vorgang öffnen'); }