diff --git a/app/Actions/ReceiveInboundMessage.php b/app/Actions/ReceiveInboundMessage.php index 6a45e76..1a8aa41 100644 --- a/app/Actions/ReceiveInboundMessage.php +++ b/app/Actions/ReceiveInboundMessage.php @@ -11,6 +11,7 @@ use App\Process\CaseLog; use App\Support\Settings; use Illuminate\Database\UniqueConstraintViolationException; +use Throwable; /** * The inbox of v0.11 (S2/S3, CH-01, CH-06, CH-08): every message of the landlord's dedicated mailbox is stored first, @@ -79,8 +80,22 @@ public function handle(PortalMail $mail, ?Mailbox $mailbox = null): InboundMessa CaseLog::record($booking, 'mail_in', 'E-Mail des Gastes eingegangen'.($message->test_mode ? ' (im Testbetrieb)' : '').': '.$message->subject, actor: CaseLog::GUEST, at: $message->received_at); $this->requests->replyReceived($booking); BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – im Posteingang ansehen; erkannte Angaben werden dort zur Übernahme vorgeschlagen.']); + // Evaluate at once instead of waiting for the next five-minute run (the run remains the safety net). + $this->evaluate($message); - return $message; + return $message->refresh(); + } + + /** + * Runs the extraction for a freshly assigned message; a problem never undoes the assignment. + */ + public function evaluate(InboundMessage $message): void + { + try { + app(ExtractMessageFacts::class)->handle($message->refresh()); + } catch (Throwable $exception) { + report($exception); + } } /** diff --git a/app/Communication/MessageMatcher.php b/app/Communication/MessageMatcher.php index de06401..82de219 100644 --- a/app/Communication/MessageMatcher.php +++ b/app/Communication/MessageMatcher.php @@ -7,6 +7,7 @@ use App\Models\BookingMessage; use App\Models\InboundMessage; use App\Models\Property; +use App\Support\Settings; use Carbon\CarbonImmutable; /** @@ -30,7 +31,9 @@ public function match(InboundMessage $message): array $sender = mb_strtolower(trim((string) $message->from_address)); $text = $message->subject."\n".$message->body; - $references = array_values(array_filter([$message->in_reply_to, ...((array) $message->references)])); + // Message-IDs are compared with and without angle brackets (mail servers deliver both forms). + $references = collect([$message->in_reply_to, ...((array) $message->references)])->filter() + ->flatMap(fn (string $id): array => ['<'.trim($id, '<> ').'>', trim($id, '<> ')])->unique()->values()->all(); if ($references !== []) { $replied = BookingMessage::query()->whereIn('message_id', $references)->whereNotNull('booking_id')->latest('id')->first()?->booking; if ($replied !== null) { @@ -39,8 +42,13 @@ public function match(InboundMessage $message): array } $hints = []; + // In test operation every answer comes from the test mailbox: there it stands for the guest of the named case. + $testSender = $message->test_mode && $sender !== '' && $sender === mb_strtolower(trim((string) Settings::tenant()?->test_recipient)); if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $text, $numbers)) { foreach (Booking::query()->whereIn('reference', array_unique($numbers[1]))->with('guest')->get() as $booking) { + if ($testSender) { + return ['booking' => $booking, 'reason' => 'reference_test_sender', 'hints' => []]; + } if ($sender !== '' && mb_strtolower((string) $booking->guest?->email) === $sender) { return ['booking' => $booking, 'reason' => 'reference_and_sender', 'hints' => []]; } diff --git a/app/Filament/Resources/InboundMessages/InboundMessageResource.php b/app/Filament/Resources/InboundMessages/InboundMessageResource.php index b09e997..060edbb 100644 --- a/app/Filament/Resources/InboundMessages/InboundMessageResource.php +++ b/app/Filament/Resources/InboundMessages/InboundMessageResource.php @@ -4,6 +4,7 @@ use App\Actions\ContributeCaseFacts; use App\Actions\CreateReservation; +use App\Actions\ReceiveInboundMessage; use App\Actions\RequestCaseData; use App\Enums\BookingStatus; use App\Enums\BookingTaskKind; @@ -137,7 +138,15 @@ public static function table(Table $table): Table CaseLog::record($booking, 'mail_in', 'E-Mail von Ihnen zugeordnet: '.$record->subject); $requests->replyReceived($booking); BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$record->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $record->subject, 0, 120).'“ – im Posteingang ansehen.']); - Notification::make()->title('Zugeordnet')->success()->send(); + app(ReceiveInboundMessage::class)->evaluate($record); + Notification::make()->title('Zugeordnet')->body(self::evaluationSummary($record->fresh()))->success()->send(); + }), + Action::make('evaluateAgain')->label('Erneut auswerten')->icon(Heroicon::OutlinedArrowPath)->color('gray') + ->visible(fn (InboundMessage $record): bool => $record->booking_id !== null && in_array($record->extraction_status, ['failed', 'disabled'], true)) + ->action(function (InboundMessage $record): void { + $record->update(['extraction_status' => null]); + app(ReceiveInboundMessage::class)->evaluate($record); + Notification::make()->title('Ausgewertet')->body(self::evaluationSummary($record->fresh()))->send(); }), Action::make('createInquiry')->label('Als neue Anfrage anlegen')->icon(Heroicon::OutlinedPlus) ->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW) @@ -204,6 +213,22 @@ public static function table(Table $table): Table ]); } + /** + * What the evaluation of a message did, in one sentence. + */ + public static function evaluationSummary(InboundMessage $message): string + { + $applied = collect((array) ($message->extraction['applied'] ?? []))->map(fn (array $fact): string => CaseRequirements::label($fact['field']))->implode(', '); + $proposed = count((array) ($message->extraction['proposed'] ?? [])); + + return match ($message->extraction_status) { + 'done' => ($applied !== '' ? 'Übernommen: '.$applied.'.' : 'Keine Angaben automatisch übernommen.').($proposed > 0 ? ' '.$proposed.' Vorschlag/Vorschläge zu prüfen.' : ''), + 'disabled' => 'Keine automatische Auswertung (System › KI-Anbindung nicht eingerichtet oder abgelehnt).', + 'failed' => 'Die automatische Auswertung war nicht möglich: '.($message->extraction['error'] ?? 'unbekannter Fehler'), + default => 'Wird ausgewertet.', + }; + } + /** * Cases to assign a message to: the hints first, then the open cases. * diff --git a/tests/Feature/GuestMailInboxTest.php b/tests/Feature/GuestMailInboxTest.php index d46c7bf..27a2993 100644 --- a/tests/Feature/GuestMailInboxTest.php +++ b/tests/Feature/GuestMailInboxTest.php @@ -187,6 +187,21 @@ public function test_the_mailbox_is_kept_as_a_record_and_full_mode_reads_every_m $this->assertNotNull($mailbox->fresh()->last_fetched_at); } + /** Test operation: every answer comes from the test mailbox, which then stands for the guest of the named case. */ + public function test_in_test_operation_the_test_address_counts_as_the_guest_of_the_named_case(): void + { + Settings::tenant()->update(['test_recipient' => 'test@example.org']); + $booking = $this->request(); + + $message = $this->receive(from: 'test@example.org', subject: 'Re: Ihre Anfrage '.$booking->reference, text: 'Strandweg 1'); + + $this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'reference_test_sender'], [$message->status, $message->booking_id, $message->match_reason]); + + Settings::tenant()->update(['operating_mode' => 'live']); + $live = $this->receive(from: 'test@example.org', subject: 'Re: Ihre Anfrage '.$booking->reference, text: 'Strandweg 1', id: ''); + $this->assertSame(InboundMessage::NEEDS_REVIEW, $live->status, 'in live operation the test address is nobody special'); + } + public function test_the_mailbox_can_be_checked_and_incoming_mails_show_on_the_case(): void { $this->actingAs(User::factory()->create()); diff --git a/tests/Feature/MessageExtractionTest.php b/tests/Feature/MessageExtractionTest.php index c09fbbc..fb2266e 100644 --- a/tests/Feature/MessageExtractionTest.php +++ b/tests/Feature/MessageExtractionTest.php @@ -65,6 +65,7 @@ protected function setUp(): void TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'test-key', 'settings' => ['provider' => 'anthropic', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5']]); app(TenantFeatures::class)->forget(); + Http::preventStrayRequests(); } public function test_without_the_service_nothing_is_sent_to_a_provider(): void diff --git a/tests/Feature/V011EndToEndTest.php b/tests/Feature/V011EndToEndTest.php index f8caec2..90053b0 100644 --- a/tests/Feature/V011EndToEndTest.php +++ b/tests/Feature/V011EndToEndTest.php @@ -68,6 +68,7 @@ protected function setUp(): void TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'sk-or-test', 'settings' => ['provider' => 'openrouter', 'small_model' => 'vendor/small-model', 'review_model' => 'vendor/large-model']]); app(TenantFeatures::class)->forget(); + Http::preventStrayRequests(); } public function test_from_an_incomplete_website_request_to_the_binding_booking(): void @@ -87,8 +88,14 @@ public function test_from_an_incomplete_website_request_to_the_binding_booking() $question = BookingMessage::query()->where('booking_id', $booking->id)->where('subject', 'like', '%Bitte ergänzen%')->sole(); $this->assertSame('test', $question->audience, 'test operation: not delivered to the guest'); + // The provider of the landlord's own AI access (faked; no network). + $this->fakeExtraction([ + ['field' => 'guest.street', 'value' => 'Lindenallee 12', 'evidence' => 'Lindenallee 12', 'confidence' => 0.97], + ['field' => 'guest.postal_code', 'value' => '10115', 'evidence' => '10115 Berlin', 'confidence' => 0.97], + ['field' => 'guest.city', 'value' => 'Berlin', 'evidence' => '10115 Berlin', 'confidence' => 0.97], + ]); // 3. The guest answers by e-mail; the inbox reads it, assigns it by the reply reference and stores it once. - $reply = new PortalMail('', 'test@example.org', 'Re: '.$question->subject, "Hallo,\nunsere Anschrift: Lindenallee 12, 10115 Berlin, Deutschland.\nGesa", CarbonImmutable::now(), inReplyTo: $question->message_id); + $reply = new PortalMail('', 'test@example.org', 'Re: '.$question->subject, "Hallo,\nunsere Anschrift: Lindenallee 12, 10115 Berlin, Deutschland.\nGesa", CarbonImmutable::now(), inReplyTo: trim((string) $question->message_id, '<>')); $reader = Mockery::mock(MailboxReader::class); $reader->shouldReceive('fetchAll')->andReturn([$reply]); $this->app->instance(MailboxReader::class, $reader); @@ -96,15 +103,11 @@ public function test_from_an_incomplete_website_request_to_the_binding_booking() $this->artisan('channels:fetch-mail')->assertSuccessful(); $message = InboundMessage::query()->sole(); - $this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'reply', true], [$message->status, $message->booking_id, $message->match_reason, $message->test_mode]); + // The server delivers the reference without angle brackets; it is assigned anyway, and evaluated at once. + $this->assertSame([InboundMessage::PROCESSED, $booking->id, 'reply', true], [$message->status, $message->booking_id, $message->match_reason, $message->test_mode]); $this->assertNull($request->fresh()->next_reminder_at, 'the answer stops the reminder'); - // 4. Extraction (faked provider) → rules → fact intake → the existing process sends the offer. - $this->fakeExtraction([ - ['field' => 'guest.street', 'value' => 'Lindenallee 12', 'evidence' => 'Lindenallee 12', 'confidence' => 0.97], - ['field' => 'guest.postal_code', 'value' => '10115', 'evidence' => '10115 Berlin', 'confidence' => 0.97], - ['field' => 'guest.city', 'value' => 'Berlin', 'evidence' => '10115 Berlin', 'confidence' => 0.97], - ]); + // 4. The inbox evaluated the reply at once (extraction → rules → fact intake); the five-minute run finds nothing left. $this->artisan('messages:extract')->assertSuccessful(); $booking->refresh();