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>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 11:29:26 +02:00
1 parent 0b7205e050
commit e5f9e0762f
33 files changed
+1450 -38

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Channels;
use App\Models\BlockedPeriod;
use App\Models\Booking;
/**
* Finds occupations from other sources that overlap a block reported by a portal
* (a possible double booking). Blocks of the same portal never conflict with each other.
*/
class ConflictDetector
{
/**
* @return list<string> human readable descriptions
*/
public function conflictsFor(BlockedPeriod $block): array
{
$property = $block->property;
$channelName = $block->channel->name ?? 'Sperre';
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
$blocks = $property->blockedPeriods()
->overlapping($block->starts_on, $block->ends_on)
->whereKeyNot($block->getKey())
->when($block->channel_id, fn ($query) => $query->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $block->channel_id)))
->with('channel')
->get()
->map(fn (BlockedPeriod $other): string => "{$channelName} meldet {$period}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})");
return [...$bookings->all(), ...$blocks->all()];
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace App\Channels\Mail;
use App\Channels\ChannelSyncException;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Throwable;
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Message;
/**
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
* Works without the PHP imap extension.
*/
class MailboxReader
{
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
public const LAST_ERROR_KEY = 'mailbox:last_error';
public static function isConfigured(): bool
{
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
}
/**
* @param list<string> $senders addresses or domains
* @return list<PortalMail>
*
* @throws ChannelSyncException
*/
public function fetch(array $senders): array
{
$config = config('fewo.mailbox');
try {
$client = (new ClientManager)->make([
'host' => $config['host'],
'port' => $config['port'],
'encryption' => $config['encryption'],
'validate_cert' => true,
'username' => $config['username'],
'password' => $config['password'],
'protocol' => 'imap',
]);
$client->connect();
$folder = $client->getFolderByPath($config['folder']);
$mails = [];
foreach ($senders as $sender) {
$messages = $folder->query()
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
->whereFrom($sender)
->leaveUnread()
->get();
foreach ($messages as $message) {
$mails[] = $this->toPortalMail($message);
}
}
$client->disconnect();
} catch (Throwable $exception) {
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
}
Cache::forever(self::LAST_SUCCESS_KEY, now()->toIso8601String());
Cache::forget(self::LAST_ERROR_KEY);
return $mails;
}
private function toPortalMail(Message $message): PortalMail
{
$text = $message->getTextBody();
if (trim($text) === '') {
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
}
$from = $message->getFrom()->first();
$date = $message->getDate()->first();
return new PortalMail(
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
from: (string) ($from->mail ?? ''),
subject: (string) $message->getSubject()->first(),
text: $text,
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
final readonly class ParsedPortalMail
{
public function __construct(
public PortalEmailType $type,
public ?CarbonImmutable $startsOn = null,
public ?CarbonImmutable $endsOn = null,
public ?string $reference = null,
) {}
public function hasPeriod(): bool
{
return $this->startsOn !== null && $this->endsOn !== null;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Channels\Mail;
use Carbon\CarbonImmutable;
/**
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
*/
final readonly class PortalMail
{
public function __construct(
public string $messageId,
public string $from,
public string $subject,
public string $text,
public CarbonImmutable $receivedAt,
) {}
}
+194
View File
@@ -0,0 +1,194 @@
<?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;
}
}