Files
fewo-stommer/app/Communication/MessageMatcher.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

114 lines
5.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Communication;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\BookingMessage;
use App\Models\InboundMessage;
use App\Models\Property;
use App\Support\Settings;
use Carbon\CarbonImmutable;
/**
* Deterministic assignment of an incoming message to a case (v0.11, CH-07, CH-13) – no scoring. A message is
* assigned only by
*
* 1. a known reply reference (In-Reply-To / References of one of our mails),
* 2. our case number together with the case's guest as sender (the number alone is no proof of identity), or
* 3. the combination of sender (the guest's e-mail), property and both dates of exactly one open case of that guest.
*
* One open case of the same sender alone is not enough; it is only shown as a hint. Everything else waits in the inbox
* for the landlord. Being assigned does not yet allow taking anything over.
*/
class MessageMatcher
{
/**
* @return array{booking: ?Booking, reason: ?string, hints: list<array{booking_id: int, reference: string, why: string}>}
*/
public function match(InboundMessage $message): array
{
$sender = mb_strtolower(trim((string) $message->from_address));
$text = $message->subject."\n".$message->body;
// Message-IDs are compared with and without angle brackets (mail servers deliver both forms).
$references = collect([$message->in_reply_to, ...((array) $message->references)])->filter()
->flatMap(fn (string $id): array => ['<'.trim($id, '<> ').'>', trim($id, '<> ')])->unique()->values()->all();
if ($references !== []) {
$replied = BookingMessage::query()->whereIn('message_id', $references)->whereNotNull('booking_id')->latest('id')->first()?->booking;
if ($replied !== null) {
return ['booking' => $replied, 'reason' => 'reply', 'hints' => []];
}
}
$hints = [];
// In test operation every answer comes from the test mailbox: there it stands for the guest of the named case.
$testSender = $message->test_mode && $sender !== '' && $sender === mb_strtolower(trim((string) Settings::tenant()?->test_recipient));
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $text, $numbers)) {
foreach (Booking::query()->whereIn('reference', array_unique($numbers[1]))->with('guest')->get() as $booking) {
if ($testSender) {
return ['booking' => $booking, 'reason' => 'reference_test_sender', 'hints' => []];
}
if ($sender !== '' && mb_strtolower((string) $booking->guest?->email) === $sender) {
return ['booking' => $booking, 'reason' => 'reference_and_sender', 'hints' => []];
}
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'Vorgangsnummer genannt, aber anderer Absender'];
}
}
if ($sender === '') {
return ['booking' => null, 'reason' => null, 'hints' => $hints];
}
$open = Booking::query()
->whereHas('guest', fn ($guest) => $guest->where('email', $sender))
->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed])
->whereDate('departure', '>=', CarbonImmutable::today())
->with('property')
->get();
$dates = $this->dates($text);
$singleProperty = Property::query()->count() === 1;
$candidates = $open->filter(fn (Booking $booking): bool => in_array($booking->arrival->toDateString(), $dates, true)
&& in_array($booking->departure->toDateString(), $dates, true)
&& ($singleProperty || mb_stripos($text, (string) $booking->property?->name) !== false));
if ($candidates->count() === 1) {
return ['booking' => $candidates->first(), 'reason' => 'sender_property_dates', 'hints' => []];
}
foreach ($open as $booking) {
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'offener Vorgang dieses Absenders ('.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y').')'];
}
return ['booking' => null, 'reason' => null, 'hints' => array_values(array_unique($hints, SORT_REGULAR))];
}
/**
* Dates written in the message (d.m.yyyy, d.m.yy, yyyy-mm-dd).
*
* @return list<string> Y-m-d
*/
public function dates(string $text): array
{
$dates = [];
if (preg_match_all('/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{4}|\d{2})\b/', $text, $german, PREG_SET_ORDER)) {
foreach ($german as [, $day, $month, $year]) {
$year = strlen($year) === 2 ? '20'.$year : $year;
if (checkdate((int) $month, (int) $day, (int) $year)) {
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
}
if (preg_match_all('/\b(20\d{2})-(\d{2})-(\d{2})\b/', $text, $iso, PREG_SET_ORDER)) {
foreach ($iso as [, $year, $month, $day]) {
if (checkdate((int) $month, (int) $day, (int) $year)) {
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
}
return array_values(array_unique($dates));
}
}