diff --git a/app/Communication/CommunicationRules.php b/app/Communication/CommunicationRules.php new file mode 100644 index 0000000..501e38c --- /dev/null +++ b/app/Communication/CommunicationRules.php @@ -0,0 +1,48 @@ +value}.active", false); + + return $ceiling && ($this->narrowing()['media'][$medium->value]['active'] ?? true) !== false; + } + + public function consentRequired(Medium $medium): bool + { + return (bool) config("communication.media.{$medium->value}.consent_required", false); + } + + /** + * @return list the effects the rules allow for the intent on the medium (never empty: review at least) + */ + public function effects(Medium $medium, MessageIntent $intent): array + { + /** @var list $ceiling */ + $ceiling = config('communication.effects.'.$intent->value, [MessageEffect::Review]); + $withdrawn = (array) ($this->narrowing()['effects'][$medium->value][$intent->value] ?? []); + $allowed = array_values(array_filter($ceiling, fn (MessageEffect $effect): bool => ! in_array($effect->value, $withdrawn, true))); + + return $allowed === [] ? [MessageEffect::Review] : $allowed; + } + + /** + * @return array + */ + private function narrowing(): array + { + return (array) (Settings::tenant()?->communication_rules ?? []); + } +} diff --git a/app/Communication/IncomingMessage.php b/app/Communication/IncomingMessage.php new file mode 100644 index 0000000..e280a34 --- /dev/null +++ b/app/Communication/IncomingMessage.php @@ -0,0 +1,25 @@ + (bool) preg_match('/('.implode('|', $words).')/u', $text); + + if ($assignedToCase && $has(['umbuchen', 'verschieb', 'stornieren', 'stornierung', 'später anreisen', 'früher anreisen', 'ändern'])) { + return MessageIntent::ChangeRequest; + } + if ($assignedToCase && $has(['ankunft', 'uhr', 'personen', 'kennzeichen', 'adresse', 'telefon', 'handynummer'])) { + return MessageIntent::ProvideData; + } + if ($assignedToCase) { + return MessageIntent::CaseReply; + } + if ($has(['frei', 'verfügbar', 'buchen', 'reservieren', 'anreise', 'zeitraum', 'vom \d'])) { + return MessageIntent::StayInquiry; + } + if ($has(['\?', 'hund', 'haustier', 'parkplatz', 'wlan', 'preis', 'kosten', 'wie weit', 'strand', 'ausstattung'])) { + return MessageIntent::GeneralQuestion; + } + + return MessageIntent::Unclear; + } +} diff --git a/app/Communication/MessageDecision.php b/app/Communication/MessageDecision.php new file mode 100644 index 0000000..06b4db0 --- /dev/null +++ b/app/Communication/MessageDecision.php @@ -0,0 +1,40 @@ + $effects applied effects, in order + * @param list $reasons plain-language explanation + */ + public function __construct( + public Medium $medium, + public MessageIntent $intent, + public ?Booking $booking, + public array $effects, + public array $reasons, + ) {} + + public function has(MessageEffect $effect): bool + { + return in_array($effect, $this->effects, true); + } + + /** + * @return array{medium: string, intent: string, booking_id: ?int, effects: list, reasons: list} + */ + public function toArray(): array + { + return ['medium' => $this->medium->value, 'intent' => $this->intent->value, 'booking_id' => $this->booking?->id, + 'effects' => array_map(fn (MessageEffect $effect): string => $effect->value, $this->effects), 'reasons' => $this->reasons]; + } +} diff --git a/app/Communication/MessageIntake.php b/app/Communication/MessageIntake.php new file mode 100644 index 0000000..dda4ebf --- /dev/null +++ b/app/Communication/MessageIntake.php @@ -0,0 +1,150 @@ +medium->value.':'.$incoming->externalId; + $existing = InboundMessage::query()->where('message_id', $key)->first(); + if ($existing !== null) { + return $this->fromStored($existing, $incoming); + } + + $reasons = []; + $booking = $this->assignedCase($incoming, $reasons); + $intent = $this->classifier->classify($incoming->text, $booking !== null); + $effects = $this->effectsFor($incoming, $intent, $booking, $reasons); + $decision = new MessageDecision($incoming->medium, $intent, $booking, $effects, $reasons); + + try { + $message = InboundMessage::query()->create([ + 'message_id' => $key, + 'medium' => $incoming->medium->value, + 'from_address' => mb_substr($incoming->sender, 0, 255), + 'from_name' => $incoming->senderName, + 'subject' => mb_substr(strtok($incoming->text, "\n") ?: '', 0, 120), + 'body' => $incoming->text, + 'received_at' => $incoming->receivedAt, + 'test_mode' => ! Settings::isLive(), + 'status' => $booking !== null && ! $decision->has(MessageEffect::Review) ? InboundMessage::ASSIGNED : InboundMessage::NEEDS_REVIEW, + 'booking_id' => $booking?->id, + 'match_reason' => $booking !== null ? 'verified_reference' : null, + 'intent' => $intent->value, + 'decision' => $decision->toArray(), + ]); + } catch (UniqueConstraintViolationException) { + return $this->fromStored(InboundMessage::query()->where('message_id', $key)->firstOrFail(), $incoming); + } + + $this->apply($message, $decision); + + return $decision; + } + + /** + * @param list $reasons + */ + private function assignedCase(IncomingMessage $incoming, array &$reasons): ?Booking + { + if ($incoming->verifiedBookingId === null) { + $reasons[] = 'Kein überprüfter Bezug zu einem Vorgang – Absender, Rufnummer, Name oder Zeitraum allein ordnen nicht zu.'; + + return null; + } + $booking = Booking::query()->find($incoming->verifiedBookingId); + if ($booking === null) { + $reasons[] = 'Der überprüfte Bezug verweist auf keinen Vorgang dieses Vermieters.'; + + return null; + } + if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $incoming->text, $numbers) && array_diff($numbers[1], [$booking->reference]) !== []) { + $reasons[] = 'Die Nachricht nennt eine andere Vorgangsnummer als der überprüfte Bezug – widersprüchlich.'; + + return null; + } + $reasons[] = 'Dem Vorgang '.$booking->reference.' zugeordnet (überprüfter Bezug).'; + + return $booking; + } + + /** + * @param list $reasons + * @return list + */ + private function effectsFor(IncomingMessage $incoming, MessageIntent $intent, ?Booking $booking, array &$reasons): array + { + if (! $this->rules->mediumActive($incoming->medium)) { + $reasons[] = $incoming->medium->getLabel().' ist für diesen Vermieter nicht eingeschaltet – die Nachricht liegt zur Klärung vor.'; + + return [MessageEffect::Review]; + } + if ($this->rules->consentRequired($incoming->medium) && ! $incoming->consentGiven) { + $reasons[] = 'Für '.$incoming->medium->getLabel().' liegt keine Einwilligung vor – nur Klärung durch den Vermieter.'; + + return [MessageEffect::Review]; + } + + $effects = array_values(array_filter( + $this->rules->effects($incoming->medium, $intent), + fn (MessageEffect $effect): bool => ! $effect->needsCase() || $booking !== null, + )); + // The review fallback only stands alone: where a real effect applies it is not added. + $real = array_values(array_filter($effects, fn (MessageEffect $effect): bool => $effect !== MessageEffect::Review)); + if ($real === [] || $intent === MessageIntent::Unclear) { + $reasons[] = 'Nicht eindeutig oder nicht zulässig – zur Klärung vorgelegt, nichts wird übernommen.'; + + return [MessageEffect::Review]; + } + + return $real; + } + + private function apply(InboundMessage $message, MessageDecision $decision): void + { + $booking = $decision->booking; + if ($booking === null || $decision->has(MessageEffect::Review)) { + return; + } + CaseLog::record($booking, 'message_in', $decision->medium->getLabel().'-Nachricht eingegangen ('.$decision->intent->getLabel().')', actor: CaseLog::GUEST, at: $message->received_at); + if ($decision->has(MessageEffect::ReportToCase) || $decision->has(MessageEffect::ContributeFacts)) { + BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => $decision->medium->getLabel().'-Nachricht („'.mb_substr((string) $message->subject, 0, 100).'“) – im Posteingang ansehen; es wird nichts automatisch übernommen.']); + } + if ($decision->has(MessageEffect::ContributeFacts)) { + app(ReceiveInboundMessage::class)->evaluate($message); + } + } + + private function fromStored(InboundMessage $stored, IncomingMessage $incoming): MessageDecision + { + $data = (array) $stored->decision; + + return new MessageDecision( + $incoming->medium, + MessageIntent::tryFrom((string) $stored->intent) ?? MessageIntent::Unclear, + $stored->booking, + array_values(array_filter(array_map(fn (string $effect): ?MessageEffect => MessageEffect::tryFrom($effect), (array) ($data['effects'] ?? [])))), + (array) ($data['reasons'] ?? []), + ); + } +} diff --git a/app/Enums/Medium.php b/app/Enums/Medium.php new file mode 100644 index 0000000..cf1b45c --- /dev/null +++ b/app/Enums/Medium.php @@ -0,0 +1,27 @@ + 'E-Mail', + self::Form => 'Formular', + self::WhatsApp => 'WhatsApp', + self::Chat => 'Chat', + }; + } +} diff --git a/app/Enums/MessageEffect.php b/app/Enums/MessageEffect.php new file mode 100644 index 0000000..d9c6c91 --- /dev/null +++ b/app/Enums/MessageEffect.php @@ -0,0 +1,34 @@ + 'allgemeine Auskunft geben', + self::ContributeFacts => 'Angaben für den Vorgang vorschlagen', + self::ReportToCase => 'Aufgabe am Vorgang anlegen', + self::HandoffInquiry => 'auf den Anfrageweg verweisen', + self::Review => 'zur Klärung vorlegen', + }; + } + + /** Effects that act on an existing case and therefore need a verified assignment. */ + public function needsCase(): bool + { + return $this === self::ContributeFacts || $this === self::ReportToCase; + } +} diff --git a/app/Enums/MessageIntent.php b/app/Enums/MessageIntent.php new file mode 100644 index 0000000..8d40d03 --- /dev/null +++ b/app/Enums/MessageIntent.php @@ -0,0 +1,31 @@ + 'allgemeine Frage', + self::StayInquiry => 'Anfrage zu einem Aufenthalt', + self::CaseReply => 'Antwort in einem Vorgang', + self::ProvideData => 'Angaben zu einem Vorgang', + self::ChangeRequest => 'Änderungswunsch', + self::Unclear => 'unklar', + }; + } +} diff --git a/app/Models/InboundMessage.php b/app/Models/InboundMessage.php index fd2833b..285b85f 100644 --- a/app/Models/InboundMessage.php +++ b/app/Models/InboundMessage.php @@ -12,7 +12,7 @@ * to a case only by a reliable reference (CH-13); otherwise it waits in the inbox for the landlord. Being assigned is * not yet permission to take anything over. */ -#[Fillable(['mailbox_id', 'message_id', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])] +#[Fillable(['mailbox_id', 'message_id', 'medium', 'intent', 'decision', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])] class InboundMessage extends Model { use BelongsToTenant; @@ -44,6 +44,7 @@ protected function casts(): array 'to_addresses' => 'array', 'hints' => 'array', 'extraction' => 'array', + 'decision' => 'array', 'test_mode' => 'boolean', 'received_at' => 'immutable_datetime', 'processed_at' => 'immutable_datetime', diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index af48d0b..194b426 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -28,7 +28,7 @@ 'channel_stale_after_minutes', 'channel_task_reminder_after_minutes', 'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections', 'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on', - 'process_defaults', 'document_releases', + 'process_defaults', 'document_releases', 'communication_rules', ])] class Tenant extends Model { @@ -77,6 +77,7 @@ protected function casts(): array 'digest_sections' => 'array', 'process_defaults' => 'array', 'document_releases' => 'array', + 'communication_rules' => 'array', 'digest_when_empty' => 'boolean', 'digest_daily_sent_on' => 'immutable_date', 'digest_weekly_sent_on' => 'immutable_date', diff --git a/config/communication.php b/config/communication.php new file mode 100644 index 0000000..6cf9cb9 --- /dev/null +++ b/config/communication.php @@ -0,0 +1,31 @@ + [ + Medium::Email->value => ['active' => true, 'consent_required' => false], + Medium::Form->value => ['active' => true, 'consent_required' => false], + Medium::WhatsApp->value => ['active' => false, 'consent_required' => true], + Medium::Chat->value => ['active' => false, 'consent_required' => false], + ], + + /** Effects per intent. Anything not listed means: review. */ + 'effects' => [ + I::GeneralQuestion->value => [E::AnswerInformation, E::Review], + I::StayInquiry->value => [E::HandoffInquiry, E::Review], + I::CaseReply->value => [E::ReportToCase, E::Review], + I::ProvideData->value => [E::ContributeFacts, E::ReportToCase, E::Review], + I::ChangeRequest->value => [E::ReportToCase, E::Review], + I::Unclear->value => [E::Review], + ], +]; diff --git a/database/migrations/2026_11_08_100000_add_medium_and_intent_to_inbound_messages.php b/database/migrations/2026_11_08_100000_add_medium_and_intent_to_inbound_messages.php new file mode 100644 index 0000000..b7f17f7 --- /dev/null +++ b/database/migrations/2026_11_08_100000_add_medium_and_intent_to_inbound_messages.php @@ -0,0 +1,34 @@ +string('medium', 20)->default('email')->after('message_id'); + $table->string('intent', 30)->nullable(); + $table->json('decision')->nullable(); + }); + Schema::table('tenants', function (Blueprint $table) { + $table->json('communication_rules')->nullable(); + }); + } + + public function down(): void + { + Schema::table('tenants', function (Blueprint $table) { + $table->dropColumn('communication_rules'); + }); + Schema::table('inbound_messages', function (Blueprint $table) { + $table->dropColumn(['medium', 'intent', 'decision']); + }); + } +}; diff --git a/tests/Feature/Process/MessageMediumIntentTest.php b/tests/Feature/Process/MessageMediumIntentTest.php new file mode 100644 index 0000000..0e953cb --- /dev/null +++ b/tests/Feature/Process/MessageMediumIntentTest.php @@ -0,0 +1,173 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + $this->property = Property::sole(); + Mail::fake(); + config(['communication.media.whatsapp.active' => true, 'communication.media.chat.active' => true]); + } + + /** Case E: a reply by WhatsApp with a verified reference reaches the case, origin preserved, nothing taken over by itself. */ + public function test_case_e_a_whatsapp_reply_with_verified_reference_reports_to_the_case_and_keeps_its_origin(): void + { + $booking = $this->request(); + + $decision = $this->receive(Medium::WhatsApp, 'Wir kommen gegen 16 Uhr an, Kennzeichen HRO-AB 123', verified: $booking->id, consent: true); + + $this->assertSame(MessageIntent::ProvideData, $decision->intent); + $this->assertTrue($decision->booking->is($booking)); + $this->assertTrue($decision->has(MessageEffect::ContributeFacts)); + $this->assertTrue($decision->has(MessageEffect::ReportToCase)); + $message = InboundMessage::query()->sole(); + $this->assertSame('whatsapp', $message->medium); + $this->assertSame($booking->id, $message->booking_id); + $this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::InboundReview)->count()); + $this->assertSame($booking->status, $booking->fresh()->status, 'the message changes no booking status'); + $this->assertSame(1, Booking::query()->count()); + } + + public function test_the_same_message_twice_is_stored_and_decided_once(): void + { + $booking = $this->request(); + + $this->receive(Medium::Chat, 'Ankunft 15 Uhr', verified: $booking->id, id: 'c-1'); + $again = $this->receive(Medium::Chat, 'Ankunft 15 Uhr', verified: $booking->id, id: 'c-1'); + + $this->assertSame(1, InboundMessage::query()->count()); + $this->assertSame(1, BookingTask::query()->where('kind', BookingTaskKind::InboundReview)->count()); + $this->assertTrue($again->booking->is($booking)); + } + + /** Case F: an inquiry without a case via chat answers or hands off – and never creates a case. */ + public function test_case_f_a_general_question_creates_no_case_and_only_allows_information(): void + { + $decision = $this->receive(Medium::Chat, 'Sind Hunde erlaubt und gibt es einen Parkplatz?'); + + $this->assertSame(MessageIntent::GeneralQuestion, $decision->intent); + $this->assertSame([MessageEffect::AnswerInformation], $decision->effects); + $this->assertNull($decision->booking); + $this->assertSame(0, Booking::query()->count()); + $this->assertSame(0, BookingTask::query()->count()); + } + + public function test_a_stay_inquiry_via_whatsapp_refers_to_the_inquiry_path_and_books_nothing(): void + { + $decision = $this->receive(Medium::WhatsApp, 'Ist die Wohnung vom 12.12. bis 19.12. frei? Wir würden gern buchen.', consent: true); + + $this->assertSame(MessageIntent::StayInquiry, $decision->intent); + $this->assertSame([MessageEffect::HandoffInquiry], $decision->effects); + $this->assertSame(0, Booking::query()->count()); + } + + public function test_same_sender_or_name_alone_never_assigns_a_case(): void + { + $booking = $this->request(); + + $decision = $this->receive(Medium::WhatsApp, 'Hier Gesa Gast, wir kommen um 16 Uhr an.', sender: 'gesa@example.org', consent: true); + + $this->assertNull($decision->booking); + $this->assertSame([MessageEffect::Review], $decision->effects); + $this->assertSame(InboundMessage::NEEDS_REVIEW, InboundMessage::query()->sole()->status); + $this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->count()); + } + + public function test_a_contradicting_case_number_in_the_text_sends_the_message_to_review(): void + { + $booking = $this->request(); + + $decision = $this->receive(Medium::Chat, 'Zu Vorgang 2099-0001: Ankunft 17 Uhr', verified: $booking->id); + + $this->assertNull($decision->booking); + $this->assertSame([MessageEffect::Review], $decision->effects); + $this->assertStringContainsString('widersprüchlich', implode(' ', $decision->reasons)); + } + + public function test_an_unclear_message_goes_to_review(): void + { + $decision = $this->receive(Medium::Chat, 'ok danke'); + + $this->assertSame(MessageIntent::Unclear, $decision->intent); + $this->assertSame([MessageEffect::Review], $decision->effects); + } + + public function test_a_medium_without_consent_or_switched_off_only_reaches_review(): void + { + $booking = $this->request(); + + $noConsent = $this->receive(Medium::WhatsApp, 'Ankunft 16 Uhr', verified: $booking->id, consent: false, id: 'w-1'); + config(['communication.media.chat.active' => false]); + $off = $this->receive(Medium::Chat, 'Ankunft 16 Uhr', verified: $booking->id, id: 'c-9'); + + $this->assertSame([MessageEffect::Review], $noConsent->effects); + $this->assertSame([MessageEffect::Review], $off->effects); + $this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->count()); + } + + public function test_the_landlord_may_only_narrow_never_widen_the_rules(): void + { + $rules = app(CommunicationRules::class); + Settings::tenant()->update(['communication_rules' => [ + 'media' => ['chat' => ['active' => false], 'email' => ['active' => true]], + 'effects' => ['whatsapp' => ['provide_data' => ['contribute_facts']]], + ]]); + + $this->assertFalse($rules->mediumActive(Medium::Chat)); + $this->assertTrue($rules->mediumActive(Medium::WhatsApp)); + $this->assertSame([MessageEffect::ReportToCase, MessageEffect::Review], $rules->effects(Medium::WhatsApp, MessageIntent::ProvideData)); + + // Widening is ignored: the ceiling keeps WhatsApp off even when the tenant says "active". + config(['communication.media.whatsapp.active' => false]); + Settings::tenant()->update(['communication_rules' => ['media' => ['whatsapp' => ['active' => true]]]]); + $this->assertFalse($rules->mediumActive(Medium::WhatsApp)); + } + + private function request(): Booking + { + return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'])->fresh(); + } + + private function receive(Medium $medium, string $text, ?int $verified = null, bool $consent = false, string $sender = '+491701234567', string $id = 'm-1'): MessageDecision + { + return app(MessageIntake::class)->handle(new IncomingMessage($medium, $sender, $text, CarbonImmutable::now(), $id, $verified, $consent)); + } +}