Coverage for dao/email_messages_dao.py: 43.48%
42 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""
2EmailMessagesDAO — individual messages in support-inbox threads (SB-35).
4Phase 1 surface (webhook ingest): insert_inbound, find_by_message_id,
5find_thread_id_by_in_reply_to.
7Phase 2 surface (admin API): list_by_thread, insert_outbound,
8get_latest_inbound_for_thread.
10Delivery status (SB-1821): record_reply_sent.
11"""
13from __future__ import annotations
15from typing import Any
17import structlog
19from dao.base_dao import BaseDAO, invalidates_cache
21logger = structlog.get_logger()
23EMAIL_MESSAGES_CACHE_PATTERN = "mt:dao:email_messages:*"
26class EmailMessagesDAO(BaseDAO):
27 """Data access for the email_messages table."""
29 # ── reads ────────────────────────────────────────────────────────────────
31 def find_by_message_id(self, message_id: str) -> dict[str, Any] | None:
32 """Look up a message by its RFC 5322 Message-ID (angle brackets stripped).
34 Used for webhook idempotency: if the same provider event arrives twice
35 (e.g. Resend retry), the second insert hits the unique constraint —
36 but we check first so we can return 200 cleanly without an exception.
37 """
38 response = (
39 self.client.table("email_messages")
40 .select("*")
41 .eq("message_id", message_id)
42 .limit(1)
43 .execute()
44 )
45 return response.data[0] if response.data else None
47 def find_thread_id_by_in_reply_to(self, in_reply_to: str) -> str | None:
48 """Resolve the thread an inbound reply belongs to via the In-Reply-To
49 header. Returns the thread_id of the referenced message, or None if
50 we don't recognize the referenced Message-ID.
52 This is the first tier of the threading resolver. Falls back to
53 case-number-in-subject and then subject+sender if this misses.
54 """
55 response = (
56 self.client.table("email_messages")
57 .select("thread_id")
58 .eq("message_id", in_reply_to)
59 .limit(1)
60 .execute()
61 )
62 return response.data[0]["thread_id"] if response.data else None
64 # ── writes ───────────────────────────────────────────────────────────────
66 @invalidates_cache(EMAIL_MESSAGES_CACHE_PATTERN)
67 def insert_inbound(
68 self,
69 *,
70 thread_id: str,
71 message_id: str,
72 from_email: str,
73 to_email: str,
74 subject: str,
75 in_reply_to: str | None = None,
76 references: str | None = None,
77 from_name: str | None = None,
78 body_text: str | None = None,
79 body_html: str | None = None,
80 had_attachments: bool = False,
81 raw_payload: dict[str, Any] | None = None,
82 ) -> dict[str, Any]:
83 """Insert a new inbound message row.
85 Caller is responsible for sanitizing body_html (we never insert raw
86 webhook HTML — bleach is applied upstream in the inbound service).
88 Raises if the unique constraint on message_id fires; the webhook
89 handler checks find_by_message_id first to make ingest idempotent.
90 """
91 payload: dict[str, Any] = {
92 "thread_id": thread_id,
93 "direction": "inbound",
94 "message_id": message_id,
95 "from_email": from_email,
96 "to_email": to_email,
97 "subject": subject,
98 "in_reply_to": in_reply_to,
99 "references": references,
100 "from_name": from_name,
101 "body_text": body_text,
102 "body_html": body_html,
103 "had_attachments": had_attachments,
104 "raw_payload": raw_payload,
105 }
106 response = self.client.table("email_messages").insert(payload).execute()
107 if not response.data:
108 raise RuntimeError("email_messages insert returned no data")
109 row = response.data[0]
110 logger.info(
111 "email_message_inserted",
112 message_id=message_id,
113 thread_id=thread_id,
114 direction="inbound",
115 had_attachments=had_attachments,
116 )
117 return row
119 # ── Phase 2: admin API surface ───────────────────────────────────────────
121 def list_by_thread(self, thread_id: str) -> list[dict[str, Any]]:
122 """All messages in a thread, oldest first."""
123 response = (
124 self.client.table("email_messages")
125 .select("*")
126 .eq("thread_id", thread_id)
127 .order("created_at", desc=False)
128 .execute()
129 )
130 return response.data or []
132 def get_latest_inbound_for_thread(
133 self, thread_id: str
134 ) -> dict[str, Any] | None:
135 """The most recent inbound message on a thread. Used by the admin-reply
136 path to set In-Reply-To on the outgoing message.
137 """
138 response = (
139 self.client.table("email_messages")
140 .select("*")
141 .eq("thread_id", thread_id)
142 .eq("direction", "inbound")
143 .order("created_at", desc=True)
144 .limit(1)
145 .execute()
146 )
147 return response.data[0] if response.data else None
149 @invalidates_cache(EMAIL_MESSAGES_CACHE_PATTERN)
150 def insert_outbound(
151 self,
152 *,
153 thread_id: str,
154 message_id: str,
155 from_email: str,
156 to_email: str,
157 subject: str,
158 sent_by_user_id: str,
159 in_reply_to: str | None = None,
160 references: str | None = None,
161 body_text: str | None = None,
162 body_html: str | None = None,
163 ) -> dict[str, Any]:
164 """Insert an outbound admin-reply message row.
166 Symmetric to insert_inbound, but the caller is the admin sending
167 the reply — sent_by_user_id is required and direction is 'outbound'.
168 had_attachments and raw_payload don't apply (we don't attach files
169 or have a provider payload to preserve on outbound).
171 message_id should be the angle-brackets-stripped form, for parity
172 with inbound storage (so In-Reply-To lookups work in both directions).
173 """
174 payload: dict[str, Any] = {
175 "thread_id": thread_id,
176 "direction": "outbound",
177 "message_id": message_id,
178 "from_email": from_email,
179 "to_email": to_email,
180 "subject": subject,
181 "in_reply_to": in_reply_to,
182 "references": references,
183 "body_text": body_text,
184 "body_html": body_html,
185 "had_attachments": False,
186 "sent_by_user_id": sent_by_user_id,
187 }
188 response = self.client.table("email_messages").insert(payload).execute()
189 if not response.data:
190 raise RuntimeError("email_messages insert returned no data")
191 row = response.data[0]
192 logger.info(
193 "email_message_inserted",
194 message_id=message_id,
195 thread_id=thread_id,
196 direction="outbound",
197 sent_by_user_id=sent_by_user_id,
198 )
199 return row
201 @invalidates_cache(EMAIL_MESSAGES_CACHE_PATTERN)
202 def record_reply_sent(self, row_id: str, resend_email_id: str, sent_at: str) -> dict[str, Any]:
203 """Store the Resend email id on an outbound reply and mark it 'sent'
204 (SB-1821). Delivery webhooks find the reply by this id.
206 A separate update rather than part of insert_outbound, so a database
207 without the delivery columns still saves the reply. Returns the
208 fields written; raises on failure (the caller treats it as best effort).
209 """
210 update: dict[str, Any] = {
211 "resend_email_id": resend_email_id,
212 "email_status": "sent",
213 "email_status_at": sent_at,
214 "email_status_detail": None,
215 }
216 self.client.table("email_messages").update(update).eq("id", row_id).eq("direction", "outbound").execute()
217 return update