151 lines
6.7 KiB
PHP
151 lines
6.7 KiB
PHP
<?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'] ?? []),
|
||
);
|
||
}
|
||
}
|