Files
fewo-stommer/tests/Feature/V011EndToEndTest.php
LarsandClaude Opus 5.5 ad63db78f3
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m6s
Posteingang: Antwortbezug ohne Klammern, Testadresse im Testbetrieb, sofortige Auswertung
- Antwortbezug (In-Reply-To/References) wird mit und ohne spitze Klammern
  verglichen – Strato liefert ihn ohne, gespeichert war er mit; Antworten
  blieben deshalb im Posteingang hängen.
- Testbetrieb: Die Testadresse steht zusammen mit der genannten
  Vorgangsnummer für den Gast dieses Vorgangs (alle Antworten kommen vom
  Testpostfach). Im Live-Betrieb gilt das nicht.
- Eine zugeordnete Nachricht wird sofort ausgewertet (automatisch und nach
  Zuordnung von Hand), nicht erst im Fünf-Minuten-Lauf; die Meldung nennt,
  was übernommen wurde. Neu: „Erneut auswerten“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:39:11 +01:00

153 lines
8.7 KiB
PHP

<?php
namespace Tests\Feature;
use App\Actions\TakeOverExternalBooking;
use App\Channels\Mail\MailboxReader;
use App\Channels\Mail\PortalMail;
use App\Enums\BookingStatus;
use App\Enums\TenantServiceKey;
use App\Livewire\BookingRequest;
use App\Models\Booking;
use App\Models\BookingMessage;
use App\Models\CaseFact;
use App\Models\Channel;
use App\Models\DataRequest;
use App\Models\InboundMessage;
use App\Models\Mailbox;
use App\Models\Property;
use App\Models\TenantService;
use App\Support\Content;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;
use Mockery;
use Tests\TestCase;
/**
* v0.11 integrated MVP, end to end with every component in place (only the IMAP server and the model provider are
* replaced): website request without address → clarification hold → data request mail → the guest answers by e-mail
* → the inbox assigns the reply by its reference → extraction → common fact intake → the existing process sends the
* offer with the unchanged offer hold → the guest accepts → binding booking. A binding portal booking keeps its
* binding throughout.
*/
class V011EndToEndTest extends TestCase
{
use RefreshDatabase;
private Property $property;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Storage::fake('local');
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
config(['mail.default' => 'array', 'fewo.spam.min_seconds' => 0]);
Mail::swap(new MailManager($this->app));
Settings::tenant()->update([
'bank_iban' => 'DE02120300000000202051',
'test_recipient' => 'test@example.org',
'process_defaults' => ['processing' => 'automatic', 'data_request_mode' => 'automatic'],
]);
Mailbox::query()->create(['tenant_id' => Settings::tenant()->id, 'host' => 'imap.example.org', 'username' => 'anfragen@example.org', 'password' => 'x', 'mode' => Mailbox::FULL, 'address' => 'anfragen@example.org', 'is_active' => true]);
// Bring your own key: the landlord's own access (here OpenRouter), no operator key.
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
{
// 1. The guest asks on the website without an address.
Livewire::test(BookingRequest::class)
->call('selectDate', '2026-11-07')->call('selectDate', '2026-11-10')
->set('firstName', 'Gesa')->set('lastName', 'Gast')->set('email', 'gesa@example.org')->set('privacyAccepted', true)
->call('submit')->assertHasNoErrors();
$booking = Booking::query()->sole();
// 2. Clarification hold of the automatic mode, a data request went out (test operation: only to the test address).
$this->assertSame([BookingStatus::Reserved, Booking::HOLD_CLARIFICATION], [$booking->status, $booking->hold_purpose]);
$this->assertTrue($booking->hold_expires_at->equalTo(now()->addMinutes(15)));
$request = $booking->openDataRequest();
$this->assertSame(DataRequest::OPEN, $request->status);
$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('<antwort@gast.example>', '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);
$this->artisan('channels:fetch-mail')->assertSuccessful();
$this->artisan('channels:fetch-mail')->assertSuccessful();
$message = InboundMessage::query()->sole();
// 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. 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();
$this->assertSame('Lindenallee 12', $booking->guest->street);
$this->assertSame('DE', $booking->guest->country, 'confirmed with the website form');
$this->assertSame(3, CaseFact::query()->where('booking_id', $booking->id)->where('outcome', CaseFact::APPLIED)->where('source', 'llm')->count());
$this->assertSame([BookingStatus::OfferSent, Booking::HOLD_OFFER], [$booking->status, $booking->hold_purpose]);
$this->assertTrue($booking->hold_expires_at->equalTo(now()->addHours(48)), 'the offer hold is the unchanged one');
$this->assertSame(DataRequest::COMPLETED, $request->fresh()->status);
// 5. The guest accepts the offer → binding booking.
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1'])->assertRedirect();
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
$this->assertSame(0, BookingMessage::query()->where('audience', 'guest')->count(), 'nothing reached a guest in test operation');
}
/** E-036 / M12: a booking binding on the portal stays binding without guest data and gets no clarification. */
public function test_a_binding_portal_booking_stays_binding_and_is_only_completed(): void
{
$portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'settings' => ['email_senders' => 'fewo-direkt.de']]);
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $portal, CarbonImmutable::parse('2026-12-05'), CarbonImmutable::parse('2026-12-08'), ['portal_reference' => 'HA-7']);
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertNull($booking->guest_id);
$this->assertNull($booking->openDataRequest(), 'no way to the guest yet: nothing is sent');
$this->assertSame('none', $booking->clarificationState()['state']);
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
}
/**
* @param list<array<string, mixed>> $facts
*/
private function fakeExtraction(array $facts): void
{
Http::fake(['https://openrouter.ai/api/v1/chat/completions' => fn (Request $request) => Http::response([
'id' => 'gen', 'model' => $request->data()['model'],
'choices' => [['finish_reason' => 'stop', 'message' => ['role' => 'assistant', 'content' => json_encode(['facts' => $facts, 'change_requests' => [], 'intent' => 'answer', 'uncertainties' => []])]]],
'usage' => ['prompt_tokens' => 10, 'completion_tokens' => 10],
])]);
}
}