V2.1: Kommunikation nach Medium, Absicht und Wirkung (Fälle E/F)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8442d0a3d8
commit
8026eceab4
13 files changed
+633
-2
No files matched your search
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Enums\Medium;
|
||||
use App\Enums\MessageEffect;
|
||||
use App\Enums\MessageIntent;
|
||||
use App\Support\Settings;
|
||||
|
||||
/**
|
||||
* The medium × intent policy (V2.1): `config/communication.php` is the ceiling, the landlord's `communication_rules`
|
||||
* (tenants) may only narrow it: switch a medium off, withdraw effects. Widening is ignored.
|
||||
*/
|
||||
class CommunicationRules
|
||||
{
|
||||
public function mediumActive(Medium $medium): bool
|
||||
{
|
||||
$ceiling = (bool) config("communication.media.{$medium->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<MessageEffect> 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<MessageEffect> $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<string, mixed>
|
||||
*/
|
||||
private function narrowing(): array
|
||||
{
|
||||
return (array) (Settings::tenant()?->communication_rules ?? []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Enums\Medium;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* A message as the medium adapters hand it over (V2.1): raw data only. {@see $verifiedBookingId} is set by the adapter
|
||||
* itself from a reference it issued and can verify (signed token, reply to one of our mails) – a claim in the text is
|
||||
* never enough. {@see $consentGiven} is likewise the adapter's statement.
|
||||
*/
|
||||
final readonly class IncomingMessage
|
||||
{
|
||||
public function __construct(
|
||||
public Medium $medium,
|
||||
public string $sender,
|
||||
public string $text,
|
||||
public CarbonImmutable $receivedAt,
|
||||
public string $externalId,
|
||||
public ?int $verifiedBookingId = null,
|
||||
public bool $consentGiven = false,
|
||||
public ?string $senderName = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Enums\MessageIntent;
|
||||
|
||||
/**
|
||||
* Rule-based intent of a message (V2.1). Deterministic and medium-independent; an AI classifier can later implement the
|
||||
* same interface of work (E-035). Whatever the rules do not clearly recognise is {@see MessageIntent::Unclear}.
|
||||
*/
|
||||
class IntentClassifier
|
||||
{
|
||||
public function classify(string $text, bool $assignedToCase): MessageIntent
|
||||
{
|
||||
$text = mb_strtolower($text);
|
||||
$has = fn (array $words): bool => (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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Enums\Medium;
|
||||
use App\Enums\MessageEffect;
|
||||
use App\Enums\MessageIntent;
|
||||
use App\Models\Booking;
|
||||
|
||||
/**
|
||||
* What the process core decided about a message (V2.1): intent, case (only if verified), the effects that apply and why.
|
||||
*/
|
||||
final readonly class MessageDecision
|
||||
{
|
||||
/**
|
||||
* @param list<MessageEffect> $effects applied effects, in order
|
||||
* @param list<string> $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<string>, reasons: list<string>}
|
||||
*/
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Actions\ReceiveInboundMessage;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\MessageEffect;
|
||||
use App\Enums\MessageIntent;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
|
||||
/**
|
||||
* Entry of messages from every medium except the e-mail inbox, which keeps its own path (V2.1, docs/…/02 §6):
|
||||
* store once → assign deterministically (only a reference verified by the adapter, and not contradicted by the text) →
|
||||
* classify → apply the effects the rules allow. A message never creates a case, reservation, offer or booking; what is
|
||||
* unclear or contradictory goes to review. No answer is sent here.
|
||||
*/
|
||||
class MessageIntake
|
||||
{
|
||||
public function __construct(private CommunicationRules $rules, private IntentClassifier $classifier) {}
|
||||
|
||||
public function handle(IncomingMessage $incoming): MessageDecision
|
||||
{
|
||||
$key = $incoming->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<string> $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<string> $reasons
|
||||
* @return list<MessageEffect>
|
||||
*/
|
||||
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'] ?? []),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* The communication medium a message came through (V2.1). It says nothing about bindingness or business meaning.
|
||||
* WhatsApp and Chat exist as test cases of the architecture; no provider is connected.
|
||||
*/
|
||||
enum Medium: string implements HasLabel
|
||||
{
|
||||
case Email = 'email';
|
||||
case Form = 'form';
|
||||
case WhatsApp = 'whatsapp';
|
||||
case Chat = 'chat';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Email => 'E-Mail',
|
||||
self::Form => 'Formular',
|
||||
self::WhatsApp => 'WhatsApp',
|
||||
self::Chat => 'Chat',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What a message may cause (V2.1). No effect creates a case, a reservation, an offer or a booking.
|
||||
*/
|
||||
enum MessageEffect: string implements HasLabel
|
||||
{
|
||||
case AnswerInformation = 'answer_information';
|
||||
case ContributeFacts = 'contribute_facts';
|
||||
case ReportToCase = 'report_to_case';
|
||||
case HandoffInquiry = 'handoff_inquiry';
|
||||
case Review = 'review';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::AnswerInformation => '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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Communication\IntentClassifier;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What a message wants (V2.1) – decided by the rules of {@see IntentClassifier}, independent of the medium.
|
||||
*/
|
||||
enum MessageIntent: string implements HasLabel
|
||||
{
|
||||
case GeneralQuestion = 'general_question';
|
||||
case StayInquiry = 'stay_inquiry';
|
||||
case CaseReply = 'case_reply';
|
||||
case ProvideData = 'provide_data';
|
||||
case ChangeRequest = 'change_request';
|
||||
case Unclear = 'unclear';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::GeneralQuestion => '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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\Medium;
|
||||
use App\Enums\MessageEffect as E;
|
||||
use App\Enums\MessageIntent as I;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Medium × intent rules (V2.1, docs/Prozessarchitektur/V2.1/02 §6)
|
||||
|--------------------------------------------------------------------------
|
||||
| The ceiling. A landlord may only narrow it (tenants.communication_rules), never widen it. A message never creates a
|
||||
| case, reservation, offer or booking – no effect does. Without a verified assignment, effects that act on a case are dropped.
|
||||
*/
|
||||
return [
|
||||
'media' => [
|
||||
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],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* V2.1 (docs/Prozessarchitektur/V2.1/02 §6): medium, intent and the decision of a message are kept next to it; existing
|
||||
* rows are e-mails. The landlord's narrowing of the communication rules is a column of the tenant.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('inbound_messages', function (Blueprint $table) {
|
||||
$table->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']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Process;
|
||||
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Communication\CommunicationRules;
|
||||
use App\Communication\IncomingMessage;
|
||||
use App\Communication\MessageDecision;
|
||||
use App\Communication\MessageIntake;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\Medium;
|
||||
use App\Enums\MessageEffect;
|
||||
use App\Enums\MessageIntent;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use PHPUnit\Framework\Attributes\Group;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* V2.1 cases E and F (docs/Prozessarchitektur/V2.1/02 §6): medium, intent and effect are separate. WhatsApp and chat are
|
||||
* test cases of the architecture (no provider): an assigned reply keeps its origin, a question without a case causes no
|
||||
* case, everything unclear or contradictory goes to review.
|
||||
*/
|
||||
#[Group('module:communication.medium')]
|
||||
class MessageMediumIntentTest 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);
|
||||
$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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user