Coverage for services/email_outbound.py: 67.96%

81 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1""" 

2Outbound-reply primitives for the Support Inbox (SB-35 Phase 2). 

3 

4Pure helpers + a thin orchestrator the admin-API route can call to send 

5a reply on an existing thread. 

6 

7- generate_message_id() fresh RFC-5322 Message-ID, ours-namespaced 

8- prefix_subject_with_case_number() idempotent [MT-{n}] prefix 

9- build_references() References chain, deduped 

10- send_admin_reply() orchestrates: send via Resend + persist + transition 

11""" 

12 

13from __future__ import annotations 

14 

15import re 

16import uuid 

17from datetime import UTC, datetime 

18from typing import TYPE_CHECKING, Any 

19 

20import resend 

21import structlog 

22 

23from services.email_service import SUPPORT_EMAIL, ensure_resend_api_key 

24 

25if TYPE_CHECKING: 

26 from dao.email_messages_dao import EmailMessagesDAO 

27 from dao.email_threads_dao import EmailThreadsDAO 

28 

29logger = structlog.get_logger() 

30 

31 

32_MESSAGE_ID_DOMAIN = "missingtable.com" 

33_REPLY_PREFIX_RE = re.compile(r"^\s*(?:re|fwd?|fw)\s*:\s*", re.IGNORECASE) 

34 

35 

36def generate_message_id() -> str: 

37 """Return a stable, ours-namespaced Message-ID without angle brackets. 

38 

39 Storage form is angle-bracket-stripped for parity with inbound (we 

40 strip them at ingest). Callers wrap in `<>` when setting the actual 

41 Message-ID header on the outgoing email. 

42 """ 

43 return f"mt-{uuid.uuid4()}@{_MESSAGE_ID_DOMAIN}" 

44 

45 

46def prefix_subject_with_case_number(subject: str | None, case_number: int) -> str: 

47 """Ensure the subject carries `[MT-{case_number}]` and starts with `Re: `. 

48 

49 Idempotent: calling twice produces the same string. Examples (case_number=1): 

50 "My Question" → "Re: [MT-1] My Question" 

51 "Re: My Question" → "Re: [MT-1] My Question" 

52 "Re: Re: My Question" → "Re: [MT-1] My Question" 

53 "[MT-1] My Question" → "Re: [MT-1] My Question" 

54 "Re: [MT-1] My Question" → "Re: [MT-1] My Question" (unchanged) 

55 "Re: Re: [MT-1] My Question" → "Re: Re: [MT-1] My Question" (unchanged) 

56 """ 

57 raw = (subject or "").strip() 

58 token_re = re.compile(rf"\[\s*MT-{case_number}\s*\]", re.IGNORECASE) 

59 

60 if token_re.search(raw): 60 ↛ 62line 60 didn't jump to line 62 because the condition on line 60 was never true

61 # Already tagged — just make sure it reads like a reply. 

62 if _REPLY_PREFIX_RE.match(raw): 

63 return raw 

64 return f"Re: {raw}" 

65 

66 # Collapse any leading Re:/Fwd:/Fw: chain before inserting the tag. 

67 stripped = raw 

68 while True: 

69 nxt = _REPLY_PREFIX_RE.sub("", stripped, count=1) 

70 if nxt == stripped: 70 ↛ 72line 70 didn't jump to line 72 because the condition on line 70 was always true

71 break 

72 stripped = nxt 

73 

74 body = stripped or "(no subject)" 

75 return f"Re: [MT-{case_number}] {body}" 

76 

77 

78def build_references(existing_references: str | None, in_reply_to_id: str | None) -> str: 

79 """Append `in_reply_to_id` (angle-bracketed) to the existing References 

80 chain, deduped, whitespace-separated. Returns an empty string when both 

81 inputs are empty. 

82 """ 

83 ids: list[str] = (existing_references or "").split() 

84 if in_reply_to_id: 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 bracketed = ( 

86 in_reply_to_id if in_reply_to_id.startswith("<") else f"<{in_reply_to_id}>" 

87 ) 

88 if bracketed not in ids: 

89 ids.append(bracketed) 

90 return " ".join(ids) 

91 

92 

93def _strip_angle_brackets(value: str | None) -> str | None: 

94 """Mirror of the inbound webhook helper. RFC 5322 Message-IDs are wrapped 

95 in `<>`. Strip them for storage so equality lookups don't care about wrapping. 

96 """ 

97 if not value: 

98 return value 

99 s = value.strip() 

100 if s.startswith("<") and s.endswith(">"): 

101 return s[1:-1] 

102 return s 

103 

104 

105def _record_reply_sent( 

106 messages_dao: EmailMessagesDAO, 

107 row: dict[str, Any], 

108 response: Any, 

109 sent_at: str, 

110) -> None: 

111 """Store Resend's email id on the reply row with status 'sent' (SB-1821). 

112 

113 Never raises: Resend already accepted the reply, so failing here (e.g. the 

114 delivery columns are not migrated yet) only means the reply shows no 

115 delivery status. Nothing is recorded without an id, since no later event 

116 could ever move it past 'sent'. 

117 """ 

118 email_id = response.get("id") if isinstance(response, dict) else None 

119 if not isinstance(email_id, str) or not email_id or not row.get("id"): 

120 return 

121 try: 

122 update = messages_dao.record_reply_sent(row["id"], email_id, sent_at) 

123 except Exception as e: 

124 logger.error("admin_reply_email_id_not_recorded", message_row_id=row.get("id"), error=str(e)) 

125 return 

126 row.update(update) 

127 

128 

129def send_admin_reply( 

130 threads_dao: EmailThreadsDAO, 

131 messages_dao: EmailMessagesDAO, 

132 *, 

133 thread: dict[str, Any], 

134 body_text: str, 

135 body_html: str | None, 

136 admin_user_id: str, 

137) -> dict[str, Any]: 

138 """Send an outbound admin reply on a thread, then persist + transition. 

139 

140 Steps: 

141 1. Look up the latest inbound message to set In-Reply-To + extend References. 

142 2. Generate a fresh Message-ID; prefix the subject idempotently. 

143 3. Call `resend.Emails.send` (with `ensure_resend_api_key()` first — lesson 

144 #2 from Phase 1 applies here too). 

145 4. Persist the outbound message and transition the thread to `awaiting_user`. 

146 5. Best effort: record Resend's email id and status 'sent' on the row, so 

147 delivery webhooks can track the reply (SB-1821). 

148 

149 Returns the inserted message row. 

150 

151 Raises RuntimeError on send failure — caller maps to 5xx. 

152 """ 

153 latest_inbound = messages_dao.get_latest_inbound_for_thread(thread["id"]) 

154 

155 in_reply_to_stripped = ( 

156 latest_inbound["message_id"] if latest_inbound else None 

157 ) 

158 in_reply_to_bracketed = ( 

159 f"<{in_reply_to_stripped}>" if in_reply_to_stripped else None 

160 ) 

161 references = build_references( 

162 latest_inbound.get("references") if latest_inbound else None, 

163 in_reply_to_stripped, 

164 ) 

165 

166 subject = prefix_subject_with_case_number( 

167 thread.get("subject"), thread["case_number"] 

168 ) 

169 

170 message_id = generate_message_id() # stored stripped 

171 message_id_bracketed = f"<{message_id}>" 

172 

173 to_email = thread["participant_email"] 

174 

175 custom_headers: dict[str, str] = {"Message-ID": message_id_bracketed} 

176 if in_reply_to_bracketed: 176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true

177 custom_headers["In-Reply-To"] = in_reply_to_bracketed 

178 if references: 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true

179 custom_headers["References"] = references 

180 

181 payload: dict[str, Any] = { 

182 "from": SUPPORT_EMAIL, 

183 "to": [to_email], 

184 "subject": subject, 

185 "text": body_text, 

186 "headers": custom_headers, 

187 } 

188 if body_html: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 payload["html"] = body_html 

190 

191 ensure_resend_api_key() 

192 try: 

193 response = resend.Emails.send(payload) 

194 except Exception as e: 

195 logger.exception( 

196 "admin_reply_send_failed", 

197 thread_id=thread["id"], 

198 case_number=thread["case_number"], 

199 ) 

200 raise RuntimeError(f"failed to send admin reply: {e}") from e 

201 

202 now_iso = datetime.now(UTC).isoformat() 

203 row = messages_dao.insert_outbound( 

204 thread_id=thread["id"], 

205 message_id=message_id, 

206 from_email=SUPPORT_EMAIL, 

207 to_email=to_email, 

208 subject=subject, 

209 sent_by_user_id=admin_user_id, 

210 in_reply_to=in_reply_to_stripped, 

211 references=references or None, 

212 body_text=body_text, 

213 body_html=body_html, 

214 ) 

215 threads_dao.transition_on_outbound(thread["id"], last_message_at=now_iso) 

216 _record_reply_sent(messages_dao, row, response, now_iso) 

217 

218 logger.info( 

219 "admin_reply_sent", 

220 thread_id=thread["id"], 

221 case_number=thread["case_number"], 

222 message_id=message_id, 

223 admin_user_id=admin_user_id, 

224 ) 

225 return row