From e5f9e0762f226e9955dae8f2677754923254d412 Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Thu, 22 Oct 2026 11:29:26 +0200 Subject: [PATCH] Schnellerkennung von Portalbuchungen per E-Mail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .env.example | 6 + AGENTS.md | 2 +- CLAUDE.md | 2 +- app/Actions/MonitorChannels.php | 42 +++- app/Actions/ProcessPortalMail.php | 165 ++++++++++++++ app/Actions/SyncChannel.php | 49 ++-- app/Channels/ConflictDetector.php | 36 +++ app/Channels/Mail/MailboxReader.php | 94 ++++++++ app/Channels/Mail/ParsedPortalMail.php | 21 ++ app/Channels/Mail/PortalMail.php | 19 ++ app/Channels/Mail/PortalMailParser.php | 194 ++++++++++++++++ app/Console/Commands/FetchPortalMail.php | 56 +++++ app/Enums/PortalEmailStatus.php | 43 ++++ app/Enums/PortalEmailType.php | 23 ++ .../PortalEmails/Pages/ListPortalEmails.php | 11 + .../PortalEmails/PortalEmailResource.php | 57 +++++ .../PortalEmails/Tables/PortalEmailsTable.php | 66 ++++++ .../ChannelsRelationManager.php | 5 + app/Http/Controllers/ChannelController.php | 58 ++++- app/Mail/MailboxAlert.php | 33 +++ app/Mail/PortalMailNotification.php | 41 ++++ app/Models/PortalEmail.php | 54 +++++ app/Policies/PortalEmailPolicy.php | 13 ++ composer.json | 3 +- composer.lock | 83 ++++++- config/fewo.php | 15 ++ ...0_22_112327_create_portal_emails_table.php | 40 ++++ docs/PORTALE.md | 2 + resources/views/mail/mailbox-alert.blade.php | 11 + resources/views/mail/portal-mail.blade.php | 28 +++ routes/console.php | 2 + routes/web.php | 4 + tests/Feature/PortalMailTest.php | 210 ++++++++++++++++++ 33 files changed, 1450 insertions(+), 38 deletions(-) create mode 100644 app/Actions/ProcessPortalMail.php create mode 100644 app/Channels/ConflictDetector.php create mode 100644 app/Channels/Mail/MailboxReader.php create mode 100644 app/Channels/Mail/ParsedPortalMail.php create mode 100644 app/Channels/Mail/PortalMail.php create mode 100644 app/Channels/Mail/PortalMailParser.php create mode 100644 app/Console/Commands/FetchPortalMail.php create mode 100644 app/Enums/PortalEmailStatus.php create mode 100644 app/Enums/PortalEmailType.php create mode 100644 app/Filament/Resources/PortalEmails/Pages/ListPortalEmails.php create mode 100644 app/Filament/Resources/PortalEmails/PortalEmailResource.php create mode 100644 app/Filament/Resources/PortalEmails/Tables/PortalEmailsTable.php create mode 100644 app/Mail/MailboxAlert.php create mode 100644 app/Mail/PortalMailNotification.php create mode 100644 app/Models/PortalEmail.php create mode 100644 app/Policies/PortalEmailPolicy.php create mode 100644 database/migrations/2026_10_22_112327_create_portal_emails_table.php create mode 100644 resources/views/mail/mailbox-alert.blade.php create mode 100644 resources/views/mail/portal-mail.blade.php create mode 100644 tests/Feature/PortalMailTest.php diff --git a/.env.example b/.env.example index 663911c..80bab86 100644 --- a/.env.example +++ b/.env.example @@ -78,3 +78,9 @@ FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120 FEWO_HEALTH_TOKEN= FEWO_AUTOMATION_WEBHOOK_URL= FEWO_AUTOMATION_SECRET= +FEWO_MAILBOX_HOST= +FEWO_MAILBOX_PORT=993 +FEWO_MAILBOX_ENCRYPTION=ssl +FEWO_MAILBOX_USERNAME= +FEWO_MAILBOX_PASSWORD= +FEWO_MAILBOX_FOLDER=INBOX diff --git a/AGENTS.md b/AGENTS.md index 3b175e5..dae5f87 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ # Ferienwohnung Stommer - Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status. - Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly. - Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. -- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal analysis: `docs/PORTALE.md`. +- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/CLAUDE.md b/CLAUDE.md index 3b175e5..dae5f87 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ # Ferienwohnung Stommer - Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status. - Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly. - Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. -- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal analysis: `docs/PORTALE.md`. +- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/app/Actions/MonitorChannels.php b/app/Actions/MonitorChannels.php index ad8e2af..7e1717f 100644 --- a/app/Actions/MonitorChannels.php +++ b/app/Actions/MonitorChannels.php @@ -2,16 +2,22 @@ namespace App\Actions; +use App\Channels\Mail\MailboxReader; use App\Mail\ChannelSyncAlert; +use App\Mail\MailboxAlert; use App\Models\Channel; +use Carbon\CarbonImmutable; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Mail; /** - * Alerts the landlord once per incident when a portal import fails or has not succeeded for too long. - * The alert is reset by the next successful sync. + * Alerts the landlord once per incident when a portal import or the mailbox fast path fails + * or has not succeeded for too long. The alert is reset by the next success. */ class MonitorChannels { + private const MAILBOX_ALERTED_KEY = 'mailbox:alerted'; + public function handle(): int { $channels = Channel::query()->active()->whereNull('alerted_at')->get() @@ -22,6 +28,36 @@ public function handle(): int $channel->forceFill(['alerted_at' => now()])->save(); } - return $channels->count(); + return $channels->count() + $this->monitorMailbox(); + } + + public static function mailboxIsStale(): bool + { + if (! MailboxReader::isConfigured()) { + return false; + } + + $lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY); + + return $lastSuccess === null + || CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes'))); + } + + private function monitorMailbox(): int + { + if (! self::mailboxIsStale()) { + Cache::forget(self::MAILBOX_ALERTED_KEY); + + return 0; + } + + if (Cache::has(self::MAILBOX_ALERTED_KEY)) { + return 0; + } + + Mail::to(config('fewo.notification_email'))->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY))); + Cache::forever(self::MAILBOX_ALERTED_KEY, true); + + return 1; } } diff --git a/app/Actions/ProcessPortalMail.php b/app/Actions/ProcessPortalMail.php new file mode 100644 index 0000000..e157d18 --- /dev/null +++ b/app/Actions/ProcessPortalMail.php @@ -0,0 +1,165 @@ +messageId)->exists()) { + return null; + } + + $channel = $this->channelFor($mail->from); + if ($channel === null) { + return null; + } + + $parsed = $this->parser->parse($mail->subject, $mail->text); + $conflicts = []; + + $record = DB::transaction(function () use ($mail, $channel, $parsed, &$conflicts): PortalEmail { + [$status, $block, $note] = match ($parsed->type) { + PortalEmailType::Booking => $this->block($channel, $parsed, $conflicts), + PortalEmailType::Cancellation => $this->release($channel, $parsed), + PortalEmailType::Inquiry => [PortalEmailStatus::Ignored, null, 'Anfrage – keine Sperre nötig.'], + PortalEmailType::Unknown => [PortalEmailStatus::NeedsReview, null, 'Inhalt nicht erkannt.'], + }; + + return PortalEmail::create([ + 'channel_id' => $channel->id, + 'message_id' => $mail->messageId, + 'from' => mb_substr($mail->from, 0, 255), + 'subject' => mb_substr($mail->subject, 0, 255), + 'received_at' => $mail->receivedAt, + 'type' => $parsed->type, + 'status' => $status, + 'starts_on' => $parsed->startsOn?->toDateString(), + 'ends_on' => $parsed->endsOn?->toDateString(), + 'reference' => $parsed->reference, + 'blocked_period_id' => $block?->id, + 'excerpt' => mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags($mail->text))), 0, 500), + 'note' => $note, + ]); + }); + + if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) { + rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new PortalMailNotification($record))); + } + + if ($conflicts !== []) { + rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts))); + } + + return $record; + } + + /** + * Channels list the sender addresses or domains of their notification e-mails in settings.email_senders. + */ + public function channelFor(string $from): ?Channel + { + $from = mb_strtolower($from); + + return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool { + foreach ($this->senders($channel) as $sender) { + if (str_contains($from, $sender)) { + return true; + } + } + + return false; + }); + } + + /** + * @return list + */ + public function senders(Channel $channel): array + { + return array_values(array_filter(array_map( + fn (string $sender): string => mb_strtolower(trim($sender)), + explode(',', (string) $channel->setting('email_senders')), + ))); + } + + /** + * @param list $conflicts + * @return array{PortalEmailStatus, ?BlockedPeriod, ?string} + */ + private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array + { + if (! $parsed->hasPeriod()) { + return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.']; + } + + $known = $channel->blockedPeriods() + ->whereDate('starts_on', $parsed->startsOn) + ->whereDate('ends_on', $parsed->endsOn) + ->first(); + if ($known) { + return [PortalEmailStatus::AlreadyKnown, $known, null]; + } + + $block = $channel->blockedPeriods()->create([ + 'property_id' => $channel->property_id, + 'starts_on' => $parsed->startsOn->toDateString(), + 'ends_on' => $parsed->endsOn->toDateString(), + 'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''), + 'source' => 'email', + 'external_uid' => 'email:'.($parsed->reference ?? $parsed->startsOn->format('Ymd').'-'.$parsed->endsOn->format('Ymd')), + ]); + + $conflicts = $this->conflictDetector->conflictsFor($block); + + return [PortalEmailStatus::Blocked, $block, null]; + } + + /** + * Only blocks created from e-mails are released here; calendar blocks disappear with the next sync. + * + * @return array{PortalEmailStatus, ?BlockedPeriod, ?string} + */ + private function release(Channel $channel, ParsedPortalMail $parsed): array + { + $emailBlocks = $channel->blockedPeriods()->where('source', 'email'); + + $block = match (true) { + $parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(), + $parsed->hasPeriod() => (clone $emailBlocks)->whereDate('starts_on', $parsed->startsOn)->whereDate('ends_on', $parsed->endsOn)->first(), + default => null, + }; + + if ($block) { + $block->delete(); + + return [PortalEmailStatus::Released, null, 'Sperre aus E-Mail aufgehoben.']; + } + + return [PortalEmailStatus::NeedsReview, null, 'Stornierung erkannt – bitte prüfen; Kalender-Sperren verschwinden mit dem nächsten Abgleich.']; + } +} diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php index d8f27ac..1dd1d2e 100644 --- a/app/Actions/SyncChannel.php +++ b/app/Actions/SyncChannel.php @@ -3,10 +3,10 @@ namespace App\Actions; use App\Channels\ChannelSyncException; +use App\Channels\ConflictDetector; use App\Channels\ExternalPeriod; use App\Mail\ChannelConflict; use App\Models\BlockedPeriod; -use App\Models\Booking; use App\Models\Channel; use App\Models\ChannelSyncLog; use Carbon\CarbonImmutable; @@ -19,6 +19,8 @@ */ class SyncChannel { + public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {} + public function handle(Channel $channel): ChannelSyncLog { $startedAt = microtime(true); @@ -46,7 +48,8 @@ public function handle(Channel $channel): ChannelSyncLog $conflicts = []; DB::transaction(function () use ($channel, $periods, $today, &$counts, &$conflicts): void { - $existing = $channel->blockedPeriods()->get()->keyBy('external_uid'); + $existing = $channel->blockedPeriods()->where('source', 'channel')->get()->keyBy('external_uid'); + $fromEmails = $channel->blockedPeriods()->where('source', 'email')->get(); $seen = []; foreach ($periods as $period) { @@ -65,6 +68,17 @@ public function handle(Channel $channel): ChannelSyncLog 'source' => 'channel', ]; + $confirmedEmailBlock = $block ? null : $fromEmails->first(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->equalTo($period->startsOn) && $emailBlock->ends_on->equalTo($period->endsOn)); + + if ($confirmedEmailBlock) { + // Already blocked from the portal's e-mail; the calendar only confirms it. + $confirmedEmailBlock->update([...$attributes, 'external_uid' => $period->uid]); + $fromEmails = $fromEmails->reject(fn (BlockedPeriod $emailBlock): bool => $emailBlock->is($confirmedEmailBlock)); + $counts['changed']++; + + continue; + } + if ($block) { $block->update($attributes); $counts['changed']++; @@ -73,7 +87,12 @@ public function handle(Channel $channel): ChannelSyncLog $counts['added']++; } - array_push($conflicts, ...$this->conflictsFor($channel, $block)); + // E-mail blocks of this portal overlapping the calendar entry describe the same booking with deviating dates. + $superseded = $fromEmails->filter(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->lessThan($block->ends_on) && $emailBlock->ends_on->greaterThan($block->starts_on)); + $superseded->each->delete(); + $fromEmails = $fromEmails->diff($superseded); + + array_push($conflicts, ...$this->conflictDetector->conflictsFor($block)); } $stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today)); @@ -101,30 +120,6 @@ public function handle(Channel $channel): ChannelSyncLog ]); } - /** - * Occupations from other sources that overlap the imported block. - * - * @return list - */ - private function conflictsFor(Channel $channel, BlockedPeriod $block): array - { - $property = $channel->property; - $imported = $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 => "{$channel->name} meldet {$imported}, ü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()) - ->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id)) - ->with('channel') - ->get() - ->map(fn (BlockedPeriod $other): string => "{$channel->name} meldet {$imported}, ü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()]; - } - private function elapsed(float $startedAt): int { return (int) round((microtime(true) - $startedAt) * 1000); diff --git a/app/Channels/ConflictDetector.php b/app/Channels/ConflictDetector.php new file mode 100644 index 0000000..b232122 --- /dev/null +++ b/app/Channels/ConflictDetector.php @@ -0,0 +1,36 @@ + 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()]; + } +} diff --git a/app/Channels/Mail/MailboxReader.php b/app/Channels/Mail/MailboxReader.php new file mode 100644 index 0000000..94b951f --- /dev/null +++ b/app/Channels/Mail/MailboxReader.php @@ -0,0 +1,94 @@ + $senders addresses or domains + * @return list + * + * @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(), + ); + } +} diff --git a/app/Channels/Mail/ParsedPortalMail.php b/app/Channels/Mail/ParsedPortalMail.php new file mode 100644 index 0000000..8789bed --- /dev/null +++ b/app/Channels/Mail/ParsedPortalMail.php @@ -0,0 +1,21 @@ +startsOn !== null && $this->endsOn !== null; + } +} diff --git a/app/Channels/Mail/PortalMail.php b/app/Channels/Mail/PortalMail.php new file mode 100644 index 0000000..5ca3396 --- /dev/null +++ b/app/Channels/Mail/PortalMail.php @@ -0,0 +1,19 @@ + 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 + */ + private function dates(string $content): array + { + $monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS))); + $patterns = [ + '/\b(?\d{1,2})\.(?\d{1,2})\.(?\d{4}|\d{2})\b/u', + '/\b(?\d{4})-(?\d{2})-(?\d{2})\b/u', + '/\b(?\d{1,2})\.?\s+(?'.$monthNames.')\.?\s+(?\d{4})\b/iu', + '/\b(?'.$monthNames.')\.?\s+(?\d{1,2}),?\s+(?\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 $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 $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 $needles + */ + private function containsAny(string $haystack, array $needles): bool + { + foreach ($needles as $needle) { + if (str_contains($haystack, $needle)) { + return true; + } + } + + return false; + } +} diff --git a/app/Console/Commands/FetchPortalMail.php b/app/Console/Commands/FetchPortalMail.php new file mode 100644 index 0000000..90c1b4e --- /dev/null +++ b/app/Console/Commands/FetchPortalMail.php @@ -0,0 +1,56 @@ +line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).'); + + return self::SUCCESS; + } + + $senders = Channel::query()->active()->get() + ->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel)) + ->unique() + ->values() + ->all(); + + if ($senders === []) { + $this->line('Für kein Portal sind Absender hinterlegt.'); + + return self::SUCCESS; + } + + try { + $mails = $reader->fetch($senders); + } catch (ChannelSyncException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + foreach ($mails as $mail) { + if ($record = $processPortalMail->handle($mail)) { + $this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})"); + } + } + + return self::SUCCESS; + } +} diff --git a/app/Enums/PortalEmailStatus.php b/app/Enums/PortalEmailStatus.php new file mode 100644 index 0000000..c180622 --- /dev/null +++ b/app/Enums/PortalEmailStatus.php @@ -0,0 +1,43 @@ + 'Gesperrt', + self::AlreadyKnown => 'Bereits gesperrt', + self::Released => 'Freigegeben', + self::NeedsReview => 'Bitte prüfen', + self::Reviewed => 'Geprüft', + self::Ignored => 'Ignoriert', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Blocked, self::Released => 'success', + self::AlreadyKnown, self::Reviewed, self::Ignored => 'gray', + self::NeedsReview => 'danger', + }; + } +} diff --git a/app/Enums/PortalEmailType.php b/app/Enums/PortalEmailType.php new file mode 100644 index 0000000..5728e9f --- /dev/null +++ b/app/Enums/PortalEmailType.php @@ -0,0 +1,23 @@ + 'Buchung', + self::Cancellation => 'Stornierung', + self::Inquiry => 'Anfrage', + self::Unknown => 'Unbekannt', + }; + } +} diff --git a/app/Filament/Resources/PortalEmails/Pages/ListPortalEmails.php b/app/Filament/Resources/PortalEmails/Pages/ListPortalEmails.php new file mode 100644 index 0000000..e50e539 --- /dev/null +++ b/app/Filament/Resources/PortalEmails/Pages/ListPortalEmails.php @@ -0,0 +1,11 @@ +where('status', PortalEmailStatus::NeedsReview)->count(); + + return $review > 0 ? (string) $review : null; + } + + public static function getNavigationBadgeColor(): string + { + return 'danger'; + } + + public static function getPages(): array + { + return [ + 'index' => ListPortalEmails::route('/'), + ]; + } +} diff --git a/app/Filament/Resources/PortalEmails/Tables/PortalEmailsTable.php b/app/Filament/Resources/PortalEmails/Tables/PortalEmailsTable.php new file mode 100644 index 0000000..17b1c66 --- /dev/null +++ b/app/Filament/Resources/PortalEmails/Tables/PortalEmailsTable.php @@ -0,0 +1,66 @@ +defaultSort('received_at', 'desc') + ->description('Buchungs-E-Mails der Portale werden jede Minute gelesen. Erkannte Buchungen werden sofort gesperrt; unklare E-Mails bitte prüfen.') + ->columns([ + TextColumn::make('received_at')->label('Eingang')->dateTime('d.m. H:i')->sortable(), + TextColumn::make('channel.name')->label('Portal'), + TextColumn::make('type')->label('Art')->badge(), + TextColumn::make('status')->label('Ergebnis')->badge()->description(fn (PortalEmail $record): ?string => $record->note), + TextColumn::make('period')->label('Zeitraum')->state(fn (PortalEmail $record): ?string => $record->period())->placeholder('–'), + TextColumn::make('reference')->label('Buchungsnr.')->placeholder('–'), + TextColumn::make('subject')->label('Betreff')->limit(50)->tooltip(fn (PortalEmail $record): ?string => $record->excerpt), + ]) + ->filters([ + SelectFilter::make('status')->label('Ergebnis')->options(PortalEmailStatus::class), + ]) + ->recordActions([ + Action::make('block') + ->label('Sperre anlegen') + ->icon(Heroicon::OutlinedLockClosed) + ->color('danger') + ->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview) + ->fillForm(fn (PortalEmail $record): array => ['starts_on' => $record->starts_on, 'ends_on' => $record->ends_on]) + ->schema([ + DatePicker::make('starts_on')->label('Anreise')->required(), + DatePicker::make('ends_on')->label('Abreise')->after('starts_on')->required(), + ]) + ->action(function (PortalEmail $record, array $data): void { + $block = $record->channel->blockedPeriods()->create([ + 'property_id' => $record->channel->property_id, + 'starts_on' => $data['starts_on'], + 'ends_on' => $data['ends_on'], + 'reason' => "{$record->channel->name} (E-Mail, geprüft)".($record->reference ? ": {$record->reference}" : ''), + 'source' => 'email', + 'external_uid' => 'email:'.($record->reference ?? $record->message_id), + ]); + $record->update(['status' => PortalEmailStatus::Blocked, 'blocked_period_id' => $block->id, 'starts_on' => $data['starts_on'], 'ends_on' => $data['ends_on']]); + + Notification::make()->title('Zeitraum gesperrt')->success()->send(); + }), + Action::make('reviewed') + ->label('Als geprüft markieren') + ->icon(Heroicon::OutlinedCheck) + ->color('gray') + ->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview) + ->action(fn (PortalEmail $record) => $record->update(['status' => PortalEmailStatus::Reviewed])), + ]); + } +} diff --git a/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php index 5ff6dbb..0abd3d0 100644 --- a/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php +++ b/app/Filament/Resources/Properties/RelationManagers/ChannelsRelationManager.php @@ -63,6 +63,11 @@ public function form(Schema $schema): Schema ->copyable() ->visible(fn (?Channel $record): bool => $record !== null) ->columnSpanFull(), + TextInput::make('settings.email_senders') + ->label('Absender der Buchungs-E-Mails (Schnellerkennung)') + ->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.') + ->maxLength(500) + ->columnSpanFull(), Toggle::make('requires_manual_blocking') ->label('Zusätzlich von Hand sperren (Sofortbuchung)') ->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.') diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php index 525d036..848f41e 100644 --- a/app/Http/Controllers/ChannelController.php +++ b/app/Http/Controllers/ChannelController.php @@ -2,13 +2,19 @@ namespace App\Http\Controllers; +use App\Actions\MonitorChannels; +use App\Actions\ProcessPortalMail; use App\Channels\ICal\ICalFeed; +use App\Channels\Mail\MailboxReader; +use App\Channels\Mail\PortalMail; use App\Enums\ChannelTaskStatus; use App\Models\Channel; use App\Models\ChannelTask; +use Carbon\CarbonImmutable; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Cache; /** * Public endpoints of the channel synchronisation: export feeds for portals, the health check for @@ -40,24 +46,60 @@ public function health(Request $request): JsonResponse 'last_error' => $channel->last_error, ]); $openTasks = ChannelTask::query()->open()->count(); + $mailbox = [ + 'configured' => MailboxReader::isConfigured(), + 'ok' => ! MonitorChannels::mailboxIsStale(), + 'last_success_at' => Cache::get(MailboxReader::LAST_SUCCESS_KEY), + 'last_error' => Cache::get(MailboxReader::LAST_ERROR_KEY), + ]; - $ok = $channels->every(fn (array $channel): bool => $channel['ok']); + $ok = $channels->every(fn (array $channel): bool => $channel['ok']) && $mailbox['ok']; return response()->json([ 'status' => $ok ? 'ok' : 'degraded', 'open_tasks' => $openTasks, + 'mailbox' => $mailbox, 'channels' => $channels->values(), ], $ok ? 200 : 503); } + /** + * Push variant of the e-mail fast path, e.g. from an n8n IMAP trigger: + * JSON {message_id, from, subject, text, received_at}, signed like the automation webhook. + */ + public function portalMail(Request $request, ProcessPortalMail $processPortalMail): JsonResponse + { + $this->verifySignature($request); + + $data = $request->validate([ + 'message_id' => ['required', 'string', 'max:255'], + 'from' => ['required', 'string', 'max:255'], + 'subject' => ['required', 'string', 'max:500'], + 'text' => ['required', 'string', 'max:200000'], + 'received_at' => ['nullable', 'date'], + ]); + + $record = $processPortalMail->handle(new PortalMail( + messageId: $data['message_id'], + from: $data['from'], + subject: $data['subject'], + text: $data['text'], + receivedAt: isset($data['received_at']) ? CarbonImmutable::parse($data['received_at']) : CarbonImmutable::now(), + )); + + return response()->json([ + 'processed' => $record !== null, + 'type' => $record?->type->value, + 'status' => $record?->status->value, + ]); + } + /** * The automation reports a task as done. The raw body must be signed like the outgoing webhook. */ public function completeTask(Request $request, ChannelTask $task): JsonResponse { - $secret = config('fewo.automation.secret'); - $signature = (string) $request->header('X-Signature'); - abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403); + $this->verifySignature($request); if ($task->status === ChannelTaskStatus::Open) { $task->complete('Automatisierung'); @@ -65,4 +107,12 @@ public function completeTask(Request $request, ChannelTask $task): JsonResponse return response()->json(['status' => $task->status->value]); } + + private function verifySignature(Request $request): void + { + $secret = config('fewo.automation.secret'); + $signature = (string) $request->header('X-Signature'); + + abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403); + } } diff --git a/app/Mail/MailboxAlert.php b/app/Mail/MailboxAlert.php new file mode 100644 index 0000000..7610941 --- /dev/null +++ b/app/Mail/MailboxAlert.php @@ -0,0 +1,33 @@ +portalEmail->channel->name; + + return new Envelope( + subject: match ($this->portalEmail->status) { + PortalEmailStatus::Blocked => "{$channel}-Buchung erkannt und gesperrt: {$this->portalEmail->period()}", + PortalEmailStatus::Released => "{$channel}-Stornierung: {$this->portalEmail->period()} wieder frei", + default => "Bitte prüfen: E-Mail von {$channel}", + }, + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.portal-mail', + ); + } +} diff --git a/app/Models/PortalEmail.php b/app/Models/PortalEmail.php new file mode 100644 index 0000000..7da028a --- /dev/null +++ b/app/Models/PortalEmail.php @@ -0,0 +1,54 @@ + + */ + protected function casts(): array + { + return [ + 'type' => PortalEmailType::class, + 'status' => PortalEmailStatus::class, + 'received_at' => 'immutable_datetime', + 'starts_on' => 'immutable_date', + 'ends_on' => 'immutable_date', + ]; + } + + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } + + /** + * @return BelongsTo + */ + public function blockedPeriod(): BelongsTo + { + return $this->belongsTo(BlockedPeriod::class); + } + + public function period(): ?string + { + return $this->starts_on && $this->ends_on ? $this->starts_on->format('d.m.Y').' – '.$this->ends_on->format('d.m.Y') : null; + } +} diff --git a/app/Policies/PortalEmailPolicy.php b/app/Policies/PortalEmailPolicy.php new file mode 100644 index 0000000..276ecfd --- /dev/null +++ b/app/Policies/PortalEmailPolicy.php @@ -0,0 +1,13 @@ +=5.0.0", + "nesbot/carbon": "^2.62.1|^3.2.4", + "php": "^8.0.2", + "symfony/http-foundation": ">=2.8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5.10" + }, + "suggest": { + "symfony/mime": "Recomended for better extension support", + "symfony/var-dumper": "Usefull tool for debugging" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.0-dev" + } + }, + "autoload": { + "psr-4": { + "Webklex\\PHPIMAP\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Malte Goldenbaum", + "email": "github@webklex.com", + "role": "Developer" + } + ], + "description": "PHP IMAP client", + "homepage": "https://github.com/webklex/php-imap", + "keywords": [ + "imap", + "mail", + "php-imap", + "pop3", + "webklex" + ], + "support": { + "issues": "https://github.com/Webklex/php-imap/issues", + "source": "https://github.com/Webklex/php-imap/tree/6.2.0" + }, + "funding": [ + { + "url": "https://www.buymeacoffee.com/webklex", + "type": "custom" + }, + { + "url": "https://ko-fi.com/webklex", + "type": "ko_fi" + } + ], + "time": "2025-04-25T06:02:37+00:00" } ], "packages-dev": [ diff --git a/config/fewo.php b/config/fewo.php index 4497f1b..1a7c318 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -61,6 +61,21 @@ 'health_token' => env('FEWO_HEALTH_TOKEN'), ], + /* + | Mailbox that receives the portals' booking notifications (fast path for portal bookings). + | Read via IMAP every minute; messages are left unread. Empty host = disabled. + */ + 'mailbox' => [ + 'host' => env('FEWO_MAILBOX_HOST'), + 'port' => (int) env('FEWO_MAILBOX_PORT', 993), + 'encryption' => env('FEWO_MAILBOX_ENCRYPTION', 'ssl'), + 'username' => env('FEWO_MAILBOX_USERNAME'), + 'password' => env('FEWO_MAILBOX_PASSWORD'), + 'folder' => env('FEWO_MAILBOX_FOLDER', 'INBOX'), + 'lookback_days' => (int) env('FEWO_MAILBOX_LOOKBACK_DAYS', 3), + 'stale_after_minutes' => (int) env('FEWO_MAILBOX_STALE_AFTER_MINUTES', 15), + ], + /* | Optional external automation (e.g. a browser bot on a private server) that carries out | manual blocking tasks. Tasks are POSTed signed with HMAC-SHA256 of the body. diff --git a/database/migrations/2026_10_22_112327_create_portal_emails_table.php b/database/migrations/2026_10_22_112327_create_portal_emails_table.php new file mode 100644 index 0000000..5193c52 --- /dev/null +++ b/database/migrations/2026_10_22_112327_create_portal_emails_table.php @@ -0,0 +1,40 @@ +id(); + $table->foreignId('channel_id')->constrained()->cascadeOnDelete(); + $table->string('message_id')->unique(); + $table->string('from'); + $table->string('subject'); + $table->dateTime('received_at'); + $table->string('type'); + $table->string('status')->index(); + $table->date('starts_on')->nullable(); + $table->date('ends_on')->nullable(); + $table->string('reference')->nullable(); + $table->foreignId('blocked_period_id')->nullable()->constrained()->nullOnDelete(); + $table->text('excerpt')->nullable(); + $table->string('note')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('portal_emails'); + } +}; diff --git a/docs/PORTALE.md b/docs/PORTALE.md index 883750e..7686431 100644 --- a/docs/PORTALE.md +++ b/docs/PORTALE.md @@ -104,6 +104,8 @@ ## 4b. Umsetzung im System - **Portal-Aufgaben** (Admin › Vermietung › Portal-Aufgaben): entstehen automatisch bei Bestätigung/Stornierung von Buchungen, bei Sperrzeiten und bei Belegungen anderer Portale; Mail sofort, Erinnerung nach 2 Std. - **Status für n8n:** `GET /health/sync?token=…` (200 = ok, 503 = gestört) mit offenen Aufgaben und Zustand je Portal. - **Automatisierungs-Webhook (optional):** `FEWO_AUTOMATION_WEBHOOK_URL` + `FEWO_AUTOMATION_SECRET`; Aufgaben werden als JSON mit `X-Signature` (HMAC-SHA256) gesendet, Erledigung per signiertem POST an die mitgelieferte `callback_url`. +- **E-Mail-Schnellerkennung:** Buchungs-, Storno- und Anfrage-Mails der Portale (Absender je Portal hinterlegt, z. B. `fewo-direkt.de, vrbo.com`) werden jede Minute per IMAP gelesen (`channels:fetch-mail`, Mails bleiben ungelesen) oder per signiertem Push von n8n (`POST /automation/portal-mail`) übergeben. Erkannte Buchungen werden sofort gesperrt (Quelle „email“) und an manuell gepflegte Portale weitergegeben; der spätere Kalender-Abgleich übernimmt die Sperre (gleiche Daten) bzw. ersetzt sie (abweichende Daten). Stornierungs-Mails heben Mail-Sperren auf. Nicht sicher erkannte Mails → „Bitte prüfen“ mit Mail an den Vermieter und Aktion „Sperre anlegen“ im Admin (Vermietung › Portal-E-Mails). Postfach-Störungen werden wie Portal-Störungen gemeldet und im Status-Endpunkt angezeigt. +- **Zeitkette FeWo-direkt-Buchung:** E-Mail (≈ 1–2 Min.) bzw. Kalender (≤ 5 Min. + Bereitstellung durch FeWo-direkt) → Sperre auf unserer Webseite sofort → Feeds der anderen Portale sofort aktualisiert (Abholung durch das Portal in dessen Takt) → bei Portalen mit Handpflege zusätzlich Aufgabe + Mail. - **Herkunft** jeder Anfrage („Wie sind Sie auf uns aufmerksam geworden?“ + UTM-Parameter) wird an der Buchung gespeichert. ## 5. Offene Fragen an die Anbieter diff --git a/resources/views/mail/mailbox-alert.blade.php b/resources/views/mail/mailbox-alert.blade.php new file mode 100644 index 0000000..d6de63e --- /dev/null +++ b/resources/views/mail/mailbox-alert.blade.php @@ -0,0 +1,11 @@ + +# Postfach-Abruf gestört + +Die Buchungs-E-Mails der Portale konnten seit über {{ config('fewo.mailbox.stale_after_minutes') }} Minuten nicht gelesen werden. Neue Portalbuchungen werden bis dahin nur über den langsameren Kalender-Abgleich erkannt. + +@if ($lastError) +**Letzte Fehlermeldung:** {{ $lastError }} +@endif + +Häufige Ursachen: geändertes Passwort des Postfachs, Wartung beim E-Mail-Anbieter. + diff --git a/resources/views/mail/portal-mail.blade.php b/resources/views/mail/portal-mail.blade.php new file mode 100644 index 0000000..2c7acb8 --- /dev/null +++ b/resources/views/mail/portal-mail.blade.php @@ -0,0 +1,28 @@ + +# {{ $portalEmail->status->getLabel() }} + +Zur E-Mail von **{{ $portalEmail->channel->name }}** („{{ $portalEmail->subject }}“, eingegangen {{ $portalEmail->received_at->format('d.m.Y, H:i') }} Uhr): + +@switch($portalEmail->status) +@case(\App\Enums\PortalEmailStatus::Blocked) +Der Zeitraum **{{ $portalEmail->period() }}** ist jetzt auf unserer Webseite gesperrt und wird an die anderen Portale weitergegeben.@if ($portalEmail->reference) Buchungsnummer: {{ $portalEmail->reference }}.@endif + +Sobald der Kalender-Abgleich die Buchung ebenfalls meldet, wird die Sperre automatisch übernommen. +@break +@case(\App\Enums\PortalEmailStatus::Released) +Die Sperre für **{{ $portalEmail->period() }}** wurde aufgehoben. +@break +@default +{{ $portalEmail->note }} + +@if ($portalEmail->period()) +Erkannter Zeitraum: {{ $portalEmail->period() }} +@endif + +Bitte prüfen Sie die Buchung im Portal und legen Sie bei Bedarf eine Sperrzeit an. +@endswitch + + +Portal-E-Mails ansehen + + diff --git a/routes/console.php b/routes/console.php index 22ef2c3..e909f5e 100644 --- a/routes/console.php +++ b/routes/console.php @@ -10,6 +10,8 @@ Schedule::command('channels:sync')->everyFiveMinutes()->withoutOverlapping(10); +Schedule::command('channels:fetch-mail')->everyMinute()->withoutOverlapping(5); + Schedule::call(fn (MonitorChannels $monitorChannels) => $monitorChannels->handle()) ->name('channels:monitor') ->everyFifteenMinutes() diff --git a/routes/web.php b/routes/web.php index 894fc10..2379fbf 100644 --- a/routes/web.php +++ b/routes/web.php @@ -20,6 +20,10 @@ Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); Route::get('/health/sync', [ChannelController::class, 'health'])->name('health.sync'); +Route::post('/automation/portal-mail', [ChannelController::class, 'portalMail']) + ->name('channels.portal-mail') + ->withoutMiddleware(PreventRequestForgery::class) + ->middleware('throttle:60,1'); Route::post('/automation/aufgaben/{task}/erledigt', [ChannelController::class, 'completeTask']) ->name('channel-tasks.complete') ->withoutMiddleware(PreventRequestForgery::class) diff --git a/tests/Feature/PortalMailTest.php b/tests/Feature/PortalMailTest.php new file mode 100644 index 0000000..b966fc9 --- /dev/null +++ b/tests/Feature/PortalMailTest.php @@ -0,0 +1,210 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + $this->property = Property::sole(); + $this->fewo = Channel::factory()->for($this->property)->create([ + 'name' => 'FeWo-direkt', + 'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/x.ics', 'email_senders' => 'fewo-direkt.de, vrbo.com'], + ]); + Mail::fake(); + } + + /** + * @return array + */ + public static function mailProvider(): array + { + return [ + 'deutsche Buchung' => ['Neue Buchung: Ferienwohnung Stommer', self::BOOKING_MAIL, PortalEmailType::Booking, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'], + 'englische Buchung' => ['Booking confirmed – Instant Booking', "Check-in: Nov 7, 2026\nCheck-out: Nov 10, 2026\nReservation ID: HA-ABCDE1", PortalEmailType::Booking, '2026-11-07', '2026-11-10', 'HA-ABCDE1'], + 'numerische Daten' => ['Buchungsbestätigung', 'Ihr Gast reist vom 07.11.2026 bis zum 10.11.2026 an.', PortalEmailType::Booking, '2026-11-07', '2026-11-10', null], + 'Anfrage ist keine Buchung' => ['Neue Buchungsanfrage von Max', self::BOOKING_MAIL, PortalEmailType::Inquiry, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'], + 'Stornierung' => ['Buchung storniert: HA-7X3K9Q', 'Die Buchung vom 07.11.2026 bis 10.11.2026 wurde storniert.', PortalEmailType::Cancellation, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'], + 'unbekannt' => ['Ihr monatlicher Bericht', 'Statistik für Oktober 2026', PortalEmailType::Unknown, null, null, null], + ]; + } + + #[DataProvider('mailProvider')] + public function test_parser_recognises_portal_mails(string $subject, string $text, PortalEmailType $type, ?string $arrival, ?string $departure, ?string $reference): void + { + $parsed = (new PortalMailParser)->parse($subject, $text); + + $this->assertSame([$type, $arrival, $departure, $reference], [$parsed->type, $parsed->startsOn?->toDateString(), $parsed->endsOn?->toDateString(), $parsed->reference]); + } + + public function test_booking_mail_blocks_immediately_and_informs_other_manual_portals(): void + { + $ostseeklar = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true]); + + $record = $this->process('Neue Buchung', self::BOOKING_MAIL); + + $this->assertSame(PortalEmailStatus::Blocked, $record->status); + $block = $this->fewo->blockedPeriods()->sole(); + $this->assertSame(['email', '2026-11-07', '2026-11-10', 'email:HA-7X3K9Q'], [$block->source, $block->starts_on->toDateString(), $block->ends_on->toDateString(), $block->external_uid]); + $this->assertSame(ChannelTaskAction::Block, $ostseeklar->tasks()->sole()->action); + Mail::assertSent(PortalMailNotification::class); + + $this->assertNull($this->process('Neue Buchung', self::BOOKING_MAIL), 'same message is processed only once'); + $this->assertSame(PortalEmailStatus::AlreadyKnown, $this->process('Neue Buchung', self::BOOKING_MAIL, 'other-id')->status); + $this->assertNull($this->process('Neue Buchung', self::BOOKING_MAIL, 'x', 'news@unbekannt.de')); + } + + public function test_overlap_with_an_existing_booking_raises_a_conflict(): void + { + Booking::factory()->for($this->property)->create(['arrival' => '2026-11-09', 'departure' => '2026-11-12', 'status' => BookingStatus::Confirmed]); + + $this->process('Neue Buchung', self::BOOKING_MAIL); + + Mail::assertSent(ChannelConflict::class); + } + + public function test_calendar_sync_confirms_the_mail_block_without_creating_new_tasks(): void + { + Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true]); + $this->process('Neue Buchung', self::BOOKING_MAIL); + $tasksBefore = ChannelTask::count(); + + $this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261110"); + (new SyncChannel)->handle($this->fewo); + + $block = $this->fewo->blockedPeriods()->sole(); + $this->assertSame(['channel', 'vrbo-123'], [$block->source, $block->external_uid]); + $this->assertSame($tasksBefore, ChannelTask::count()); + } + + public function test_calendar_entry_with_other_dates_replaces_the_mail_block(): void + { + $this->process('Neue Buchung', self::BOOKING_MAIL); + + $this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261111"); + (new SyncChannel)->handle($this->fewo); + + $this->assertSame(['channel', '2026-11-11'], [$this->fewo->blockedPeriods()->sole()->source, $this->fewo->blockedPeriods()->sole()->ends_on->toDateString()]); + } + + public function test_mail_blocks_survive_a_calendar_sync_that_does_not_know_them_yet(): void + { + $this->process('Neue Buchung', self::BOOKING_MAIL); + + $this->fakeFeed(''); + (new SyncChannel)->handle($this->fewo); + + $this->assertSame(1, $this->fewo->blockedPeriods()->count()); + } + + public function test_cancellation_releases_the_mail_block(): void + { + $this->process('Neue Buchung', self::BOOKING_MAIL); + + $record = $this->process('Buchung storniert: HA-7X3K9Q', 'Die Buchung wurde storniert.', 'cancel-1'); + + $this->assertSame(PortalEmailStatus::Released, $record->status); + $this->assertSame(0, $this->fewo->blockedPeriods()->count()); + } + + public function test_booking_without_readable_dates_needs_review_and_can_be_blocked_in_the_admin(): void + { + $record = $this->process('Neue Buchung', 'Details finden Sie in Ihrem Vermieterkonto.'); + + $this->assertSame(PortalEmailStatus::NeedsReview, $record->status); + $this->assertSame(0, $this->fewo->blockedPeriods()->count()); + Mail::assertSent(PortalMailNotification::class); + + $this->actingAs(User::factory()->create()); + Livewire::test(ListPortalEmails::class) + ->assertCanSeeTableRecords([$record]) + ->callTableAction('block', $record, ['starts_on' => '2026-11-20', 'ends_on' => '2026-11-23']); + + $this->assertSame(PortalEmailStatus::Blocked, $record->fresh()->status); + $this->assertSame('2026-11-20', $this->fewo->blockedPeriods()->sole()->starts_on->toDateString()); + } + + public function test_n8n_can_push_mails_with_a_signed_request(): void + { + config(['fewo.automation.secret' => 'geheim']); + $body = json_encode(['message_id' => 'n8n-1', 'from' => 'noreply@fewo-direkt.de', 'subject' => 'Neue Buchung', 'text' => self::BOOKING_MAIL]); + + $this->call('POST', route('channels.portal-mail'), [], [], [], ['HTTP_X-Signature' => 'falsch', 'CONTENT_TYPE' => 'application/json'], $body)->assertForbidden(); + $this->call('POST', route('channels.portal-mail'), [], [], [], ['HTTP_X-Signature' => hash_hmac('sha256', $body, 'geheim'), 'CONTENT_TYPE' => 'application/json'], $body) + ->assertOk() + ->assertJson(['processed' => true, 'type' => 'booking', 'status' => 'blocked']); + + $this->assertSame(1, PortalEmail::count()); + } + + public function test_mailbox_outage_is_alerted_once(): void + { + config(['fewo.mailbox.host' => 'imap.strato.de', 'fewo.mailbox.username' => 'fewo@stommer.de']); + + $this->fewo->update(['settings' => ['email_senders' => 'fewo-direkt.de']]); + + $this->assertSame(1, (new MonitorChannels)->handle()); + $this->assertSame(0, (new MonitorChannels)->handle()); + Mail::assertSent(MailboxAlert::class, 1); + } + + private function process(string $subject, string $text, string $messageId = 'msg-1', string $from = 'noreply@fewo-direkt.de'): ?PortalEmail + { + return app(ProcessPortalMail::class)->handle(new PortalMail($messageId, $from, $subject, $text, CarbonImmutable::now())); + } + + private function fakeFeed(string $event): void + { + $body = "BEGIN:VCALENDAR\r\n".($event !== '' ? "BEGIN:VEVENT\r\n{$event}\r\nEND:VEVENT\r\n" : '').'END:VCALENDAR'; + Http::fake(['*' => Http::response($body)]); + } +}