Files
fewo-stommer/app/Actions/ProcessPortalMail.php
T
LarsandClaude Sonnet 5.5 8442d0a3d8 V2.1: Kanalfähigkeiten, Ausführungsvarianten, Dokumentenentkopplung, Portalbestätigung
Modellwahl über Kanalfähigkeiten mit erklärten Einschränkungen, Abgleich alter Werte,
Ausführungsvarianten je Modul, getrennte Vertrags-/Buchungsinformation, Warten auf
die Portalbestätigung mit Eskalation und Wiederaufnahme (Fälle C und D getestet).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:54:11 +01:00

229 lines
9.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Actions;
use App\Channels\ConflictDetector;
use App\Channels\Intake\PortalIntake;
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\Enums\TenantServiceKey;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\IntakeObservation;
use App\Models\PortalEmail;
use App\Process\ProcessRunner;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Carbon\CarbonInterface;
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;
}
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
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,
]);
});
// One intake for all channels (package 4): bookings, requests and cancellations reach their case.
rescue(fn () => $this->intake($channel, $parsed, $record));
rescue(fn () => $this->resume($channel, $parsed, $record));
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
}
if ($conflicts !== []) {
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
}
return $record;
}
/**
* A booking mail of the portal can be the confirmation a case waits for (V2.1, docs/Prozessarchitektur/V2.1/02 §5): the
* case is evaluated again. Only cases whose channel makes them wait are touched – everything else stays as it was.
*/
private function resume(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{
if ($parsed->type !== PortalEmailType::Booking) {
return;
}
$case = $record->blocked_period_id !== null ? Booking::query()->find(BlockedPeriod::withTrashed()->whereKey($record->blocked_period_id)->value('linked_booking_id')) : null;
$case ??= $parsed->reference !== null ? app(PortalIntake::class)->caseByReference($channel, $parsed->reference) : null;
if ($case !== null && $case->isBinding() && $case->process()->awaitsPortalConfirmation()) {
app(ProcessRunner::class)->advance($case, 'portal.mail');
}
}
private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{
$intake = app(PortalIntake::class);
match ($parsed->type) {
PortalEmailType::Booking => $record->blocked_period_id !== null ? $intake->process(BlockedPeriod::query()->findOrFail($record->blocked_period_id), IntakeObservation::SOURCE_MAIL) : null,
PortalEmailType::Cancellation => $intake->cancellationMail($channel, $parsed, $record),
PortalEmailType::Inquiry => $intake->inquiryMail($channel, $parsed, $record),
PortalEmailType::Unknown => null,
};
}
/**
* 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);
$matches = Channel::query()->active()->get()->filter(function (Channel $channel) use ($from): bool {
foreach ($this->senders($channel) as $sender) {
if (str_contains($from, $sender)) {
return true;
}
}
return false;
});
if ($matches->count() > 1) {
foreach ($matches as $channel) {
$channel->forceFill(['sync_warnings' => array_values(array_unique([
...($channel->sync_warnings ?? []), 'Portal-Mail-Absender passt zu mehreren Kanälen. Keine automatische Wohnungszuordnung vorgenommen.',
]))])->saveQuietly();
}
}
return $matches->count() === 1 ? $matches->first() : null;
}
/**
* @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 array<string, CarbonInterface> $conflicts description => first night
* @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 = $parsed->reference === null ? null : $channel->blockedPeriods()
->whereIn('external_uid', ['email:'.$parsed->reference, $parsed->reference])->first();
if ($known) {
if ($known->source === 'email') {
$known->update(['starts_on' => $parsed->startsOn->toDateString(), 'ends_on' => $parsed->endsOn->toDateString()]);
}
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 ?? bin2hex(random_bytes(16))),
]);
if ($channel->blockedPeriods()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists()) {
$block->forceFill(['needs_review' => true, 'review_note' => 'Überlappende Portalrepräsentationen ohne gemeinsame Kennung persönlich prüfen.'])->saveQuietly();
}
$conflicts = array_fill_keys($this->conflictDetector->conflictsFor($block), $block->starts_on);
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(),
default => null,
};
// A block that belongs to a case is never released by a mail: the case leads, the landlord decides (E-019).
if ($block && $block->linked_booking_id !== null) {
return [PortalEmailStatus::NeedsReview, $block, 'Stornierung zu einem gebuchten Vorgang gemeldet – nichts automatisch freigegeben; Aufgabe am Vorgang prüfen.'];
}
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.'];
}
}