Files
fewo-stommer/app/Channels/Mail/PortalMailParser.php
Lars StommerandClaude Opus 5.5 e5f9e0762f Schnellerkennung von Portalbuchungen per E-Mail
- IMAP-Abruf jede Minute (webklex/php-imap, ohne PHP-imap-Erweiterung) oder signierter Push von n8n
- Parser für Buchungs-, Storno- und Anfrage-Mails (de/en), Buchungsnummer, An-/Abreise
- Erkannte Buchungen werden sofort gesperrt und an handgepflegte Portale weitergegeben; Kalender-Abgleich übernimmt bzw. ersetzt Mail-Sperren
- Unklare Mails: Prüf-Mail + Admin-Liste Portal-E-Mails mit Aktion Sperre anlegen
- Überwachung des Postfachs in Monitor und /health/sync

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:29:26 +02:00

195 lines
7.1 KiB
PHP

<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
/**
* Reads booking notifications of portals (German and English). It only extracts what it can find
* with confidence; everything else is left empty so that the e-mail is flagged for review.
*/
class PortalMailParser
{
private const CANCELLATION = ['storniert', 'stornierung', 'cancelled', 'canceled', 'cancellation', 'abgesagt'];
private const BOOKING = ['neue buchung', 'buchung bestätigt', 'buchungsbestätigung', 'reservierung bestätigt', 'sofortbuchung', 'hat gebucht', 'ist gebucht', 'new booking', 'booking confirmed', 'reservation confirmed', 'instant booking', 'you have a new reservation', 'neue reservierung'];
/** Checked before bookings: "Neue Buchungsanfrage" is not a confirmed booking. */
private const INQUIRY = ['buchungsanfrage', 'booking request', 'reservation request', 'anfrage', 'inquiry', 'enquiry'];
private const MONTHS = [
'jan' => 1, 'januar' => 1, 'january' => 1,
'feb' => 2, 'februar' => 2, 'february' => 2,
'mär' => 3, 'märz' => 3, 'mrz' => 3, 'mar' => 3, 'march' => 3,
'apr' => 4, 'april' => 4,
'mai' => 5, 'may' => 5,
'jun' => 6, 'juni' => 6, 'june' => 6,
'jul' => 7, 'juli' => 7, 'july' => 7,
'aug' => 8, 'august' => 8,
'sep' => 9, 'sept' => 9, 'september' => 9,
'okt' => 10, 'oktober' => 10, 'oct' => 10, 'october' => 10,
'nov' => 11, 'november' => 11,
'dez' => 12, 'dezember' => 12, 'dec' => 12, 'december' => 12,
];
public function parse(string $subject, string $text): ParsedPortalMail
{
$content = $this->normalize($subject."\n".$text);
$type = $this->type(mb_strtolower($subject))
?? $this->type(mb_strtolower($this->normalize($text)))
?? PortalEmailType::Unknown;
[$startsOn, $endsOn] = $this->period($content);
return new ParsedPortalMail($type, $startsOn, $endsOn, $this->reference($content));
}
/**
* The subject decides first; the body only when the subject is not conclusive.
*/
private function type(string $text): ?PortalEmailType
{
return match (true) {
$this->containsAny($text, self::CANCELLATION) => PortalEmailType::Cancellation,
$this->containsAny($text, self::INQUIRY) => PortalEmailType::Inquiry,
$this->containsAny($text, self::BOOKING) => PortalEmailType::Booking,
default => null,
};
}
/**
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function period(string $content): array
{
$dates = $this->dates($content);
$arrival = $this->dateAfterLabel($content, $dates, '/\b(anreise|ankunft|check-?in|arrival)\b/iu');
$departure = $this->dateAfterLabel($content, $dates, '/\b(abreise|check-?out|departure)\b/iu');
if ($arrival === null || $departure === null) {
[$arrival, $departure] = $this->firstPlausiblePair($dates);
}
if ($arrival === null || $departure === null || ! $this->isPlausible($arrival, $departure)) {
return [null, null];
}
return [$arrival, $departure];
}
/**
* All dates in the text with their offsets, in order of appearance.
*
* @return list<array{offset: int, date: CarbonImmutable}>
*/
private function dates(string $content): array
{
$monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS)));
$patterns = [
'/\b(?<d>\d{1,2})\.(?<m>\d{1,2})\.(?<y>\d{4}|\d{2})\b/u',
'/\b(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})\b/u',
'/\b(?<d>\d{1,2})\.?\s+(?<mn>'.$monthNames.')\.?\s+(?<y>\d{4})\b/iu',
'/\b(?<mn>'.$monthNames.')\.?\s+(?<d>\d{1,2}),?\s+(?<y>\d{4})\b/iu',
];
$dates = [];
foreach ($patterns as $pattern) {
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
foreach ($matches as $match) {
$month = isset($match['mn']) && $match['mn'][0] !== '' ? self::MONTHS[mb_strtolower($match['mn'][0])] ?? null : (int) $match['m'][0];
$year = (int) $match['y'][0];
$year = $year < 100 ? 2000 + $year : $year;
if ($month !== null && checkdate($month, (int) $match['d'][0], $year)) {
$dates[] = ['offset' => $match[0][1], 'date' => CarbonImmutable::create($year, $month, (int) $match['d'][0])];
}
}
}
usort($dates, fn (array $a, array $b): int => $a['offset'] <=> $b['offset']);
return $dates;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
*/
private function dateAfterLabel(string $content, array $dates, string $labelPattern): ?CarbonImmutable
{
if (! preg_match($labelPattern, $content, $label, PREG_OFFSET_CAPTURE)) {
return null;
}
$labelEnd = $label[0][1] + strlen($label[0][0]);
foreach ($dates as $date) {
if ($date['offset'] >= $labelEnd && $date['offset'] - $labelEnd <= 80) {
return $date['date'];
}
}
return null;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function firstPlausiblePair(array $dates): array
{
foreach ($dates as $index => $first) {
foreach (array_slice($dates, $index + 1) as $second) {
if ($this->isPlausible($first['date'], $second['date'])) {
return [$first['date'], $second['date']];
}
}
}
return [null, null];
}
private function isPlausible(CarbonImmutable $arrival, CarbonImmutable $departure): bool
{
return $departure->greaterThan($arrival)
&& $arrival->diffInDays($departure) <= 90
&& $arrival->greaterThanOrEqualTo(CarbonImmutable::today()->subDays(2))
&& $arrival->lessThanOrEqualTo(CarbonImmutable::today()->addYears(3));
}
private function reference(string $content): ?string
{
if (preg_match('/\b(HA-[A-Z0-9]{5,})\b/', $content, $match)) {
return $match[1];
}
if (preg_match('/(?:buchungsnummer|buchungs-nr\.?|reservierungsnummer|reservation id|reservation number|booking id|booking number)\s*[:#]?\s*([A-Z0-9][A-Z0-9-]{4,})/iu', $content, $match)) {
return $match[1];
}
return null;
}
private function normalize(string $text): string
{
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return preg_replace('/[ \t\x{00A0}\x{202F}]+/u', ' ', $text);
}
/**
* @param list<string> $needles
*/
private function containsAny(string $haystack, array $needles): bool
{
foreach ($needles as $needle) {
if (str_contains($haystack, $needle)) {
return true;
}
}
return false;
}
}