v0.11 U5: Posteingang, deterministische Zuordnung, Klärungsansicht
- mailboxes (Modell für mehrere, eines aktiv): Übernahme des bisherigen Postfachs als „nur Portal-Mails“; Modus „alle Nachrichten“ für ein eigenes Postfach; Adresse als Antwortadresse der Rückfragen. - inbound_messages: jede Nachricht zuerst gespeichert, einmal je Message-ID, mit Testbetriebs-Kennzeichen (M10). Portal-Mails laufen unverändert über den Portalpfad (CH-08). - MessageMatcher (CH-13, ohne Scoring): Antwortbezug; Vorgangsnummer nur mit dem Gast als Absender; sonst Absender + Wohnung + beide Termine eines einzigen offenen Vorgangs. Ein offener Vorgang des Absenders allein genügt nicht (nur Hinweis). Alles andere → Klärung (M04). - Ausgehende Mails speichern ihre Message-ID; Antwort stoppt Erinnerungen. - Filament „Posteingang“: lesen, Vorgang zuordnen, als neue Anfrage anlegen, ignorieren, erledigt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e4a3cb7f7b
commit
dff9e2344e
19 files changed
+990
-59
No files matched your search
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Communication\MessageMatcher;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Mailbox;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
|
||||
/**
|
||||
* The inbox of v0.11 (S2/S3, CH-01, CH-06, CH-08): every message of the landlord's dedicated mailbox is stored first,
|
||||
* once per Message-ID. Booking notifications of the portals go unchanged through the existing portal path; every other
|
||||
* message is assigned to a case by the deterministic rules or waits in the inbox for the landlord. A message never
|
||||
* creates a case by itself. An assigned reply stops the reminders of the case's data request; its details are taken
|
||||
* over only through the extraction and the common fact intake.
|
||||
*/
|
||||
class ReceiveInboundMessage
|
||||
{
|
||||
public function __construct(private ProcessPortalMail $portalMail, private MessageMatcher $matcher, private RequestCaseData $requests) {}
|
||||
|
||||
public function handle(PortalMail $mail, ?Mailbox $mailbox = null): InboundMessage
|
||||
{
|
||||
$existing = InboundMessage::query()->where('message_id', $mail->messageId)->first();
|
||||
if ($existing !== null) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
try {
|
||||
$message = InboundMessage::query()->create([
|
||||
'mailbox_id' => $mailbox?->id,
|
||||
'message_id' => $mail->messageId,
|
||||
'in_reply_to' => $mail->inReplyTo,
|
||||
'references' => $mail->references,
|
||||
'from_address' => mb_strtolower($mail->from),
|
||||
'from_name' => $mail->fromName,
|
||||
'to_addresses' => $mail->to,
|
||||
'subject' => mb_substr($mail->subject, 0, 500),
|
||||
'body' => $mail->text,
|
||||
'received_at' => $mail->receivedAt,
|
||||
// CH §5 / M10: what arrives in test operation is marked as such.
|
||||
'test_mode' => ! Settings::isLive(),
|
||||
'status' => InboundMessage::NEW,
|
||||
]);
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
return InboundMessage::query()->where('message_id', $mail->messageId)->firstOrFail();
|
||||
}
|
||||
|
||||
if ($this->portalMail->channelFor($mail->from) !== null) {
|
||||
// A portal's notification: the existing portal path decides, unchanged (CH-08).
|
||||
$record = $this->portalMail->handle($mail);
|
||||
$record?->forceFill(['inbound_message_id' => $message->id])->save();
|
||||
$message->update(['status' => InboundMessage::PORTAL, 'portal_email_id' => $record?->id, 'processed_at' => now()]);
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
if ($this->isOwn($mail, $mailbox)) {
|
||||
$message->update(['status' => InboundMessage::IGNORED, 'match_reason' => 'own', 'processed_at' => now()]);
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
$match = $this->matcher->match($message);
|
||||
if ($match['booking'] === null) {
|
||||
$message->update(['status' => InboundMessage::NEEDS_REVIEW, 'hints' => $match['hints']]);
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
$booking = $match['booking'];
|
||||
$message->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => $match['reason']]);
|
||||
CaseLog::record($booking, 'mail_in', 'E-Mail des Gastes eingegangen'.($message->test_mode ? ' (im Testbetrieb)' : '').': '.$message->subject, actor: CaseLog::GUEST, at: $message->received_at);
|
||||
$this->requests->replyReceived($booking);
|
||||
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – im Posteingang ansehen; erkannte Angaben werden dort zur Übernahme vorgeschlagen.']);
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Our own mails (copies, loops) are not guest messages.
|
||||
*/
|
||||
private function isOwn(PortalMail $mail, ?Mailbox $mailbox): bool
|
||||
{
|
||||
$own = array_filter(array_map(fn (?string $address): string => mb_strtolower(trim((string) $address)), [
|
||||
$mailbox?->address, config('mail.from.address'), Settings::tenant()?->sender_email,
|
||||
]));
|
||||
|
||||
return in_array(mb_strtolower($mail->from), $own, true);
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,14 @@ public function answered(Booking $booking, FactContribution $contribution, FactS
|
||||
return;
|
||||
}
|
||||
|
||||
if ($source->isAuthoritative() && $request->status === DataRequest::OPEN && $request->next_reminder_at === null && $request->followups_sent < $booking->process()->followupsMax()) {
|
||||
// The landlord took over the guest's e-mail answer and something is still missing: a follow-up question is
|
||||
// prepared for his release.
|
||||
$request->forceFill(['status' => DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP, 'fields' => $needs['fields']])->save();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($source->isAuthoritative() || $request->status !== DataRequest::OPEN || (! $contribution->anyApplied() && ! $contribution->needsReview())) {
|
||||
$request->update(['fields' => $needs['fields']]);
|
||||
|
||||
@@ -243,6 +251,21 @@ public function answered(Booking $booking, FactContribution $contribution, FactS
|
||||
CaseLog::record($booking, 'data_request', 'Antwort unvollständig – Folgefrage vorbereitet: '.implode(', ', CaseRequirements::labels($needs['fields'])), actor: CaseLog::SYSTEM);
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply of the guest arrived (assigned by the inbox): the open reminder is cancelled (CH-17). What it says is
|
||||
* taken over only through the extraction and the fact intake.
|
||||
*/
|
||||
public function replyReceived(Booking $booking): void
|
||||
{
|
||||
$request = $booking->openDataRequest();
|
||||
if ($request?->status !== DataRequest::OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null])->save();
|
||||
CaseLog::record($booking, 'data_request', 'Antwort des Gastes per E-Mail – Erinnerungen ruhen', actor: CaseLog::SYSTEM);
|
||||
}
|
||||
|
||||
/**
|
||||
* Due reminders of every running request (scheduler). At the limit the landlord takes over; nothing changes any
|
||||
* deadline of the case.
|
||||
|
||||
@@ -98,6 +98,48 @@ public function fetch(array $senders): array
|
||||
return $mails;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every message of the last days (v0.11 inbox, mailbox mode "full"), left unread. Deduplication happens when the
|
||||
* messages are stored.
|
||||
*
|
||||
* @return list<PortalMail>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetchAll(): array
|
||||
{
|
||||
$config = self::configuration();
|
||||
if ($config === null) {
|
||||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||||
}
|
||||
|
||||
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();
|
||||
$messages = $client->getFolderByPath($config['folder'])->query()
|
||||
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||||
->leaveUnread()
|
||||
->get();
|
||||
$mails = [];
|
||||
foreach ($messages as $message) {
|
||||
$mails[] = $this->toPortalMail($message);
|
||||
}
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
|
||||
|
||||
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||||
}
|
||||
|
||||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
private function toPortalMail(Message $message): PortalMail
|
||||
{
|
||||
$text = $message->getTextBody();
|
||||
@@ -108,12 +150,18 @@ private function toPortalMail(Message $message): PortalMail
|
||||
$from = $message->getFrom()->first();
|
||||
$date = $message->getDate()->first();
|
||||
|
||||
$references = preg_split('/\s+/', trim((string) $message->getReferences()?->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(),
|
||||
inReplyTo: ($reply = trim((string) $message->getInReplyTo()?->first())) !== '' ? $reply : null,
|
||||
references: array_values(array_filter($references)),
|
||||
to: collect($message->getTo()?->all() ?? [])->map(fn ($address): string => mb_strtolower((string) ($address->mail ?? '')))->filter()->values()->all(),
|
||||
fromName: filled($from->personal ?? null) ? (string) $from->personal : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,24 @@
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
|
||||
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook. The reply references, recipients and the
|
||||
* sender's name are only filled when the whole mailbox is read (v0.11 inbox).
|
||||
*/
|
||||
final readonly class PortalMail
|
||||
{
|
||||
/**
|
||||
* @param list<string> $references
|
||||
* @param list<string> $to
|
||||
*/
|
||||
public function __construct(
|
||||
public string $messageId,
|
||||
public string $from,
|
||||
public string $subject,
|
||||
public string $text,
|
||||
public CarbonImmutable $receivedAt,
|
||||
public ?string $inReplyTo = null,
|
||||
public array $references = [],
|
||||
public array $to = [],
|
||||
public ?string $fromName = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Communication;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingMessage;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Deterministic assignment of an incoming message to a case (v0.11, CH-07, CH-13) – no scoring. A message is
|
||||
* assigned only by
|
||||
*
|
||||
* 1. a known reply reference (In-Reply-To / References of one of our mails),
|
||||
* 2. our case number together with the case's guest as sender (the number alone is no proof of identity), or
|
||||
* 3. the combination of sender (the guest's e-mail), property and both dates of exactly one open case of that guest.
|
||||
*
|
||||
* One open case of the same sender alone is not enough; it is only shown as a hint. Everything else waits in the inbox
|
||||
* for the landlord. Being assigned does not yet allow taking anything over.
|
||||
*/
|
||||
class MessageMatcher
|
||||
{
|
||||
/**
|
||||
* @return array{booking: ?Booking, reason: ?string, hints: list<array{booking_id: int, reference: string, why: string}>}
|
||||
*/
|
||||
public function match(InboundMessage $message): array
|
||||
{
|
||||
$sender = mb_strtolower(trim((string) $message->from_address));
|
||||
$text = $message->subject."\n".$message->body;
|
||||
|
||||
$references = array_values(array_filter([$message->in_reply_to, ...((array) $message->references)]));
|
||||
if ($references !== []) {
|
||||
$replied = BookingMessage::query()->whereIn('message_id', $references)->whereNotNull('booking_id')->latest('id')->first()?->booking;
|
||||
if ($replied !== null) {
|
||||
return ['booking' => $replied, 'reason' => 'reply', 'hints' => []];
|
||||
}
|
||||
}
|
||||
|
||||
$hints = [];
|
||||
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $text, $numbers)) {
|
||||
foreach (Booking::query()->whereIn('reference', array_unique($numbers[1]))->with('guest')->get() as $booking) {
|
||||
if ($sender !== '' && mb_strtolower((string) $booking->guest?->email) === $sender) {
|
||||
return ['booking' => $booking, 'reason' => 'reference_and_sender', 'hints' => []];
|
||||
}
|
||||
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'Vorgangsnummer genannt, aber anderer Absender'];
|
||||
}
|
||||
}
|
||||
|
||||
if ($sender === '') {
|
||||
return ['booking' => null, 'reason' => null, 'hints' => $hints];
|
||||
}
|
||||
|
||||
$open = Booking::query()
|
||||
->whereHas('guest', fn ($guest) => $guest->where('email', $sender))
|
||||
->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed])
|
||||
->whereDate('departure', '>=', CarbonImmutable::today())
|
||||
->with('property')
|
||||
->get();
|
||||
|
||||
$dates = $this->dates($text);
|
||||
$singleProperty = Property::query()->count() === 1;
|
||||
$candidates = $open->filter(fn (Booking $booking): bool => in_array($booking->arrival->toDateString(), $dates, true)
|
||||
&& in_array($booking->departure->toDateString(), $dates, true)
|
||||
&& ($singleProperty || mb_stripos($text, (string) $booking->property?->name) !== false));
|
||||
|
||||
if ($candidates->count() === 1) {
|
||||
return ['booking' => $candidates->first(), 'reason' => 'sender_property_dates', 'hints' => []];
|
||||
}
|
||||
|
||||
foreach ($open as $booking) {
|
||||
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'offener Vorgang dieses Absenders ('.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y').')'];
|
||||
}
|
||||
|
||||
return ['booking' => null, 'reason' => null, 'hints' => array_values(array_unique($hints, SORT_REGULAR))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dates written in the message (d.m.yyyy, d.m.yy, yyyy-mm-dd).
|
||||
*
|
||||
* @return list<string> Y-m-d
|
||||
*/
|
||||
public function dates(string $text): array
|
||||
{
|
||||
$dates = [];
|
||||
if (preg_match_all('/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{4}|\d{2})\b/', $text, $german, PREG_SET_ORDER)) {
|
||||
foreach ($german as [, $day, $month, $year]) {
|
||||
$year = strlen($year) === 2 ? '20'.$year : $year;
|
||||
if (checkdate((int) $month, (int) $day, (int) $year)) {
|
||||
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (preg_match_all('/\b(20\d{2})-(\d{2})-(\d{2})\b/', $text, $iso, PREG_SET_ORDER)) {
|
||||
foreach ($iso as [, $year, $month, $day]) {
|
||||
if (checkdate((int) $month, (int) $day, (int) $year)) {
|
||||
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($dates));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Actions\ReceiveInboundMessage;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Enums\TenantServiceKey;
|
||||
@@ -41,6 +42,27 @@ private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMai
|
||||
return;
|
||||
}
|
||||
|
||||
// v0.11: a dedicated mailbox is read completely; portal notifications still go through the portal path.
|
||||
$mailbox = $tenant->activeMailbox();
|
||||
if ($mailbox?->readsEverything()) {
|
||||
try {
|
||||
$mails = $reader->fetchAll();
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error("{$tenant->name}: {$exception->getMessage()}");
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($mails as $mail) {
|
||||
$message = app(ReceiveInboundMessage::class)->handle($mail, $mailbox);
|
||||
if ($message->wasRecentlyCreated) {
|
||||
$this->info("{$tenant->name}: {$message->statusLabel()} ({$message->subject})");
|
||||
}
|
||||
}
|
||||
$mailbox->forceFill(['last_fetched_at' => now()])->save();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$senders = Channel::query()->active()->get()
|
||||
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
|
||||
->unique()
|
||||
|
||||
@@ -34,6 +34,7 @@ enum BookingTaskKind: string implements HasLabel
|
||||
case FactConflict = 'fact_conflict';
|
||||
case ChangeRequest = 'change_request';
|
||||
case GuestUnresponsive = 'guest_unresponsive';
|
||||
case InboundReview = 'inbound_review';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
@@ -57,6 +58,7 @@ public function getLabel(): string
|
||||
self::FactConflict => 'Abweichende Angabe des Gastes prüfen',
|
||||
self::ChangeRequest => 'Änderungswunsch des Gastes prüfen',
|
||||
self::GuestUnresponsive => 'Fehlende Angaben selbst beim Gast nachfragen',
|
||||
self::InboundReview => 'Antwort des Gastes prüfen',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Models\Mailbox;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
@@ -102,12 +103,14 @@ public function mount(): void
|
||||
'bank_iban' => $tenant->bank_iban,
|
||||
'bank_bic' => $tenant->bank_bic,
|
||||
'tax_note' => $tenant->tax_note,
|
||||
'mailbox_host' => $tenant->mailbox_host,
|
||||
'mailbox_port' => $tenant->mailbox_port,
|
||||
'mailbox_username' => $tenant->mailbox_username,
|
||||
'mailbox_password' => $tenant->mailbox_password,
|
||||
'mailbox_encryption' => $tenant->mailbox_encryption,
|
||||
'mailbox_folder' => $tenant->mailbox_folder,
|
||||
'mailbox_host' => $tenant->activeMailbox()?->host ?? $tenant->mailbox_host,
|
||||
'mailbox_port' => $tenant->activeMailbox()?->port ?? $tenant->mailbox_port,
|
||||
'mailbox_username' => $tenant->activeMailbox()?->username ?? $tenant->mailbox_username,
|
||||
'mailbox_password' => $tenant->activeMailbox()?->password ?? $tenant->mailbox_password,
|
||||
'mailbox_encryption' => $tenant->activeMailbox()?->encryption ?? $tenant->mailbox_encryption,
|
||||
'mailbox_folder' => $tenant->activeMailbox()?->folder ?? $tenant->mailbox_folder,
|
||||
'mailbox_address' => $tenant->activeMailbox()?->address,
|
||||
'mailbox_mode' => $tenant->activeMailbox()?->mode ?? Mailbox::PORTAL_ONLY,
|
||||
'reminder_interval_days' => $tenant->reminder_interval_days,
|
||||
'digest_daily' => $tenant->digest_daily,
|
||||
'digest_weekly' => $tenant->digest_weekly,
|
||||
@@ -249,6 +252,12 @@ public function form(Schema $schema): Schema
|
||||
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
||||
->placeholder('SSL'),
|
||||
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
|
||||
Select::make('mailbox_mode')->label('Was wird gelesen?')
|
||||
->options([Mailbox::PORTAL_ONLY => 'Nur Buchungsmails der Portale (wie bisher)', Mailbox::FULL => 'Alle Nachrichten (eigenes Postfach für die Gästekommunikation)'])
|
||||
->required()
|
||||
->helperText('„Alle Nachrichten“ nur für ein Postfach, das ausschließlich für Anfragen und Gästeantworten dient: Antworten und Gast-Mails werden dann den Vorgängen zugeordnet oder im Posteingang zur Klärung gezeigt.'),
|
||||
TextInput::make('mailbox_address')->label('Adresse dieses Postfachs (für Antworten der Gäste)')->email()->maxLength(190)
|
||||
->helperText('Rückfragen nennen diese Adresse als Antwortadresse, damit die Antwort hier ankommt.'),
|
||||
]),
|
||||
Section::make('Fristen und Grenzen')
|
||||
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
||||
@@ -329,6 +338,22 @@ public function save(): void
|
||||
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
|
||||
]);
|
||||
|
||||
// v0.11 (CH-05): the active mailbox record leads; it is kept in step with the fields above.
|
||||
$mailbox = $tenant->activeMailbox() ?? new Mailbox(['is_active' => true]);
|
||||
$mailbox->forceFill(['tenant_id' => $tenant->id])->fill([
|
||||
'host' => $data['mailbox_host'] ?? null,
|
||||
'port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
|
||||
'username' => $data['mailbox_username'] ?? null,
|
||||
'password' => $data['mailbox_password'] ?? null,
|
||||
'encryption' => $data['mailbox_encryption'] ?? null,
|
||||
'folder' => $data['mailbox_folder'] ?? null,
|
||||
'address' => $data['mailbox_address'] ?? null,
|
||||
'mode' => $data['mailbox_mode'] ?? Mailbox::PORTAL_ONLY,
|
||||
]);
|
||||
if ($mailbox->exists || filled($mailbox->host)) {
|
||||
$mailbox->save();
|
||||
}
|
||||
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\InboundMessages;
|
||||
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\RequestCaseData;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Process\CaseLog;
|
||||
use BackedEnum;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\HtmlString;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* The inbox of v0.11 (CH-06, "Kommunikations-Klärungsansicht"): messages of the guest communication mailbox, with
|
||||
* hints from known senders. The landlord assigns a message to a case, makes a new request out of it, or ignores it.
|
||||
* Nothing here changes a booking by itself.
|
||||
*/
|
||||
class InboundMessageResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = InboundMessage::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedInboxArrowDown;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Posteingang';
|
||||
|
||||
protected static ?string $modelLabel = 'Nachricht';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Posteingang';
|
||||
|
||||
protected static ?int $navigationSort = 7;
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$open = InboundMessage::query()->where('status', InboundMessage::NEEDS_REVIEW)->count();
|
||||
|
||||
return $open > 0 ? (string) $open : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'warning';
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('received_at', 'desc')
|
||||
->emptyStateHeading('Keine Nachrichten')
|
||||
->emptyStateDescription('Sobald ein Postfach im Modus „Alle Nachrichten“ eingerichtet ist (System › Betrieb), erscheinen Gast-Mails hier.')
|
||||
->columns([
|
||||
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m.Y H:i')->sortable(),
|
||||
TextColumn::make('from_address')->label('Von')->description(fn (InboundMessage $record): ?string => $record->from_name)->searchable(),
|
||||
TextColumn::make('subject')->label('Betreff')->wrap()->searchable(),
|
||||
TextColumn::make('status')->label('Stand')->badge()->formatStateUsing(fn (InboundMessage $record): string => $record->statusLabel())
|
||||
->color(fn (string $state): string => match ($state) {
|
||||
InboundMessage::NEEDS_REVIEW => 'warning',
|
||||
InboundMessage::ASSIGNED => 'info',
|
||||
InboundMessage::PROCESSED, InboundMessage::PORTAL => 'success',
|
||||
default => 'gray',
|
||||
}),
|
||||
TextColumn::make('booking.reference')->label('Vorgang')->url(fn (InboundMessage $record): ?string => $record->booking ? BookingResource::getUrl('view', ['record' => $record->booking]) : null),
|
||||
IconColumn::make('test_mode')->label('Testbetrieb')->boolean()->trueIcon(Heroicon::OutlinedBeaker)->falseIcon(null)->tooltip('Im Testbetrieb eingegangen'),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')->label('Stand')->options([
|
||||
InboundMessage::NEEDS_REVIEW => 'zu klären', InboundMessage::ASSIGNED => 'zugeordnet', InboundMessage::PROCESSED => 'erledigt',
|
||||
InboundMessage::PORTAL => 'Portal-Mail', InboundMessage::IGNORED => 'ignoriert',
|
||||
]),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('read')->label('Lesen')->icon(Heroicon::OutlinedEye)->button()
|
||||
->modalHeading(fn (InboundMessage $record): string => (string) $record->subject)
|
||||
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->modalWidth('3xl')
|
||||
->schema([
|
||||
TextEntry::make('from')->label('Von')->state(fn (InboundMessage $record): string => trim(($record->from_name ? $record->from_name.' · ' : '').$record->from_address)),
|
||||
TextEntry::make('hints_text')->label('Hinweise')->state(fn (InboundMessage $record): string => collect((array) $record->hints)->map(fn (array $hint): string => $hint['reference'].': '.$hint['why'])->implode(' · ') ?: 'keine')
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW),
|
||||
TextEntry::make('body_text')->label('Nachricht')->state(fn (InboundMessage $record): HtmlString => new HtmlString(nl2br(e((string) $record->body)))),
|
||||
]),
|
||||
Action::make('assign')->label('Vorgang zuordnen')->icon(Heroicon::OutlinedLink)
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
|
||||
->schema([
|
||||
Select::make('booking_id')->label('Vorgang')->required()->searchable()
|
||||
->options(fn (InboundMessage $record): array => self::caseOptions($record)),
|
||||
])
|
||||
->action(function (InboundMessage $record, array $data, RequestCaseData $requests): void {
|
||||
$booking = Booking::query()->findOrFail($data['booking_id']);
|
||||
$record->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => 'landlord']);
|
||||
CaseLog::record($booking, 'mail_in', 'E-Mail von Ihnen zugeordnet: '.$record->subject);
|
||||
$requests->replyReceived($booking);
|
||||
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$record->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $record->subject, 0, 120).'“ – im Posteingang ansehen.']);
|
||||
Notification::make()->title('Zugeordnet')->success()->send();
|
||||
}),
|
||||
Action::make('createInquiry')->label('Als neue Anfrage anlegen')->icon(Heroicon::OutlinedPlus)
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
|
||||
->modalDescription('Es entsteht eine unverbindliche Anfrage wie über die Webseite; der Gast erhält die übliche Eingangsbestätigung bzw. Rückfrage. Termine und Personenzahl bitte aus der Nachricht übernehmen.')
|
||||
->fillForm(fn (InboundMessage $record): array => [
|
||||
'property_id' => Property::query()->orderBy('id')->value('id'),
|
||||
'email' => $record->from_address,
|
||||
'first_name' => str($record->from_name ?? '')->before(' ')->toString(),
|
||||
'last_name' => str($record->from_name ?? '')->after(' ')->toString(),
|
||||
'guests' => 2,
|
||||
])
|
||||
->schema([
|
||||
Select::make('property_id')->label('Wohnung')->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())->required(),
|
||||
DatePicker::make('arrival')->label('Anreise')->required(),
|
||||
DatePicker::make('departure')->label('Abreise')->required()->after('arrival'),
|
||||
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->required(),
|
||||
TextInput::make('first_name')->label('Vorname')->required(),
|
||||
TextInput::make('last_name')->label('Nachname')->required(),
|
||||
TextInput::make('email')->label('E-Mail')->email()->required(),
|
||||
])
|
||||
->action(function (InboundMessage $record, array $data, CreateReservation $create): void {
|
||||
try {
|
||||
$booking = $create->handle(Property::query()->findOrFail($data['property_id']), new StayRequest(CarbonImmutable::parse($data['arrival']), CarbonImmutable::parse($data['departure']), (int) $data['guests']),
|
||||
['first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email']], mb_substr((string) $record->body, 0, 2000), source: 'email');
|
||||
} catch (QuoteException|ReservationException $exception) {
|
||||
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
$record->update(['status' => InboundMessage::PROCESSED, 'booking_id' => $booking->id, 'match_reason' => 'new_request', 'processed_at' => now()]);
|
||||
Notification::make()->title('Anfrage '.$booking->reference.' angelegt')->success()->send();
|
||||
}),
|
||||
ActionGroup::make([
|
||||
Action::make('done')->label('Als erledigt markieren')->icon(Heroicon::OutlinedCheck)
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::ASSIGNED)
|
||||
->action(function (InboundMessage $record): void {
|
||||
$record->update(['status' => InboundMessage::PROCESSED, 'processed_at' => now()]);
|
||||
BookingTask::query()->where('booking_id', $record->booking_id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$record->id)->where('status', BookingTaskStatus::Open)
|
||||
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => auth()->user()?->name])->save());
|
||||
}),
|
||||
Action::make('ignore')->label('Ignorieren')->icon(Heroicon::OutlinedEyeSlash)->color('gray')
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
|
||||
->action(fn (InboundMessage $record) => $record->update(['status' => InboundMessage::IGNORED, 'processed_at' => now()])),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cases to assign a message to: the hints first, then the open cases.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function caseOptions(InboundMessage $message): array
|
||||
{
|
||||
$hinted = collect((array) $message->hints)->pluck('booking_id')->all();
|
||||
|
||||
return Booking::query()->with('guest')
|
||||
->where(fn (Builder $query) => $query->whereKey($hinted)->orWhereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed]))
|
||||
->orderByRaw('CASE WHEN id IN ('.(implode(',', array_map('intval', $hinted)) ?: '0').') THEN 0 ELSE 1 END')->orderBy('arrival')
|
||||
->limit(100)->get()
|
||||
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')])
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return ['index' => ListInboundMessages::route('/')];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\InboundMessages\Pages;
|
||||
|
||||
use App\Filament\Resources\InboundMessages\InboundMessageResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListInboundMessages extends ListRecords
|
||||
{
|
||||
protected static string $resource = InboundMessageResource::class;
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
return 'Nachrichten aus Ihrem Postfach für die Gästekommunikation. Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.';
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,18 @@
|
||||
*/
|
||||
class LogBookingMail
|
||||
{
|
||||
/**
|
||||
* The Message-ID header as sent (not the transport's id), with angle brackets as replies quote it.
|
||||
*/
|
||||
public static function messageId(MessageSent $event): ?string
|
||||
{
|
||||
// The raw message as it went out carries the header; the transport's own id may differ (SMTP queue ids).
|
||||
$raw = $event->sent->getSymfonySentMessage()->getMessage()->toString();
|
||||
$headers = substr($raw, 0, (int) (strpos($raw, "\r\n\r\n") ?: strlen($raw)));
|
||||
|
||||
return preg_match('/^Message-ID:\s*(<[^>\r\n]+>)/mi', $headers, $match) ? $match[1] : null;
|
||||
}
|
||||
|
||||
public function handle(MessageSent $event): void
|
||||
{
|
||||
try {
|
||||
@@ -33,6 +45,8 @@ public function handle(MessageSent $event): void
|
||||
'booking_id' => $booking->id,
|
||||
'audience' => $audience,
|
||||
'subject' => mb_substr((string) $event->message->getSubject(), 0, 255),
|
||||
// v0.11: the Message-ID lets a reply be assigned to its case (CH-13, "bekannter Antwortbezug").
|
||||
'message_id' => rescue(fn (): ?string => self::messageId($event), null, false),
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
} catch (Throwable) {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Models\Booking;
|
||||
use App\Models\DataRequest;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
@@ -46,10 +47,18 @@ public function envelope(): Envelope
|
||||
DataRequest::FOLLOWUP => $subject.': Noch eine kurze Rückfrage',
|
||||
default => $subject.': Bitte ergänzen Sie Ihre Angaben',
|
||||
},
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
// Answers go to the dedicated mailbox when one is read completely (v0.11 inbox), so they reach the case.
|
||||
replyTo: [new Address(self::replyAddress(), config('fewo.owner.name'))],
|
||||
);
|
||||
}
|
||||
|
||||
public static function replyAddress(): string
|
||||
{
|
||||
$mailbox = Settings::tenant()?->activeMailbox();
|
||||
|
||||
return $mailbox?->readsEverything() && filled($mailbox->address) ? (string) $mailbox->address : (string) config('fewo.owner.email');
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(markdown: 'mail.data-requested');
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/**
|
||||
* An e-mail that went out for a booking (communication log). Only subject and audience are kept.
|
||||
*/
|
||||
#[Fillable(['booking_id', 'audience', 'subject', 'sent_at'])]
|
||||
#[Fillable(['booking_id', 'audience', 'subject', 'message_id', 'sent_at'])]
|
||||
class BookingMessage extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A message read from the landlord's mailbox (v0.11, S2/S3), stored before anything is done with it. It is assigned
|
||||
* to a case only by a reliable reference (CH-13); otherwise it waits in the inbox for the landlord. Being assigned is
|
||||
* not yet permission to take anything over.
|
||||
*/
|
||||
#[Fillable(['mailbox_id', 'message_id', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])]
|
||||
class InboundMessage extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const NEW = 'new';
|
||||
|
||||
/** Assigned to a case by a reliable reference. */
|
||||
public const ASSIGNED = 'assigned';
|
||||
|
||||
/** Waits for the landlord: no or no reliable reference, or contradicting hints. */
|
||||
public const NEEDS_REVIEW = 'needs_review';
|
||||
|
||||
/** A portal notification, handled by the existing portal path. */
|
||||
public const PORTAL = 'portal';
|
||||
|
||||
public const IGNORED = 'ignored';
|
||||
|
||||
/** Done: details taken over or decided by the landlord. */
|
||||
public const PROCESSED = 'processed';
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'body' => 'encrypted',
|
||||
'references' => 'array',
|
||||
'to_addresses' => 'array',
|
||||
'hints' => 'array',
|
||||
'extraction' => 'array',
|
||||
'test_mode' => 'boolean',
|
||||
'received_at' => 'immutable_datetime',
|
||||
'processed_at' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Booking, $this>
|
||||
*/
|
||||
public function booking(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Booking::class);
|
||||
}
|
||||
|
||||
public function statusLabel(): string
|
||||
{
|
||||
return match ($this->status) {
|
||||
self::ASSIGNED => 'einem Vorgang zugeordnet',
|
||||
self::NEEDS_REVIEW => 'zu klären',
|
||||
self::PORTAL => 'Portal-Mail',
|
||||
self::IGNORED => 'ignoriert',
|
||||
self::PROCESSED => 'erledigt',
|
||||
default => 'neu',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* A landlord's IMAP mailbox (v0.11, CH-05). Several may exist, one is active. "portal_only" reads the portals'
|
||||
* booking notifications as before; "full" reads every message of a mailbox dedicated to guest communication.
|
||||
*/
|
||||
#[Fillable(['label', 'host', 'port', 'encryption', 'username', 'password', 'folder', 'address', 'mode', 'is_active', 'last_fetched_at'])]
|
||||
#[Hidden(['password'])]
|
||||
class Mailbox extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const PORTAL_ONLY = 'portal_only';
|
||||
|
||||
public const FULL = 'full';
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'password' => 'encrypted',
|
||||
'is_active' => 'boolean',
|
||||
'port' => 'integer',
|
||||
'last_fetched_at' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function readsEverything(): bool
|
||||
{
|
||||
return $this->mode === self::FULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection data in the form the reader expects, or null when it is not usable.
|
||||
*
|
||||
* @return array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string}|null
|
||||
*/
|
||||
public function connection(): ?array
|
||||
{
|
||||
if (blank($this->host) || blank($this->username)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'host' => (string) $this->host,
|
||||
'port' => (int) ($this->port ?: 993),
|
||||
'encryption' => (string) ($this->encryption ?: 'ssl'),
|
||||
'username' => (string) $this->username,
|
||||
'password' => $this->password,
|
||||
'folder' => (string) ($this->folder ?: 'INBOX'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,12 @@ public function serviceUsages(): HasMany
|
||||
*/
|
||||
public function mailbox(): ?array
|
||||
{
|
||||
// v0.11: the active mailbox record leads; the tenant columns remain the fallback until every system migrated.
|
||||
$mailbox = $this->activeMailbox();
|
||||
if ($mailbox !== null) {
|
||||
return $mailbox->connection();
|
||||
}
|
||||
|
||||
if (blank($this->mailbox_host) || blank($this->mailbox_username)) {
|
||||
return null;
|
||||
}
|
||||
@@ -137,6 +143,14 @@ public function mailbox(): ?array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The landlord's active mailbox (at most one, CH-05).
|
||||
*/
|
||||
public function activeMailbox(): ?Mailbox
|
||||
{
|
||||
return Mailbox::query()->withoutGlobalScopes()->where('tenant_id', $this->id)->where('is_active', true)->orderBy('id')->first();
|
||||
}
|
||||
|
||||
public function isLive(): bool
|
||||
{
|
||||
return $this->operating_mode === 'live';
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\Permission;
|
||||
|
||||
/**
|
||||
* The inbox of guest messages belongs to handling the bookings.
|
||||
*/
|
||||
class InboundMessagePolicy extends RolePolicy
|
||||
{
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return Permission::Bookings;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Prozessarchitektur v0.11, communication handler inbox (CH-01, CH-05, CH-06):
|
||||
*
|
||||
* - mailboxes: the data model allows several per landlord; at go-live one is active. Mode "portal_only" reads only the
|
||||
* portals' senders as before; "full" reads every message of a dedicated mailbox. The existing mailbox of each
|
||||
* landlord is taken over unchanged as "portal_only" (the tenant columns stay readable until production migrated).
|
||||
* - inbound_messages: every message read in "full" mode, stored before it is processed, deduplicated per landlord by
|
||||
* its Message-ID, with the case it was assigned to (or why it waits for clarification) and the test-mode mark.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('mailboxes', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
|
||||
$table->string('label')->default('Postfach');
|
||||
$table->string('host', 190)->nullable();
|
||||
$table->unsignedSmallInteger('port')->nullable();
|
||||
$table->string('encryption', 10)->nullable();
|
||||
$table->string('username', 190)->nullable();
|
||||
$table->text('password')->nullable();
|
||||
$table->string('folder', 190)->nullable();
|
||||
$table->string('address')->nullable();
|
||||
$table->string('mode', 20)->default('portal_only');
|
||||
$table->boolean('is_active')->default(true);
|
||||
$table->dateTime('last_fetched_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
foreach (DB::table('tenants')->whereNotNull('mailbox_host')->get() as $tenant) {
|
||||
DB::table('mailboxes')->insert([
|
||||
'tenant_id' => $tenant->id,
|
||||
'label' => 'Postfach',
|
||||
'host' => $tenant->mailbox_host,
|
||||
'port' => $tenant->mailbox_port,
|
||||
'encryption' => $tenant->mailbox_encryption,
|
||||
'username' => $tenant->mailbox_username,
|
||||
// Same application key, same encrypted value.
|
||||
'password' => $tenant->mailbox_password,
|
||||
'folder' => $tenant->mailbox_folder,
|
||||
'mode' => 'portal_only',
|
||||
'is_active' => true,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
Schema::create('inbound_messages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('mailbox_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('message_id');
|
||||
$table->string('in_reply_to')->nullable();
|
||||
$table->text('references')->nullable();
|
||||
$table->string('from_address')->nullable();
|
||||
$table->string('from_name')->nullable();
|
||||
$table->text('to_addresses')->nullable();
|
||||
$table->string('subject', 500)->nullable();
|
||||
$table->longText('body')->nullable();
|
||||
$table->dateTime('received_at');
|
||||
$table->boolean('test_mode')->default(false);
|
||||
$table->string('status', 20);
|
||||
$table->foreignId('booking_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('match_reason', 40)->nullable();
|
||||
$table->json('hints')->nullable();
|
||||
$table->unsignedBigInteger('portal_email_id')->nullable();
|
||||
$table->string('extraction_status', 20)->nullable();
|
||||
$table->json('extraction')->nullable();
|
||||
$table->dateTime('processed_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['tenant_id', 'message_id']);
|
||||
$table->index(['status', 'extraction_status']);
|
||||
});
|
||||
|
||||
Schema::table('portal_emails', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('inbound_message_id')->nullable()->index();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('portal_emails', function (Blueprint $table) {
|
||||
$table->dropColumn('inbound_message_id');
|
||||
});
|
||||
Schema::dropIfExists('inbound_messages');
|
||||
Schema::dropIfExists('mailboxes');
|
||||
}
|
||||
};
|
||||
+155
-50
@@ -2,88 +2,193 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Filament\Resources\InboxMessages\InboxMessageResource;
|
||||
use App\Filament\Resources\InboxMessages\Pages\ListInboxMessages;
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\ReceiveInboundMessage;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Filament\Pages\Operations;
|
||||
use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages;
|
||||
use App\Mail\DataRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingMessage;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\Channel;
|
||||
use App\Models\InboxMessage;
|
||||
use App\Models\DataRequest;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Mailbox;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use App\Support\CurrentProperty;
|
||||
use App\Support\Inbox;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Database\Seeders\SiteSeeder;
|
||||
use Filament\Actions\Testing\TestAction;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Mail\MailManager;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Livewire\Livewire;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* v0.11 package U5: the inbox of the guest communication mailbox – stored once, portal notifications through the
|
||||
* unchanged portal path, deterministic assignment (CH-13) or clarification (M04), reply references (M07 part),
|
||||
* test-mode mark (M10) and the landlord's clarification view.
|
||||
*/
|
||||
class InboxTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Channel $channel;
|
||||
private Property $property;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
|
||||
$this->seed([PropertySeeder::class, SiteSeeder::class]);
|
||||
$this->property = Property::sole();
|
||||
Mail::fake();
|
||||
Http::fake(['*' => Http::response('', 500)]);
|
||||
}
|
||||
|
||||
public function test_a_reply_to_our_mail_is_assigned_and_stops_the_reminders(): void
|
||||
{
|
||||
Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'automatic']]);
|
||||
$booking = $this->request();
|
||||
BookingMessage::query()->create(['booking_id' => $booking->id, 'audience' => 'test', 'subject' => 'Rückfrage', 'message_id' => '<abc@fewo.test>', 'sent_at' => now()]);
|
||||
|
||||
$message = $this->receive(from: 'irgendwer@example.org', subject: 'Re: Ihre Anfrage', text: 'Strandweg 1, 18225 Kühlungsborn', inReplyTo: '<abc@fewo.test>');
|
||||
|
||||
$this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'reply'], [$message->status, $message->booking_id, $message->match_reason]);
|
||||
$this->assertNull($booking->openDataRequest()->next_reminder_at, 'the answer stops the reminder');
|
||||
$this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::InboundReview)->count());
|
||||
$this->assertTrue($message->test_mode, 'arrived in test operation');
|
||||
}
|
||||
|
||||
public function test_the_case_number_counts_only_with_the_guest_as_sender(): void
|
||||
{
|
||||
$booking = $this->request();
|
||||
|
||||
$own = $this->receive(from: 'gesa@example.org', subject: 'Frage zu '.$booking->reference, text: 'Hallo');
|
||||
$foreign = $this->receive(from: 'fremd@example.org', subject: 'Frage zu '.$booking->reference, text: 'Hallo', id: '<2@x>');
|
||||
|
||||
$this->assertSame([InboundMessage::ASSIGNED, 'reference_and_sender'], [$own->status, $own->match_reason]);
|
||||
$this->assertSame(InboundMessage::NEEDS_REVIEW, $foreign->status);
|
||||
$this->assertSame($booking->id, $foreign->hints[0]['booking_id']);
|
||||
}
|
||||
|
||||
/** CH-13 as specified: one open case of the same sender alone is not enough. */
|
||||
public function test_a_direct_guest_mail_needs_sender_property_and_dates(): void
|
||||
{
|
||||
$booking = $this->request();
|
||||
|
||||
$vague = $this->receive(from: 'gesa@example.org', subject: 'Unsere Reise', text: 'Wir freuen uns schon!');
|
||||
$precise = $this->receive(from: 'gesa@example.org', subject: 'Unsere Reise', text: 'Für den Aufenthalt vom 07.11.2026 bis 10.11.2026 noch eine Frage.', id: '<3@x>');
|
||||
|
||||
$this->assertSame(InboundMessage::NEEDS_REVIEW, $vague->status);
|
||||
$this->assertSame('offener Vorgang dieses Absenders (07.11.–10.11.2026)', $vague->hints[0]['why']);
|
||||
$this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'sender_property_dates'], [$precise->status, $precise->booking_id, $precise->match_reason]);
|
||||
}
|
||||
|
||||
public function test_dates_of_two_cases_of_the_same_guest_are_resolved_only_when_unambiguous(): void
|
||||
{
|
||||
$first = $this->request();
|
||||
$second = $this->request(arrival: '2026-11-20', departure: '2026-11-23');
|
||||
|
||||
$one = $this->receive(from: 'gesa@example.org', subject: 'Frage', text: 'Zum 20.11.2026 – 23.11.2026: Bringen wir den Hund mit?');
|
||||
$both = $this->receive(from: 'gesa@example.org', subject: 'Frage', text: '07.11.2026 bis 10.11.2026 und 20.11.2026 bis 23.11.2026', id: '<4@x>');
|
||||
|
||||
$this->assertSame($second->id, $one->booking_id);
|
||||
$this->assertSame(InboundMessage::NEEDS_REVIEW, $both->status);
|
||||
$this->assertNotSame($first->id, $one->booking_id);
|
||||
}
|
||||
|
||||
public function test_a_message_is_stored_once_and_our_own_mails_are_ignored(): void
|
||||
{
|
||||
$this->receive(from: 'gast@example.org', subject: 'Hallo', text: 'Test');
|
||||
$this->receive(from: 'gast@example.org', subject: 'Hallo', text: 'Test');
|
||||
$own = $this->receive(from: (string) config('mail.from.address'), subject: 'Kopie', text: 'x', id: '<own@x>');
|
||||
|
||||
$this->assertSame(2, InboundMessage::query()->count());
|
||||
$this->assertSame(InboundMessage::IGNORED, $own->status);
|
||||
}
|
||||
|
||||
/** CH-08: the portal path stays as it is. */
|
||||
public function test_a_portal_notification_goes_through_the_unchanged_portal_path(): void
|
||||
{
|
||||
Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'settings' => ['email_senders' => 'fewo-direkt.de']]);
|
||||
|
||||
$message = $this->receive(from: 'noreply@fewo-direkt.de', subject: 'Neue Buchung', text: "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-1");
|
||||
|
||||
$portal = PortalEmail::query()->sole();
|
||||
$this->assertSame([InboundMessage::PORTAL, $portal->id], [$message->status, $message->portal_email_id]);
|
||||
$this->assertSame($message->id, $portal->inbound_message_id);
|
||||
$this->assertNotNull($portal->blocked_period_id, 'the booking was blocked as before');
|
||||
}
|
||||
|
||||
/** M04: a general message creates nothing; the landlord decides in the inbox. */
|
||||
public function test_the_landlord_assigns_a_message_or_makes_a_new_request_of_it(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->channel = Channel::factory()->for(Property::factory())->create(['name' => 'FeWo-direkt']);
|
||||
$booking = $this->request();
|
||||
$general = $this->receive(from: 'neu@example.org', subject: 'Haben Sie im Dezember frei?', text: 'Wir sind zwei Personen.');
|
||||
$other = $this->receive(from: 'unbekannt@example.org', subject: 'Nachtrag', text: 'Bitte zuordnen', id: '<5@x>');
|
||||
$this->assertSame(1, Booking::query()->count(), 'no case from a message by itself');
|
||||
|
||||
Livewire::test(ListInboundMessages::class)
|
||||
->callAction(TestAction::make('assign')->table($other), ['booking_id' => $booking->id])
|
||||
->callAction(TestAction::make('createInquiry')->table($general), ['property_id' => $this->property->id, 'arrival' => '2026-12-01', 'departure' => '2026-12-05', 'guests' => 2, 'first_name' => 'Nina', 'last_name' => 'Neu', 'email' => 'neu@example.org']);
|
||||
|
||||
$this->assertSame([InboundMessage::ASSIGNED, $booking->id], [$other->fresh()->status, $other->fresh()->booking_id]);
|
||||
$created = Booking::query()->where('source', 'email')->sole();
|
||||
$this->assertSame([InboundMessage::PROCESSED, $created->id], [$general->fresh()->status, $general->fresh()->booking_id]);
|
||||
$this->assertNotNull($created->openDataRequest(), 'the new request asks for its missing address');
|
||||
}
|
||||
|
||||
public function test_a_finding_is_posted_only_once(): void
|
||||
public function test_our_mails_keep_their_message_id_for_replies(): void
|
||||
{
|
||||
$inbox = app(Inbox::class);
|
||||
config(['mail.default' => 'array']);
|
||||
Settings::tenant()->update(['test_recipient' => 'test@example.org']);
|
||||
Mail::swap(new MailManager($this->app));
|
||||
$booking = $this->request();
|
||||
$request = $booking->dataRequests()->create(['tenant_id' => $booking->tenant_id, 'status' => DataRequest::OPEN, 'mode' => 'automatic', 'purpose' => 'offer', 'fields' => ['guest.street']]);
|
||||
|
||||
$first = $inbox->post(InboxMessageKind::ChannelConflict, 'x', 'Mögliche Doppelbuchung', 'Text', $this->channel);
|
||||
$again = $inbox->post(InboxMessageKind::ChannelConflict, 'x', 'Mögliche Doppelbuchung', 'Text', $this->channel);
|
||||
Mail::to('gesa@example.org')->send(new DataRequested($booking, $request, DataRequest::INITIAL, 'https://example.test'));
|
||||
|
||||
$this->assertNotNull($first);
|
||||
$this->assertNull($again);
|
||||
$this->assertSame($this->channel->property_id, $first->property_id);
|
||||
$this->assertSame(1, InboxMessage::count());
|
||||
$this->assertMatchesRegularExpression('/^<.+@.+>$/', (string) BookingMessage::query()->where('booking_id', $booking->id)->latest('id')->value('message_id'));
|
||||
}
|
||||
|
||||
public function test_menu_shows_the_number_of_unread_messages(): void
|
||||
public function test_the_mailbox_is_kept_as_a_record_and_full_mode_reads_every_message(): void
|
||||
{
|
||||
InboxMessage::factory()->for($this->channel)->count(2)->create();
|
||||
InboxMessage::factory()->for($this->channel)->read()->create();
|
||||
$this->actingAs(User::factory()->create());
|
||||
Livewire::test(Operations::class)
|
||||
->fillForm(['mailbox_host' => 'imap.example.org', 'mailbox_username' => 'anfragen@example.org', 'mailbox_password' => 'geheim', 'mailbox_mode' => Mailbox::FULL, 'mailbox_address' => 'anfragen@example.org'])
|
||||
->call('save')->assertHasNoFormErrors();
|
||||
$mailbox = Mailbox::query()->sole();
|
||||
$this->assertSame([Mailbox::FULL, 'anfragen@example.org', 'geheim'], [$mailbox->mode, $mailbox->address, $mailbox->password]);
|
||||
$this->assertSame('anfragen@example.org', DataRequested::replyAddress(), 'questions ask for answers to this mailbox');
|
||||
|
||||
$this->assertSame('2', InboxMessageResource::getNavigationBadge());
|
||||
$this->get(InboxMessageResource::getUrl('index'))->assertOk()->assertSee('Postfach');
|
||||
$reader = Mockery::mock(MailboxReader::class);
|
||||
$reader->shouldReceive('fetchAll')->once()->andReturn([new PortalMail('<9@x>', 'gast@example.org', 'Hallo', 'Text', CarbonImmutable::now())]);
|
||||
$this->app->instance(MailboxReader::class, $reader);
|
||||
$this->artisan('channels:fetch-mail')->assertSuccessful();
|
||||
|
||||
$this->assertSame(InboundMessage::NEEDS_REVIEW, InboundMessage::query()->sole()->status);
|
||||
$this->assertNotNull($mailbox->fresh()->last_fetched_at);
|
||||
}
|
||||
|
||||
public function test_messages_can_be_marked_as_read_and_opened(): void
|
||||
private function request(string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
|
||||
{
|
||||
$message = InboxMessage::factory()->for($this->channel)->create(['subject' => 'Mögliche Doppelbuchung über FeWo-direkt', 'action_url' => 'http://localhost/admin/belegung']);
|
||||
$other = InboxMessage::factory()->for($this->channel)->create();
|
||||
|
||||
Livewire::test(ListInboxMessages::class)
|
||||
->assertCanSeeTableRecords([$message, $other])
|
||||
->assertSee('Mögliche Doppelbuchung über FeWo-direkt')
|
||||
->callAction(TestAction::make('toggleRead')->table($other))
|
||||
->callAction(TestAction::make('open')->table($message))
|
||||
->assertRedirect('http://localhost/admin/belegung');
|
||||
|
||||
$this->assertTrue($message->fresh()->isRead());
|
||||
$this->assertTrue($other->fresh()->isRead());
|
||||
$this->assertNull(InboxMessageResource::getNavigationBadge());
|
||||
return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'])->fresh();
|
||||
}
|
||||
|
||||
public function test_read_all_marks_only_the_chosen_apartments_messages(): void
|
||||
private function receive(string $from, string $subject, string $text, ?string $inReplyTo = null, string $id = '<1@x>'): InboundMessage
|
||||
{
|
||||
$otherChannel = Channel::factory()->for(Property::factory())->create();
|
||||
$own = InboxMessage::factory()->for($this->channel)->create(['property_id' => $this->channel->property_id]);
|
||||
$general = InboxMessage::factory()->create(['tenant_id' => $this->channel->tenant_id]);
|
||||
$foreign = InboxMessage::factory()->for($otherChannel)->create(['property_id' => $otherChannel->property_id]);
|
||||
app(CurrentProperty::class)->select($this->channel->property);
|
||||
|
||||
Livewire::test(ListInboxMessages::class)
|
||||
->assertCanSeeTableRecords([$own, $general])
|
||||
->assertCanNotSeeTableRecords([$foreign])
|
||||
->callAction('readAll');
|
||||
|
||||
$this->assertTrue($own->fresh()->isRead());
|
||||
$this->assertTrue($general->fresh()->isRead());
|
||||
$this->assertFalse($foreign->fresh()->isRead());
|
||||
return app(ReceiveInboundMessage::class)->handle(new PortalMail($id, $from, $subject, $text, CarbonImmutable::now(), inReplyTo: $inReplyTo))->fresh();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user