Coverage for dao/email_threads_dao.py: 23.08%
106 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"""
2EmailThreadsDAO — support-inbox conversations (SB-35).
4Phase 1 surface (webhook ingest): create_for_inbound, transition_on_inbound,
5get_by_id, get_by_case_number.
7Phase 2 surface (admin API): list_by_status, get_thread_with_messages,
8transition_on_outbound, set_status, mark_all_read, unread_count_for_attention.
9"""
11from __future__ import annotations
13import base64
14from datetime import UTC, datetime
15from typing import Any
17import structlog
19from dao.base_dao import BaseDAO, invalidates_cache
21logger = structlog.get_logger()
23EMAIL_THREADS_CACHE_PATTERN = "mt:dao:email_threads:*"
24EMAIL_MESSAGES_CACHE_PATTERN = "mt:dao:email_messages:*"
26_VALID_STATUSES = frozenset({"new", "awaiting_admin", "awaiting_user", "resolved", "spam"})
27_MANUAL_STATUSES = frozenset({"resolved", "spam", "awaiting_admin"})
30def encode_cursor(last_message_at: str, thread_id: str) -> str:
31 """Opaque cursor for keyset pagination on (last_message_at desc, id desc).
33 Base64-encoded so callers don't depend on the internal shape.
34 """
35 raw = f"{last_message_at}|{thread_id}".encode()
36 return base64.urlsafe_b64encode(raw).decode().rstrip("=")
39def decode_cursor(cursor: str) -> tuple[str, str]:
40 """Inverse of encode_cursor. Returns (last_message_at, thread_id)."""
41 padded = cursor + "=" * (-len(cursor) % 4)
42 raw = base64.urlsafe_b64decode(padded).decode()
43 ts, _, tid = raw.partition("|")
44 if not ts or not tid:
45 raise ValueError("invalid cursor")
46 return ts, tid
49class EmailThreadsDAO(BaseDAO):
50 """Data access for the email_threads table."""
52 # ── reads ────────────────────────────────────────────────────────────────
54 def get_thread_by_id(self, thread_id: str) -> dict[str, Any] | None:
55 """Fetch a thread by UUID. Returns None if not found.
57 Named `get_thread_by_id` (rather than `get_by_id`) so the typed UUID
58 argument doesn't collide with BaseDAO.get_by_id(table, record_id).
59 """
60 response = (
61 self.client.table("email_threads")
62 .select("*")
63 .eq("id", thread_id)
64 .limit(1)
65 .execute()
66 )
67 return response.data[0] if response.data else None
69 def find_recent_by_participant(
70 self,
71 participant_email: str,
72 *,
73 since_iso: str,
74 ) -> list[dict[str, Any]]:
75 """Recent threads from a participant, newest first.
77 Used by the threading resolver's third-tier fallback: when neither
78 In-Reply-To nor a case-number-in-subject matches, look for a recent
79 thread from the same sender and merge by normalized subject upstream.
81 Args:
82 participant_email: external party's address (case-insensitive match)
83 since_iso: ISO timestamp lower bound (e.g. now - 30 days)
84 """
85 response = (
86 self.client.table("email_threads")
87 .select("*")
88 .ilike("participant_email", participant_email)
89 .gte("last_message_at", since_iso)
90 .order("last_message_at", desc=True)
91 .limit(20)
92 .execute()
93 )
94 return response.data or []
96 def get_by_case_number(self, case_number: int) -> dict[str, Any] | None:
97 """Fetch a thread by its MT-{n} case number. Returns None if not found.
99 Used by the threading resolver (fallback when In-Reply-To is missing
100 but the inbound subject contains `[MT-{n}]`) and by the admin UI for
101 deep-linking by case number.
102 """
103 response = (
104 self.client.table("email_threads")
105 .select("*")
106 .eq("case_number", case_number)
107 .limit(1)
108 .execute()
109 )
110 return response.data[0] if response.data else None
112 # ── writes ───────────────────────────────────────────────────────────────
114 @invalidates_cache(EMAIL_THREADS_CACHE_PATTERN)
115 def create_for_inbound(
116 self,
117 *,
118 subject: str,
119 participant_email: str,
120 participant_name: str | None = None,
121 last_message_at: str | None = None,
122 ) -> dict[str, Any]:
123 """Insert a new thread for an inbound email that didn't match any
124 existing thread. case_number is assigned automatically from the
125 sequence; status starts as 'new'; unread_count is set to 1 since
126 this insert always pairs with an inbound message.
128 Args:
129 subject: subject line of the first inbound message
130 participant_email: the external party (sender of the inbound)
131 participant_name: optional display name from From header
132 last_message_at: optional ISO timestamp; defaults to now() in db
134 Returns:
135 The inserted row (including assigned id and case_number).
136 """
137 payload: dict[str, Any] = {
138 "subject": subject,
139 "participant_email": participant_email,
140 "participant_name": participant_name,
141 "status": "new",
142 "unread_count": 1,
143 }
144 if last_message_at:
145 payload["last_message_at"] = last_message_at
147 response = self.client.table("email_threads").insert(payload).execute()
148 if not response.data:
149 raise RuntimeError("email_threads insert returned no data")
150 row = response.data[0]
151 logger.info(
152 "email_thread_created",
153 thread_id=row["id"],
154 case_number=row["case_number"],
155 participant_email=participant_email,
156 )
157 return row
159 @invalidates_cache(EMAIL_THREADS_CACHE_PATTERN)
160 def transition_on_inbound(
161 self,
162 thread_id: str,
163 *,
164 last_message_at: str | None = None,
165 ) -> dict[str, Any] | None:
166 """An inbound message just landed on an existing thread.
168 Side effects:
169 - status: 'new' / 'awaiting_admin' / 'resolved' → 'awaiting_admin'
170 (reopens 'resolved' threads on user reply).
171 - status: 'spam' → unchanged (silently absorb).
172 - unread_count += 1
173 - last_message_at = max(existing, last_message_at)
174 """
175 current = self.get_thread_by_id(thread_id)
176 if not current:
177 return None
179 next_status = current["status"]
180 if next_status != "spam":
181 next_status = "awaiting_admin"
183 updates: dict[str, Any] = {
184 "status": next_status,
185 "unread_count": (current.get("unread_count") or 0) + 1,
186 }
187 if last_message_at:
188 updates["last_message_at"] = last_message_at
190 response = (
191 self.client.table("email_threads")
192 .update(updates)
193 .eq("id", thread_id)
194 .execute()
195 )
196 return response.data[0] if response.data else None
198 # ── Phase 2: admin API surface ───────────────────────────────────────────
200 def list_by_status(
201 self,
202 statuses: list[str],
203 *,
204 limit: int = 50,
205 cursor: str | None = None,
206 ) -> dict[str, Any]:
207 """Paginated list of threads filtered by status, newest-first.
209 Keyset cursor on `(last_message_at desc, id desc)` — stable across
210 inserts and avoids OFFSET's slow-scan behavior on large inboxes.
212 Args:
213 statuses: list of status values to include (e.g. ['new', 'awaiting_admin'])
214 limit: page size (caller should clamp to a sane max)
215 cursor: opaque cursor from a previous call (or None for first page)
217 Returns:
218 {"items": [thread_dict, ...], "next_cursor": str | None}
220 Threads come back with an embedded `message_count` so the admin UI's
221 list view doesn't have to N+1.
222 """
223 query = (
224 self.client.table("email_threads")
225 .select("*, email_messages(count)")
226 .in_("status", statuses)
227 )
229 if cursor:
230 try:
231 ts, tid = decode_cursor(cursor)
232 except (ValueError, Exception) as e:
233 raise ValueError(f"invalid cursor: {e}") from e
234 # PostgREST keyset: (last_message_at < ts) OR (last_message_at = ts AND id < tid)
235 query = query.or_(
236 f"last_message_at.lt.{ts},"
237 f"and(last_message_at.eq.{ts},id.lt.{tid})"
238 )
240 response = (
241 query.order("last_message_at", desc=True)
242 .order("id", desc=True)
243 .limit(limit + 1)
244 .execute()
245 )
246 rows = response.data or []
248 # Flatten embedded message_count and trim peek row used for cursor calc.
249 for row in rows:
250 embedded = row.pop("email_messages", None) or []
251 row["message_count"] = embedded[0]["count"] if embedded else 0
253 next_cursor: str | None = None
254 if len(rows) > limit:
255 rows = rows[:limit]
256 last = rows[-1]
257 next_cursor = encode_cursor(last["last_message_at"], last["id"])
259 return {"items": rows, "next_cursor": next_cursor}
261 def get_thread_with_messages(self, thread_id: str) -> dict[str, Any] | None:
262 """Fetch a thread plus all its messages in one round trip.
264 Messages are sorted chronologically (oldest first) — the order the
265 admin UI renders.
266 """
267 response = (
268 self.client.table("email_threads")
269 .select("*, email_messages(*)")
270 .eq("id", thread_id)
271 .limit(1)
272 .execute()
273 )
274 if not response.data:
275 return None
276 row = response.data[0]
277 messages = row.pop("email_messages", None) or []
278 messages.sort(key=lambda m: m.get("created_at") or "")
279 row["messages"] = messages
280 return row
282 @invalidates_cache(EMAIL_THREADS_CACHE_PATTERN)
283 def transition_on_outbound(
284 self,
285 thread_id: str,
286 *,
287 last_message_at: str | None = None,
288 ) -> dict[str, Any] | None:
289 """An outbound admin reply was just sent on this thread.
291 Side effects:
292 - status → 'awaiting_user' (unconditional — admin has acted)
293 - last_message_at = max(existing, last_message_at)
295 Symmetric to transition_on_inbound. Does NOT bump unread_count
296 (outbound messages aren't "unread" from the admin's perspective).
297 """
298 updates: dict[str, Any] = {"status": "awaiting_user"}
299 if last_message_at:
300 updates["last_message_at"] = last_message_at
302 response = (
303 self.client.table("email_threads")
304 .update(updates)
305 .eq("id", thread_id)
306 .execute()
307 )
308 return response.data[0] if response.data else None
310 @invalidates_cache(EMAIL_THREADS_CACHE_PATTERN)
311 def set_status(self, thread_id: str, status: str) -> dict[str, Any] | None:
312 """Manual status override from an admin (resolved, spam, awaiting_admin).
314 Only the manual-override statuses are accepted here; auto-transitions
315 (new, awaiting_user) are owned by the inbound/outbound message paths.
316 """
317 if status not in _MANUAL_STATUSES:
318 raise ValueError(
319 f"status must be one of {sorted(_MANUAL_STATUSES)}, got {status!r}"
320 )
321 response = (
322 self.client.table("email_threads")
323 .update({"status": status})
324 .eq("id", thread_id)
325 .execute()
326 )
327 return response.data[0] if response.data else None
329 @invalidates_cache(EMAIL_THREADS_CACHE_PATTERN, EMAIL_MESSAGES_CACHE_PATTERN)
330 def mark_all_read(self, thread_id: str) -> int:
331 """Zero out the thread's unread_count and stamp read_at on every
332 previously-unread message. Returns the number of message rows updated.
333 """
334 now_iso = datetime.now(UTC).isoformat()
336 # Stamp unread messages first so we know how many actually changed.
337 msg_response = (
338 self.client.table("email_messages")
339 .update({"read_at": now_iso})
340 .eq("thread_id", thread_id)
341 .is_("read_at", None)
342 .execute()
343 )
344 updated_count = len(msg_response.data or [])
346 self.client.table("email_threads").update({"unread_count": 0}).eq(
347 "id", thread_id
348 ).execute()
350 return updated_count
352 def unread_count_for_attention(self) -> int:
353 """Sum of unread_count across threads that need admin attention.
355 Powers the Phase 3 nav badge. Cacheable upstream for ~30s.
356 """
357 response = (
358 self.client.table("email_threads")
359 .select("unread_count")
360 .in_("status", ["new", "awaiting_admin"])
361 .execute()
362 )
363 return sum((row.get("unread_count") or 0) for row in (response.data or []))