Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las. Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben. `App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst führen: - `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder* Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten Dienst auf. - `Channel::importsOccupations()` – Import und Scheduler. - Der öffentliche iCal-Feed antwortet mit 404. - `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg. `TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da, bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber- Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es soweit ist (A16). Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste. Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei, damit der Umbau laufenden Betrieb nicht stillschweigend stoppt. 240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
174 lines
6.6 KiB
PHP
174 lines
6.6 KiB
PHP
<?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\Enums\TenantServiceKey;
|
||
use App\Mail\ChannelConflict;
|
||
use App\Mail\PortalMailNotification;
|
||
use App\Models\BlockedPeriod;
|
||
use App\Models\Channel;
|
||
use App\Models\PortalEmail;
|
||
use App\Support\Settings;
|
||
use App\Tenancy\TenantFeatures;
|
||
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,
|
||
]);
|
||
});
|
||
|
||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
||
}
|
||
|
||
if ($conflicts !== []) {
|
||
rescue(fn () => Mail::to(Settings::notificationRecipients())->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.'];
|
||
}
|
||
}
|