diff --git a/app/Channels/Mail/MailboxReader.php b/app/Channels/Mail/MailboxReader.php index d681c02..e7988d8 100644 --- a/app/Channels/Mail/MailboxReader.php +++ b/app/Channels/Mail/MailboxReader.php @@ -140,6 +140,33 @@ public function fetchAll(): array return $mails; } + /** + * Connects with the given connection data and counts the messages of the last days (check on System › Betrieb). + * Nothing is read, marked or stored. + * + * @param array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string} $config + * + * @throws ChannelSyncException + */ + public function probe(array $config): int + { + try { + $client = (new ClientManager)->make([ + 'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true, + 'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap', + ]); + $client->connect(); + $count = $client->getFolderByPath($config['folder'])->query() + ->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3))) + ->leaveUnread()->setFetchBody(false)->count(); + $client->disconnect(); + } catch (Throwable $exception) { + throw new ChannelSyncException('Postfach nicht erreichbar: '.$exception->getMessage(), previous: $exception); + } + + return (int) $count; + } + private function toPortalMail(Message $message): PortalMail { $text = $message->getTextBody(); diff --git a/app/Filament/Pages/Operations.php b/app/Filament/Pages/Operations.php index 57a300b..99f30cb 100644 --- a/app/Filament/Pages/Operations.php +++ b/app/Filament/Pages/Operations.php @@ -3,6 +3,8 @@ namespace App\Filament\Pages; use App\Actions\SendDigests; +use App\Channels\ChannelSyncException; +use App\Channels\Mail\MailboxReader; use App\Enums\DigestSection; use App\Enums\TenantServiceKey; use App\Enums\UserRole; @@ -13,6 +15,7 @@ use App\Tenancy\TenantConfig; use App\Tenancy\TenantFeatures; use BackedEnum; +use Carbon\CarbonImmutable; use Filament\Actions\Action; use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\Radio; @@ -30,6 +33,7 @@ use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; +use Illuminate\Support\Facades\Cache; use UnitEnum; /** @@ -258,6 +262,11 @@ public function form(Schema $schema): Schema ->helperText('„Alle Nachrichten“ nur für ein Postfach, das ausschließlich für Anfragen und Gästeantworten dient: Antworten und Gast-Mails werden dann den Vorgängen zugeordnet oder im Posteingang zur Klärung gezeigt.'), TextInput::make('mailbox_address')->label('Adresse dieses Postfachs (für Antworten der Gäste)')->email()->maxLength(190) ->helperText('Rückfragen nennen diese Adresse als Antwortadresse, damit die Antwort hier ankommt.'), + Text::make(fn (): string => $this->mailboxState())->columnSpanFull(), + Actions::make([ + Action::make('checkMailbox')->label('Postfach prüfen')->icon(Heroicon::OutlinedSignal)->color('gray') + ->action(fn () => $this->checkMailbox()), + ])->columnSpanFull(), ]), Section::make('Fristen und Grenzen') ->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.') @@ -300,6 +309,47 @@ protected function getHeaderActions(): array ]; } + /** + * Connects to the saved mailbox and counts the messages of the last days; nothing is read or marked. + */ + public function checkMailbox(): void + { + $connection = $this->tenant()->mailbox(); + if ($connection === null) { + Notification::make()->title('Kein Postfach gespeichert')->body('Bitte Server und Benutzer eintragen und speichern.')->warning()->send(); + + return; + } + + try { + $count = app(MailboxReader::class)->probe($connection); + } catch (ChannelSyncException $exception) { + Notification::make()->title('Postfach nicht erreichbar')->body($exception->getMessage())->danger()->persistent()->send(); + + return; + } + + Notification::make()->title('Verbindung in Ordnung')->body($count.' Nachricht(en) der letzten '.config('fewo.mailbox.lookback_days', 3).' Tage im Ordner „'.$connection['folder'].'“.')->success()->send(); + } + + /** + * When the mailbox was last read and whether the last attempt failed. + */ + private function mailboxState(): string + { + $mailbox = $this->tenant()->activeMailbox(); + if ($mailbox === null || blank($mailbox->host)) { + return 'Kein Postfach eingerichtet.'; + } + + $error = Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY)); + $success = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY)); + + return 'Abruf jede Minute. Zuletzt erfolgreich gelesen: '.($success ? CarbonImmutable::parse($success)->format('d.m.Y, H:i').' Uhr' : 'noch nie') + .($error ? ' · Letzter Fehler: '.mb_substr((string) $error, 0, 200) : '') + .($mailbox->readsEverything() ? ' · Eingegangene Nachrichten stehen unter Verwaltung › Posteingang.' : ' · Gelesen werden nur Buchungsmails der Portale.'); + } + public function save(): void { $data = $this->form->getState(); diff --git a/app/Filament/Resources/Bookings/BookingResource.php b/app/Filament/Resources/Bookings/BookingResource.php index ba7842c..d7eeda9 100644 --- a/app/Filament/Resources/Bookings/BookingResource.php +++ b/app/Filament/Resources/Bookings/BookingResource.php @@ -8,6 +8,7 @@ use App\Filament\Resources\Bookings\Pages\CreateBooking; use App\Filament\Resources\Bookings\Pages\ListBookings; use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Filament\Resources\Bookings\RelationManagers\InboundMessagesRelationManager; use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager; use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager; use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager; @@ -76,6 +77,7 @@ public static function getRelations(): array PaymentsRelationManager::class, TasksRelationManager::class, MessagesRelationManager::class, + InboundMessagesRelationManager::class, ]; } diff --git a/app/Filament/Resources/Bookings/RelationManagers/InboundMessagesRelationManager.php b/app/Filament/Resources/Bookings/RelationManagers/InboundMessagesRelationManager.php new file mode 100644 index 0000000..462aa17 --- /dev/null +++ b/app/Filament/Resources/Bookings/RelationManagers/InboundMessagesRelationManager.php @@ -0,0 +1,60 @@ +recordTitleAttribute('subject') + ->defaultSort('received_at', 'desc') + ->emptyStateHeading('Noch keine eingegangenen E-Mails zu diesem Vorgang') + ->description('Antworten und Nachrichten aus dem Postfach für die Gästekommunikation, die diesem Vorgang zugeordnet sind. Nicht zugeordnete Nachrichten stehen unter Verwaltung › Posteingang.') + ->columns([ + TextColumn::make('received_at')->label('Eingang')->dateTime('d.m.Y, H:i'), + TextColumn::make('from_address')->label('Von')->description(fn (InboundMessage $record): ?string => $record->from_name), + TextColumn::make('subject')->label('Betreff')->wrap(), + TextColumn::make('extraction_status')->label('Auswertung')->badge()->formatStateUsing(fn (?string $state): string => match ($state) { + 'done' => 'ausgewertet', + 'failed' => 'nicht möglich', + 'disabled' => 'ohne KI', + default => 'ausstehend', + }), + IconColumn::make('test_mode')->label('Testbetrieb')->boolean()->trueIcon(Heroicon::OutlinedBeaker)->falseIcon(null), + ]) + ->recordActions([ + Action::make('read')->label('Lesen')->icon(Heroicon::OutlinedEye) + ->modalHeading(fn (InboundMessage $record): string => (string) $record->subject) + ->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->modalWidth('3xl') + ->schema([ + TextEntry::make('found')->label('Erkannt')->state(fn (InboundMessage $record): string => collect([...(array) ($record->extraction['applied'] ?? []), ...(array) ($record->extraction['proposed'] ?? [])]) + ->map(fn (array $fact): string => $fact['field'].': „'.$fact['value'].'“')->implode(' · ') ?: '–'), + TextEntry::make('body_text')->label('Nachricht')->state(fn (InboundMessage $record): HtmlString => new HtmlString(nl2br(e((string) $record->body)))), + ]), + ]); + } +} diff --git a/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php b/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php index e73c46b..7bde9d5 100644 --- a/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php +++ b/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php @@ -13,7 +13,7 @@ class MessagesRelationManager extends RelationManager { protected static string $relationship = 'messages'; - protected static ?string $title = 'Mailverlauf'; + protected static ?string $title = 'Gesendete E-Mails'; public function isReadOnly(): bool { diff --git a/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php b/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php index b564c4c..8407141 100644 --- a/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php +++ b/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php @@ -2,8 +2,12 @@ namespace App\Filament\Resources\InboundMessages\Pages; +use App\Channels\Mail\MailboxReader; use App\Filament\Resources\InboundMessages\InboundMessageResource; +use App\Support\Settings; +use Carbon\CarbonImmutable; use Filament\Resources\Pages\ListRecords; +use Illuminate\Support\Facades\Cache; class ListInboundMessages extends ListRecords { @@ -11,6 +15,14 @@ class ListInboundMessages extends ListRecords public function getSubheading(): ?string { - return 'Nachrichten aus Ihrem Postfach für die Gästekommunikation. Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.'; + $mailbox = Settings::tenant()?->activeMailbox(); + $state = match (true) { + $mailbox === null || blank($mailbox->host) => 'Kein Postfach eingerichtet (System › Betrieb).', + ! $mailbox->readsEverything() => 'Das Postfach liest nur Buchungsmails der Portale; für Gast-Mails „Alle Nachrichten“ wählen (System › Betrieb).', + default => 'Abruf jede Minute, zuletzt erfolgreich: '.(($success = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY))) ? CarbonImmutable::parse($success)->format('d.m.Y, H:i').' Uhr' : 'noch nie') + .(($error = Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))) ? ' · Letzter Fehler: '.mb_substr((string) $error, 0, 160) : '').'.', + }; + + return $state.' Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.'; } } diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 84b324a..0612ed7 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -519,6 +519,12 @@ public function canBeArchived(): bool || ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true)); } + /** @return HasMany */ + public function inboundMessages(): HasMany + { + return $this->hasMany(InboundMessage::class); + } + /** @return HasMany */ public function dataRequests(): HasMany { diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index b5ba303..d842187 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -125,11 +125,20 @@ public static function for(Booking $booking): array }); } elseif ($inquiry) { $offerDone = $booking->offer_version > 0 || $binding; + // G2a (v0.11): without every required detail there is no offer – the step waits for the guest's answer + // (mail, link or the landlord's entry) instead of being offered as the next step. + $offerMissing = $offerDone ? [] : CaseRequirements::missing($booking, CaseRequirements::OFFER); $activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) { $offerDone => ActivityState::Done, + $offerMissing !== [] => ActivityState::Later, $booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open, default => ActivityState::Later, - }), $booking->offer_version > 0 ? 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y') : ($booking->hold_expires_at ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : null), $offerDone ? null : 'sendOffer'); + }), match (true) { + $booking->offer_version > 0 => 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y'), + $offerMissing !== [] => 'erst wenn alle Angaben da sind', + $booking->hold_expires_at !== null => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr', + default => null, + }, $offerDone || $offerMissing !== [] ? null : 'sendOffer'); $activities[] = new Activity('acceptance', 'Gast nimmt das Angebot an', $later(match (true) { $binding => ActivityState::Done, @@ -356,6 +365,8 @@ private static function task(BookingTask $task): Activity $task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting, $task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later, $task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem, + // v0.11 (B3): the binding confirmation waits for the missing details as well. + $task->kind === BookingTaskKind::BookingWish && $task->booking !== null && CaseRequirements::missing($task->booking, CaseRequirements::WISH_CONFIRMATION) !== [] => ActivityState::Waiting, default => ActivityState::Open, }; $detail = $task->status === BookingTaskStatus::Done diff --git a/tests/Feature/DataRequestTest.php b/tests/Feature/DataRequestTest.php index ea8f570..64c74e5 100644 --- a/tests/Feature/DataRequestTest.php +++ b/tests/Feature/DataRequestTest.php @@ -84,6 +84,23 @@ public function test_approval_mode_prepares_the_question_and_the_landlord_releas $this->assertSame(DataRequest::OPEN, $request->fresh()->status); } + /** G2a: while the guest is asked, the offer is not offered as the next step – neither by hand nor automatically. */ + public function test_the_offer_waits_for_the_answer_even_when_the_steps_are_released_by_hand(): void + { + Settings::tenant()->update(['process_defaults' => ['processing' => 'manual', 'data_request_mode' => 'automatic']]); + + $booking = $this->request(); + + $this->assertSame(DataRequest::OPEN, $booking->openDataRequest()->status); + $this->assertNotSame('sendOffer', CaseActivities::next($booking)?->action); + $offer = collect(CaseActivities::for($booking))->firstWhere('key', 'offer'); + $this->assertSame(['erst wenn alle Angaben da sind', null], [$offer->detail, $offer->action]); + + app(ContributeCaseFacts::class)->handle($booking, ['guest.street' => 'Strandweg 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], FactSource::GuestLink, ['reference' => 'link']); + $this->assertSame('sendOffer', CaseActivities::next($booking->fresh())?->action, 'complete: now the landlord releases the offer'); + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status, 'manual processing: nothing sent by itself'); + } + public function test_manual_mode_leaves_the_question_to_the_landlord(): void { Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'manual']]); diff --git a/tests/Feature/GuestMailInboxTest.php b/tests/Feature/GuestMailInboxTest.php index c5321ce..d3c89c7 100644 --- a/tests/Feature/GuestMailInboxTest.php +++ b/tests/Feature/GuestMailInboxTest.php @@ -8,6 +8,8 @@ use App\Channels\Mail\PortalMail; use App\Enums\BookingTaskKind; use App\Filament\Pages\Operations; +use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Filament\Resources\Bookings\RelationManagers\InboundMessagesRelationManager; use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages; use App\Mail\DataRequested; use App\Models\Booking; @@ -182,6 +184,22 @@ public function test_the_mailbox_is_kept_as_a_record_and_full_mode_reads_every_m $this->assertNotNull($mailbox->fresh()->last_fetched_at); } + public function test_the_mailbox_can_be_checked_and_incoming_mails_show_on_the_case(): void + { + $this->actingAs(User::factory()->create()); + Mailbox::query()->create(['tenant_id' => Settings::tenant()->id, 'host' => 'imap.example.org', 'username' => 'anfragen@example.org', 'password' => 'x', 'mode' => Mailbox::FULL, 'is_active' => true]); + $reader = Mockery::mock(MailboxReader::class); + $reader->shouldReceive('probe')->once()->andReturn(7); + $this->app->instance(MailboxReader::class, $reader); + + Livewire::test(Operations::class)->call('checkMailbox')->assertNotified('Verbindung in Ordnung'); + + $booking = $this->request(); + $this->receive(from: 'gesa@example.org', subject: 'Frage zu '.$booking->reference, text: 'Hallo'); + Livewire::test(InboundMessagesRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class]) + ->assertSee('Frage zu '.$booking->reference); + } + private function request(string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking { return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'])->fresh();