From dff9e2344ed61d5f9ad970eb7c8bd283d2119a45 Mon Sep 17 00:00:00 2001 From: Lars Date: Tue, 3 Nov 2026 13:39:20 +0100 Subject: [PATCH] =?UTF-8?q?v0.11=20U5:=20Posteingang,=20deterministische?= =?UTF-8?q?=20Zuordnung,=20Kl=C3=A4rungsansicht?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- app/Actions/ReceiveInboundMessage.php | 95 ++++++++ app/Actions/RequestCaseData.php | 23 ++ app/Channels/Mail/MailboxReader.php | 48 ++++ app/Channels/Mail/PortalMail.php | 11 +- app/Communication/MessageMatcher.php | 105 +++++++++ app/Console/Commands/FetchPortalMail.php | 22 ++ app/Enums/BookingTaskKind.php | 2 + app/Filament/Pages/Operations.php | 37 +++- .../InboundMessageResource.php | 197 +++++++++++++++++ .../Pages/ListInboundMessages.php | 16 ++ app/Listeners/LogBookingMail.php | 14 ++ app/Mail/DataRequested.php | 11 +- app/Models/BookingMessage.php | 2 +- app/Models/InboundMessage.php | 72 ++++++ app/Models/Mailbox.php | 62 ++++++ app/Models/Tenant.php | 14 ++ app/Policies/InboundMessagePolicy.php | 16 ++ ..._create_mailboxes_and_inbound_messages.php | 97 +++++++++ tests/Feature/InboxTest.php | 205 +++++++++++++----- 19 files changed, 990 insertions(+), 59 deletions(-) create mode 100644 app/Actions/ReceiveInboundMessage.php create mode 100644 app/Communication/MessageMatcher.php create mode 100644 app/Filament/Resources/InboundMessages/InboundMessageResource.php create mode 100644 app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php create mode 100644 app/Models/InboundMessage.php create mode 100644 app/Models/Mailbox.php create mode 100644 app/Policies/InboundMessagePolicy.php create mode 100644 database/migrations/2026_11_06_120000_create_mailboxes_and_inbound_messages.php diff --git a/app/Actions/ReceiveInboundMessage.php b/app/Actions/ReceiveInboundMessage.php new file mode 100644 index 0000000..8777452 --- /dev/null +++ b/app/Actions/ReceiveInboundMessage.php @@ -0,0 +1,95 @@ +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); + } +} diff --git a/app/Actions/RequestCaseData.php b/app/Actions/RequestCaseData.php index 7b61b6e..3186303 100644 --- a/app/Actions/RequestCaseData.php +++ b/app/Actions/RequestCaseData.php @@ -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. diff --git a/app/Channels/Mail/MailboxReader.php b/app/Channels/Mail/MailboxReader.php index d898415..d681c02 100644 --- a/app/Channels/Mail/MailboxReader.php +++ b/app/Channels/Mail/MailboxReader.php @@ -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 + * + * @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, ); } } diff --git a/app/Channels/Mail/PortalMail.php b/app/Channels/Mail/PortalMail.php index 5ca3396..ad17a2d 100644 --- a/app/Channels/Mail/PortalMail.php +++ b/app/Channels/Mail/PortalMail.php @@ -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 $references + * @param list $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, ) {} } diff --git a/app/Communication/MessageMatcher.php b/app/Communication/MessageMatcher.php new file mode 100644 index 0000000..de06401 --- /dev/null +++ b/app/Communication/MessageMatcher.php @@ -0,0 +1,105 @@ +} + */ + 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 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)); + } +} diff --git a/app/Console/Commands/FetchPortalMail.php b/app/Console/Commands/FetchPortalMail.php index 26b3137..ea6dea6 100644 --- a/app/Console/Commands/FetchPortalMail.php +++ b/app/Console/Commands/FetchPortalMail.php @@ -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() diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index e4667e6..5009c08 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -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', }; } diff --git a/app/Filament/Pages/Operations.php b/app/Filament/Pages/Operations.php index 501fa99..57a300b 100644 --- a/app/Filament/Pages/Operations.php +++ b/app/Filament/Pages/Operations.php @@ -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) { diff --git a/app/Filament/Resources/InboundMessages/InboundMessageResource.php b/app/Filament/Resources/InboundMessages/InboundMessageResource.php new file mode 100644 index 0000000..c44f9a3 --- /dev/null +++ b/app/Filament/Resources/InboundMessages/InboundMessageResource.php @@ -0,0 +1,197 @@ +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 + */ + 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('/')]; + } +} diff --git a/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php b/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php new file mode 100644 index 0000000..b564c4c --- /dev/null +++ b/app/Filament/Resources/InboundMessages/Pages/ListInboundMessages.php @@ -0,0 +1,16 @@ +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) { diff --git a/app/Mail/DataRequested.php b/app/Mail/DataRequested.php index 41f1da2..437af3c 100644 --- a/app/Mail/DataRequested.php +++ b/app/Mail/DataRequested.php @@ -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'); diff --git a/app/Models/BookingMessage.php b/app/Models/BookingMessage.php index 8e0254b..5c99709 100644 --- a/app/Models/BookingMessage.php +++ b/app/Models/BookingMessage.php @@ -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; diff --git a/app/Models/InboundMessage.php b/app/Models/InboundMessage.php new file mode 100644 index 0000000..fd2833b --- /dev/null +++ b/app/Models/InboundMessage.php @@ -0,0 +1,72 @@ + + */ + 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 + */ + 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', + }; + } +} diff --git a/app/Models/Mailbox.php b/app/Models/Mailbox.php new file mode 100644 index 0000000..4f7ff7c --- /dev/null +++ b/app/Models/Mailbox.php @@ -0,0 +1,62 @@ + + */ + 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'), + ]; + } +} diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index 4c64eda..af48d0b 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -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'; diff --git a/app/Policies/InboundMessagePolicy.php b/app/Policies/InboundMessagePolicy.php new file mode 100644 index 0000000..0fd5d71 --- /dev/null +++ b/app/Policies/InboundMessagePolicy.php @@ -0,0 +1,16 @@ +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'); + } +}; diff --git a/tests/Feature/InboxTest.php b/tests/Feature/InboxTest.php index 3966530..84db681 100644 --- a/tests/Feature/InboxTest.php +++ b/tests/Feature/InboxTest.php @@ -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' => '', 'sent_at' => now()]); + + $message = $this->receive(from: 'irgendwer@example.org', subject: 'Re: Ihre Anfrage', text: 'Strandweg 1, 18225 Kühlungsborn', inReplyTo: ''); + + $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: ''); + + $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(); } }