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:
LarsandClaude Sonnet 5.5 committed 2026-11-05 07:57:54 +01:00
1 parent 8442d0a3d8
commit 8026eceab4
13 files changed
+633 -2

No files matched your search

+48
View File
@@ -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 ?? []);
}
}
+25
View File
@@ -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,
) {}
}
+36
View File
@@ -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;
}
}
+40
View File
@@ -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];
}
}
+150
View File
@@ -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'] ?? []),
);
}
}