Coverage for api/admin_emails.py: 44.35%
99 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Admin API for the Support Inbox (SB-35 Phase 2).
4Exposes the JSON surface the Phase 3 admin UI will consume:
6 GET /api/admin/emails/threads list w/ keyset pagination
7 GET /api/admin/emails/threads/{id_or_mt_n} thread + messages
8 POST /api/admin/emails/threads/{id}/reply send outbound + persist
9 PATCH /api/admin/emails/threads/{id}/status manual status override
10 PATCH /api/admin/emails/threads/{id}/read zero unread_count + stamp read_at
11 GET /api/admin/emails/unread-count attention badge
13All endpoints gated by `require_admin`. Admin operations use the service-role
14client (same project pattern as backend/api/invites.py) so the auth dependency
15is the trust gate.
16"""
18from __future__ import annotations
20import os
21import re
22import sys
23from typing import Any, Literal
25import structlog
26from fastapi import APIRouter, Depends, HTTPException, Query
27from pydantic import BaseModel, Field
29from supabase import create_client
31sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
33from auth import require_admin
34from dao.email_messages_dao import EmailMessagesDAO
35from dao.email_threads_dao import EmailThreadsDAO
36from dao.match_dao import SupabaseConnection as DbConnectionHolder
37from services.email_outbound import send_admin_reply
39logger = structlog.get_logger(__name__)
41# Service-role connection for admin reads/writes. require_admin is the trust
42# gate — same pattern as backend/api/invites.py.
43_supabase_url = os.getenv("SUPABASE_URL", "")
44_service_key = os.getenv("SUPABASE_SERVICE_KEY")
45if _service_key: 45 ↛ 53line 45 didn't jump to line 53 because the condition on line 45 was always true
46 _service_client = create_client(_supabase_url, _service_key)
47 _conn_holder = DbConnectionHolder()
48 # Pin the DAO's client to the service-role client by reaching into the
49 # holder. Mirrors how invites.py uses service_client directly but keeps
50 # the DAOs' query surface.
51 _conn_holder.client = _service_client
52else:
53 _conn_holder = DbConnectionHolder()
55_threads_dao = EmailThreadsDAO(_conn_holder)
56_messages_dao = EmailMessagesDAO(_conn_holder)
58router = APIRouter(prefix="/api/admin/emails", tags=["admin-emails"])
61# ── Constants ────────────────────────────────────────────────────────────────
63_DEFAULT_STATUSES = ("new", "awaiting_admin")
64_ALL_STATUSES = frozenset(
65 {"new", "awaiting_admin", "awaiting_user", "resolved", "spam"}
66)
67_MT_PATH_RE = re.compile(r"^MT-(\d+)$", re.IGNORECASE)
68_LIMIT_DEFAULT = 50
69_LIMIT_MAX = 200
72# ── Pydantic models ──────────────────────────────────────────────────────────
75class ReplyRequest(BaseModel):
76 body_text: str = Field(..., min_length=1)
77 body_html: str | None = None
80class StatusUpdateRequest(BaseModel):
81 status: Literal["resolved", "spam", "awaiting_admin"]
84# ── Helpers ──────────────────────────────────────────────────────────────────
87def _admin_user_id(current_user: dict[str, Any]) -> str:
88 """Pluck the user id out of the auth payload. Different code paths populate
89 different keys (id / user_id / sub) — same fallback chain as invites.py.
90 """
91 user_id = (
92 current_user.get("id")
93 or current_user.get("user_id")
94 or current_user.get("sub")
95 )
96 if not user_id:
97 raise HTTPException(status_code=400, detail="user id missing from auth payload")
98 return user_id
101def _resolve_thread_or_404(thread_id_or_case_number: str) -> dict[str, Any]:
102 """Path-param resolver: accepts either a UUID or `MT-{n}` form."""
103 mt_match = _MT_PATH_RE.match(thread_id_or_case_number)
104 if mt_match:
105 case_number = int(mt_match.group(1))
106 thread = _threads_dao.get_by_case_number(case_number)
107 else:
108 thread = _threads_dao.get_thread_by_id(thread_id_or_case_number)
110 if not thread:
111 raise HTTPException(
112 status_code=404, detail=f"thread {thread_id_or_case_number!r} not found"
113 )
114 return thread
117def _parse_statuses(raw: str | None) -> list[str]:
118 if not raw:
119 return list(_DEFAULT_STATUSES)
120 values = [v.strip() for v in raw.split(",") if v.strip()]
121 invalid = [v for v in values if v not in _ALL_STATUSES]
122 if invalid:
123 raise HTTPException(
124 status_code=400, detail=f"invalid status value(s): {invalid}"
125 )
126 return values
129# ── Endpoints ────────────────────────────────────────────────────────────────
132@router.get("/threads")
133async def list_threads(
134 status: str | None = Query(
135 default=None,
136 description="CSV of status values; default 'new,awaiting_admin'.",
137 ),
138 cursor: str | None = Query(default=None),
139 limit: int = Query(default=_LIMIT_DEFAULT, ge=1, le=_LIMIT_MAX),
140 _admin: dict[str, Any] = Depends(require_admin),
141) -> dict[str, Any]:
142 """Paginated list of threads. Keyset cursor on (last_message_at, id)."""
143 statuses = _parse_statuses(status)
144 try:
145 return _threads_dao.list_by_status(statuses, limit=limit, cursor=cursor)
146 except ValueError as e:
147 raise HTTPException(status_code=400, detail=str(e)) from e
150@router.get("/unread-count")
151async def get_unread_count(
152 _admin: dict[str, Any] = Depends(require_admin),
153) -> dict[str, int]:
154 """Sum of unread_count across threads in (new, awaiting_admin)."""
155 return {"count": _threads_dao.unread_count_for_attention()}
158@router.get("/threads/{thread_id_or_case_number}")
159async def get_thread(
160 thread_id_or_case_number: str,
161 _admin: dict[str, Any] = Depends(require_admin),
162) -> dict[str, Any]:
163 """Thread + all messages in chronological order. Accepts UUID or `MT-{n}`."""
164 # Resolve to UUID first, then fetch with embedded messages.
165 thread = _resolve_thread_or_404(thread_id_or_case_number)
166 full = _threads_dao.get_thread_with_messages(thread["id"])
167 if not full:
168 # Could only happen on a race with deletion.
169 raise HTTPException(status_code=404, detail="thread not found")
170 return full
173@router.post("/threads/{thread_id}/reply")
174async def reply_to_thread(
175 thread_id: str,
176 request: ReplyRequest,
177 current_user: dict[str, Any] = Depends(require_admin),
178) -> dict[str, Any]:
179 """Send an outbound reply on the thread.
181 - Generates a fresh Message-ID and threads correctly via In-Reply-To/References.
182 - Idempotently prefixes the subject with [MT-{n}].
183 - Persists the outbound message and transitions the thread to awaiting_user.
184 """
185 thread = _resolve_thread_or_404(thread_id)
186 admin_user_id = _admin_user_id(current_user)
188 try:
189 row = send_admin_reply(
190 _threads_dao,
191 _messages_dao,
192 thread=thread,
193 body_text=request.body_text,
194 body_html=request.body_html,
195 admin_user_id=admin_user_id,
196 )
197 except RuntimeError as e:
198 raise HTTPException(status_code=502, detail=str(e)) from e
200 return row
203@router.patch("/threads/{thread_id}/status")
204async def patch_status(
205 thread_id: str,
206 request: StatusUpdateRequest,
207 _admin: dict[str, Any] = Depends(require_admin),
208) -> dict[str, Any]:
209 """Manual status override (resolved / spam / awaiting_admin)."""
210 thread = _resolve_thread_or_404(thread_id)
211 try:
212 updated = _threads_dao.set_status(thread["id"], request.status)
213 except ValueError as e:
214 raise HTTPException(status_code=400, detail=str(e)) from e
215 if not updated:
216 raise HTTPException(status_code=404, detail="thread not found")
217 return updated
220@router.patch("/threads/{thread_id}/read")
221async def mark_read(
222 thread_id: str,
223 _admin: dict[str, Any] = Depends(require_admin),
224) -> dict[str, Any]:
225 """Zero unread_count and stamp read_at on every unread message."""
226 thread = _resolve_thread_or_404(thread_id)
227 updated = _threads_dao.mark_all_read(thread["id"])
228 return {"thread_id": thread["id"], "messages_marked_read": updated}