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:
1 parent
0b7205e050
commit
e5f9e0762f
33 files changed
+1450
-38
No files matched your search
@@ -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
|
||||
@@ -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`.
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\Mail\ParsedPortalMail;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Fast path for portal bookings: the notification e-mail usually arrives within a minute, long before
|
||||
* the portal's calendar export is read. A recognised booking is blocked immediately; the later calendar
|
||||
* sync confirms the block. Anything not recognised with confidence is flagged for review – never guessed.
|
||||
*/
|
||||
class ProcessPortalMail
|
||||
{
|
||||
public function __construct(
|
||||
private PortalMailParser $parser,
|
||||
private ConflictDetector $conflictDetector,
|
||||
) {}
|
||||
|
||||
public function handle(PortalMail $mail): ?PortalEmail
|
||||
{
|
||||
if (PortalEmail::where('message_id', $mail->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<string>
|
||||
*/
|
||||
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<string> $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.'];
|
||||
}
|
||||
}
|
||||
+22
-27
@@ -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<string>
|
||||
*/
|
||||
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);
|
||||
|
||||
@@ -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()];
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
) {}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:fetch-mail')]
|
||||
#[Description('Read booking notifications of the portals from the mailbox and block recognised bookings immediately')]
|
||||
class FetchPortalMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** A new block was created from the e-mail. */
|
||||
case Blocked = 'blocked';
|
||||
|
||||
/** The period was already blocked (e.g. by the calendar sync). */
|
||||
case AlreadyKnown = 'already_known';
|
||||
|
||||
/** A cancellation released a block created from an e-mail. */
|
||||
case Released = 'released';
|
||||
|
||||
case NeedsReview = 'needs_review';
|
||||
case Reviewed = 'reviewed';
|
||||
case Ignored = 'ignored';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blocked => '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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailType: string implements HasLabel
|
||||
{
|
||||
case Booking = 'booking';
|
||||
case Cancellation = 'cancellation';
|
||||
case Inquiry = 'inquiry';
|
||||
case Unknown = 'unknown';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Booking => 'Buchung',
|
||||
self::Cancellation => 'Stornierung',
|
||||
self::Inquiry => 'Anfrage',
|
||||
self::Unknown => 'Unbekannt',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails\Pages;
|
||||
|
||||
use App\Filament\Resources\PortalEmails\PortalEmailResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPortalEmails extends ListRecords
|
||||
{
|
||||
protected static string $resource = PortalEmailResource::class;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
|
||||
use App\Filament\Resources\PortalEmails\Tables\PortalEmailsTable;
|
||||
use App\Models\PortalEmail;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class PortalEmailResource extends Resource
|
||||
{
|
||||
protected static ?string $model = PortalEmail::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelopeOpen;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal-E-Mail';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portal-E-Mails';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return PortalEmailsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$review = PortalEmail::query()->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('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails\Tables;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Models\PortalEmail;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class PortalEmailsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->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])),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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.')
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Alerts the landlord that portal notification e-mails cannot be read any more.
|
||||
*/
|
||||
class MailboxAlert extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public ?string $lastError) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Postfach-Abruf gestört: Portal-Buchungen werden nur noch über den Kalender erkannt',
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.mailbox-alert',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Models\PortalEmail;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Tells the landlord what was done with a portal notification e-mail.
|
||||
*/
|
||||
class PortalMailNotification extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public PortalEmail $portalEmail) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
$channel = $this->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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A notification e-mail of a portal (e.g. "new booking" from FeWo-direkt) and what the system did with it.
|
||||
* Only a short excerpt is stored, not the whole e-mail.
|
||||
*/
|
||||
#[Fillable(['channel_id', 'message_id', 'from', 'subject', 'received_at', 'type', 'status', 'starts_on', 'ends_on', 'reference', 'blocked_period_id', 'excerpt', 'note'])]
|
||||
class PortalEmail extends Model
|
||||
{
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<BlockedPeriod, $this>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
|
||||
class PortalEmailPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
{
|
||||
return [UserRole::Rentals];
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -11,7 +11,8 @@
|
||||
"filament/filament": "^5.10",
|
||||
"filament/spatie-laravel-media-library-plugin": "^5.0",
|
||||
"laravel/framework": "^13.17",
|
||||
"laravel/tinker": "^3.0"
|
||||
"laravel/tinker": "^3.0",
|
||||
"webklex/php-imap": "^6.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
|
||||
Generated
+82
-1
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "1f5e3ea95226f9ee49c3baddc64e655e",
|
||||
"content-hash": "7ac2d219fe91e076aad564e1649fac54",
|
||||
"packages": [
|
||||
{
|
||||
"name": "anourvalar/eloquent-serialize",
|
||||
@@ -9285,6 +9285,87 @@
|
||||
}
|
||||
],
|
||||
"time": "2026-04-26T05:33:54+00:00"
|
||||
},
|
||||
{
|
||||
"name": "webklex/php-imap",
|
||||
"version": "6.2.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Webklex/php-imap.git",
|
||||
"reference": "6b8ef85d621bbbaf52741b00cca8e9237e2b2e05"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/Webklex/php-imap/zipball/6b8ef85d621bbbaf52741b00cca8e9237e2b2e05",
|
||||
"reference": "6b8ef85d621bbbaf52741b00cca8e9237e2b2e05",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-fileinfo": "*",
|
||||
"ext-iconv": "*",
|
||||
"ext-json": "*",
|
||||
"ext-libxml": "*",
|
||||
"ext-mbstring": "*",
|
||||
"ext-openssl": "*",
|
||||
"ext-zip": "*",
|
||||
"illuminate/pagination": ">=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": [
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('portal_emails', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<x-mail::message>
|
||||
# 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.
|
||||
</x-mail::message>
|
||||
@@ -0,0 +1,28 @@
|
||||
<x-mail::message>
|
||||
# {{ $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
|
||||
|
||||
<x-mail::button :url="\App\Filament\Resources\PortalEmails\PortalEmailResource::getUrl('index')">
|
||||
Portal-E-Mails ansehen
|
||||
</x-mail::button>
|
||||
</x-mail::message>
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\MonitorChannels;
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\MailboxAlert;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Livewire\Livewire;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PortalMailTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const BOOKING_MAIL = <<<'TXT'
|
||||
Hallo Brigitte,
|
||||
gute Nachrichten! Sie haben eine neue Buchung erhalten.
|
||||
Gast: Max Mustermann
|
||||
Anreise: Sa., 7. Nov. 2026
|
||||
Abreise: Di., 10. Nov. 2026
|
||||
Reisende: 2 Erwachsene
|
||||
Buchungsnummer: HA-7X3K9Q
|
||||
Ihr FeWo-direkt Team
|
||||
TXT;
|
||||
|
||||
private Property $property;
|
||||
|
||||
private Channel $fewo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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<string, array{string, string, PortalEmailType, ?string, ?string, ?string}>
|
||||
*/
|
||||
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)]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user