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(); // CH-09/12: if the notification belongs to a case, the guest details it carries are evaluated for that case. $bookingId = $record?->blockedPeriod()->value('linked_booking_id'); $message->update(['status' => InboundMessage::PORTAL, 'portal_email_id' => $record?->id, 'booking_id' => $bookingId, 'match_reason' => $bookingId ? 'portal_reference' : null, '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); } }