Coverage for api/notification_channels.py: 31.49%

244 statements  

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

1""" 

2Scoped notification channels API (SB-1602). 

3 

4- GET /api/notification-channels 

5- GET /api/notification-channels/event-types 

6- POST /api/notification-channels 

7- PATCH /api/notification-channels/{id} 

8- DELETE /api/notification-channels/{id} 

9- POST /api/notification-channels/{id}/test 

10 

11Permissions by scope: global is admin only; a club needs admin or that club's 

12manager; a squad needs anyone who can manage the team. `destination` is 

13write-only: responses carry its last four characters as `hint`. 

14""" 

15 

16from __future__ import annotations 

17 

18from typing import Literal 

19 

20import structlog 

21from fastapi import APIRouter, Depends, HTTPException, Response, status 

22from pydantic import BaseModel, Field 

23 

24from api.club_notifications import check_rate_limit, ensure_club_access, is_notifications_enabled 

25from auth import AuthManager, get_current_user_required 

26from dao.match_dao import SupabaseConnection 

27from dao.notification_channels_dao import ( 

28 ChannelWriteError, 

29 DuplicateChannelError, 

30 NotificationChannelsDAO, 

31 actor_id, 

32) 

33from dao.notification_deliveries_dao import NotificationDeliveriesDAO 

34from notifications.adapters.base import ( 

35 Capability, 

36 ChannelAdapter, 

37 DeliveryError, 

38 InvalidDestinationError, 

39 NotificationConfigError, 

40 UnsupportedPlatformError, 

41) 

42from notifications.audience import player_channel_problem 

43from notifications.preferences import CHANNEL_EVENT_TYPES, EVENT_LABELS, is_player_only 

44from notifications.registry import get_adapter 

45 

46logger = structlog.get_logger(__name__) 

47 

48TEST_MESSAGE = "✅ Missing Table notification test: this channel is set up correctly." 

49TEST_THREAD_NAME = "Missing Table test" 

50TEST_THREAD_REPLY = "✅ Match updates will be posted as replies in each match's thread, like this one." 

51 

52router = APIRouter(prefix="/api/notification-channels", tags=["notification-channels"]) 

53 

54ScopeType = Literal["club", "team", "global"] 

55Audience = Literal["fans", "players"] 

56 

57_connection: SupabaseConnection | None = None 

58 

59 

60def _conn() -> SupabaseConnection: 

61 global _connection 

62 if _connection is None: 

63 _connection = SupabaseConnection() 

64 return _connection 

65 

66 

67def _dao() -> NotificationChannelsDAO: 

68 return NotificationChannelsDAO(_conn()) 

69 

70 

71def _deliveries() -> NotificationDeliveriesDAO: 

72 return NotificationDeliveriesDAO(_conn()) 

73 

74 

75class ChannelScope(BaseModel): 

76 scope_type: ScopeType 

77 club_id: int | None = None 

78 team_id: int | None = None 

79 age_group_id: int | None = None 

80 

81 

82class ChannelCreate(ChannelScope): 

83 audience: Audience = "fans" 

84 platform: str 

85 destination: str = Field(..., min_length=1, max_length=500) 

86 # None = every event; [] = none. Never collapse the two. 

87 event_types: list[str] | None = None 

88 enabled: bool = True 

89 # Shown to members, unlike destination; see api/channel_members.py. 

90 invite_url: str | None = Field(None, max_length=500) 

91 # A manager's own name for the channel; blank is stored as NULL. 

92 label: str | None = Field(None, max_length=80) 

93 # One post per match, updates inside it (SB-1606). Discord forum channels. 

94 post_as_threads: bool = False 

95 

96 

97class ChannelUpdate(BaseModel): 

98 destination: str | None = Field(None, min_length=1, max_length=500) 

99 event_types: list[str] | None = None 

100 enabled: bool | None = None 

101 invite_url: str | None = Field(None, max_length=500) 

102 # A manager's own name for the channel; blank is stored as NULL. 

103 label: str | None = Field(None, max_length=80) 

104 post_as_threads: bool | None = None 

105 

106 

107class LastDelivery(BaseModel): 

108 status: Literal["pending", "sent", "failed"] 

109 at: str | None = None 

110 # Sanitized when stored: never a destination, token or provider URL. 

111 error: str | None = None 

112 

113 

114class TestSendResult(BaseModel): 

115 success: bool 

116 error: str | None = None 

117 

118 

119class EventType(BaseModel): 

120 id: str 

121 label: str 

122 # Only a squad's player channel can carry it (SB-1610). 

123 player_only: bool = False 

124 

125 

126class ChannelOut(ChannelScope): 

127 id: int 

128 audience: Audience 

129 platform: str 

130 event_types: list[str] | None 

131 enabled: bool 

132 invite_url: str | None = None 

133 label: str | None = None 

134 post_as_threads: bool = False 

135 hint: str | None = Field(None, description="Last 4 chars of destination; full value never exposed") 

136 # None with last_delivery_known=True: nothing posted yet. With False: the 

137 # ledger could not be read, so the UI must not claim "nothing yet". 

138 last_delivery: LastDelivery | None = None 

139 last_delivery_known: bool = True 

140 

141 

142def _unprocessable(detail: str) -> HTTPException: 

143 return HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=detail) 

144 

145 

146def _last_delivery(row: dict | None) -> LastDelivery | None: 

147 if row is None: 

148 return None 

149 return LastDelivery( 

150 status=row["status"], 

151 at=row.get("updated_at") or row.get("created_at"), 

152 error=row.get("error") if row["status"] == "failed" else None, 

153 ) 

154 

155 

156def _to_out(row: dict, deliveries: dict[int, dict] | None) -> ChannelOut: 

157 """`deliveries` is latest_for()'s result: None when the ledger was unreadable.""" 

158 destination = row.get("destination") or "" 

159 return ChannelOut( 

160 id=row["id"], 

161 scope_type=row["scope_type"], 

162 club_id=row.get("club_id"), 

163 team_id=row.get("team_id"), 

164 age_group_id=row.get("age_group_id"), 

165 audience=row["audience"], 

166 platform=row["platform"], 

167 event_types=row.get("event_types"), 

168 enabled=bool(row["enabled"]), 

169 invite_url=row.get("invite_url"), 

170 label=row.get("label"), 

171 post_as_threads=bool(row.get("post_as_threads")), 

172 hint=destination[-4:] if destination else None, 

173 last_delivery=_last_delivery((deliveries or {}).get(row["id"])), 

174 last_delivery_known=deliveries is not None, 

175 ) 

176 

177 

178def _with_deliveries(rows: list[dict]) -> list[ChannelOut]: 

179 deliveries = _deliveries().latest_for([row["id"] for row in rows]) if rows else {} 

180 return [_to_out(row, deliveries) for row in rows] 

181 

182 

183def _clean_label(fields: dict) -> None: 

184 """Trim the label in place; blank means none.""" 

185 if "label" in fields and fields["label"] is not None: 

186 fields["label"] = fields["label"].strip() or None 

187 

188 

189def _require_scope_shape(scope: ChannelScope) -> None: 

190 """Exactly the identifiers this scope uses, so the database CHECK is never the first to say so.""" 

191 shape = (scope.club_id is not None, scope.team_id is not None, scope.age_group_id is not None) 

192 expected = {"club": (True, False, False), "team": (False, True, True), "global": (False, False, False)} 

193 if shape != expected[scope.scope_type]: 

194 raise _unprocessable( 

195 { 

196 "club": "A club channel needs club_id only", 

197 "team": "A team channel needs team_id and age_group_id only", 

198 "global": "A global channel takes no club, team or age group", 

199 }[scope.scope_type] 

200 ) 

201 

202 

203def _ensure_scope_access(current_user: dict, scope: ChannelScope) -> None: 

204 allowed = True 

205 if scope.scope_type == "global": 

206 allowed = current_user.get("role") == "admin" 

207 elif scope.scope_type == "club": 

208 ensure_club_access(current_user, scope.club_id) 

209 else: 

210 allowed = AuthManager(_conn().get_client()).can_manage_team(current_user, scope.team_id) 

211 if not allowed: 

212 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not allowed to manage this channel") 

213 

214 

215def _adapter(platform: str) -> ChannelAdapter: 

216 try: 

217 return get_adapter(platform) 

218 except UnsupportedPlatformError: 

219 raise _unprocessable("Unknown platform") from None 

220 

221 

222def _validate_destination(adapter: ChannelAdapter, destination: str) -> None: 

223 try: 

224 adapter.validate_destination(destination) 

225 except InvalidDestinationError as exc: 

226 raise _unprocessable(str(exc)) from None 

227 

228 

229def _validate_invite_url(adapter: ChannelAdapter, invite_url: str | None) -> None: 

230 """None clears the link; anything else must be the platform's private join link.""" 

231 if invite_url is None: 

232 return 

233 try: 

234 adapter.validate_invite_url(invite_url) 

235 except InvalidDestinationError as exc: 

236 raise _unprocessable(str(exc)) from None 

237 

238 

239def _validate_event_types( 

240 event_types: list[str] | None, scope_type: str | None = None, audience: str | None = None 

241) -> None: 

242 unknown = sorted(set(event_types or []) - set(CHANNEL_EVENT_TYPES)) 

243 if unknown: 

244 raise _unprocessable(f"Unknown event types: {', '.join(unknown)}") 

245 player_only = sorted(e for e in (event_types or []) if is_player_only(e)) 

246 if player_only and (scope_type != "team" or audience != "players"): 

247 labels = ", ".join(EVENT_LABELS[e] for e in player_only) 

248 raise _unprocessable(f"{labels} can only go to a squad's player channel") 

249 

250 

251def _validate_threads(post_as_threads: bool | None, platform: str, scope_type: str, audience: str | None) -> None: 

252 """Match threads need a platform that has them (SB-1606). 

253 

254 A club players room stays flat: read-only permissions are not confirmed to 

255 work with forum posts. 

256 """ 

257 if not post_as_threads: 

258 return 

259 if Capability.THREADS not in _adapter(platform).capabilities: 

260 raise _unprocessable(f"{_adapter(platform).label} channels can't post match threads") 

261 if scope_type == "club" and audience == "players": 

262 raise _unprocessable("A club players channel posts flat; match threads are for squad and fan channels") 

263 

264 

265def _age_group_name(age_group_id: int) -> str: 

266 rows = _conn().get_client().table("age_groups").select("name").eq("id", age_group_id).limit(1).execute().data 

267 if not rows: 

268 raise _unprocessable("Unknown age group") 

269 return rows[0]["name"] 

270 

271 

272def _validate_audience(body: ChannelCreate, adapter: ChannelAdapter) -> None: 

273 if body.scope_type == "global" and body.audience != "fans": 

274 raise _unprocessable("A global channel is for fans") 

275 age_group_name = _age_group_name(body.age_group_id) if body.scope_type == "team" else None 

276 if body.audience == "players": 

277 problem = player_channel_problem(adapter, age_group_name) 

278 if problem: 

279 raise _unprocessable(problem) 

280 

281 

282@router.get("/event-types", response_model=list[EventType]) 

283def list_event_types(current_user: dict = Depends(get_current_user_required)) -> list[EventType]: 

284 """The events a channel can be limited to, in display order.""" 

285 return [ 

286 EventType(id=event, label=EVENT_LABELS[event], player_only=is_player_only(event)) 

287 for event in CHANNEL_EVENT_TYPES 

288 ] 

289 

290 

291@router.get("", response_model=list[ChannelOut]) 

292def list_channels( 

293 scope_type: ScopeType, 

294 club_id: int | None = None, 

295 team_id: int | None = None, 

296 age_group_id: int | None = None, 

297 current_user: dict = Depends(get_current_user_required), 

298) -> list[ChannelOut]: 

299 scope = ChannelScope(scope_type=scope_type, club_id=club_id, team_id=team_id, age_group_id=age_group_id) 

300 _require_scope_shape(scope) 

301 _ensure_scope_access(current_user, scope) 

302 return _with_deliveries(_dao().list_for_scope(scope_type, club_id, team_id, age_group_id)) 

303 

304 

305@router.post("", response_model=ChannelOut, status_code=status.HTTP_201_CREATED) 

306def create_channel( 

307 body: ChannelCreate, 

308 current_user: dict = Depends(get_current_user_required), 

309) -> ChannelOut: 

310 _require_scope_shape(body) 

311 _ensure_scope_access(current_user, body) 

312 adapter = _adapter(body.platform) 

313 _validate_destination(adapter, body.destination) 

314 _validate_invite_url(adapter, body.invite_url) 

315 _validate_event_types(body.event_types, body.scope_type, body.audience) 

316 _validate_threads(body.post_as_threads, body.platform, body.scope_type, body.audience) 

317 _validate_audience(body, adapter) 

318 fields = body.model_dump() 

319 _clean_label(fields) 

320 try: 

321 row = _dao().create({**fields, "created_by": actor_id(current_user)}) 

322 except DuplicateChannelError: 

323 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="That channel already exists") from None 

324 except ChannelWriteError: 

325 raise HTTPException(status_code=500, detail="Failed to save notification channel") from None 

326 # A new channel has posted nothing, so that is known without asking. 

327 return _to_out(row, {}) 

328 

329 

330def _owned_channel(channel_id: int, current_user: dict) -> dict: 

331 """The channel, once the caller is cleared for its scope. Absent is 404.""" 

332 row = _dao().get_by_id(channel_id) 

333 if row is None: 

334 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Channel not found") 

335 _ensure_scope_access( 

336 current_user, 

337 ChannelScope( 

338 scope_type=row["scope_type"], 

339 club_id=row.get("club_id"), 

340 team_id=row.get("team_id"), 

341 age_group_id=row.get("age_group_id"), 

342 ), 

343 ) 

344 return row 

345 

346 

347@router.patch("/{channel_id}", response_model=ChannelOut) 

348def update_channel( 

349 channel_id: int, 

350 body: ChannelUpdate, 

351 current_user: dict = Depends(get_current_user_required), 

352) -> ChannelOut: 

353 row = _owned_channel(channel_id, current_user) 

354 # exclude_unset: an explicit `event_types: null` means "every event". 

355 fields = body.model_dump(exclude_unset=True) 

356 if fields.get("destination") is not None: 

357 _validate_destination(_adapter(row["platform"]), fields["destination"]) 

358 elif "destination" in fields: 

359 raise _unprocessable("destination cannot be null") 

360 if "enabled" in fields and fields["enabled"] is None: 

361 raise _unprocessable("enabled cannot be null") 

362 _validate_event_types(fields.get("event_types"), row["scope_type"], row.get("audience")) 

363 if "post_as_threads" in fields: 

364 if fields["post_as_threads"] is None: 

365 raise _unprocessable("post_as_threads cannot be null") 

366 _validate_threads(fields["post_as_threads"], row["platform"], row["scope_type"], row.get("audience")) 

367 if "invite_url" in fields: 

368 _validate_invite_url(_adapter(row["platform"]), fields["invite_url"]) 

369 _clean_label(fields) 

370 if not fields: 

371 return _with_deliveries([row])[0] 

372 try: 

373 updated = _dao().update(channel_id, fields) 

374 except DuplicateChannelError: 

375 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="That channel already exists") from None 

376 except ChannelWriteError: 

377 raise HTTPException(status_code=500, detail="Failed to save notification channel") from None 

378 if updated is None: 

379 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Channel not found") 

380 return _with_deliveries([updated])[0] 

381 

382 

383@router.delete("/{channel_id}", status_code=status.HTTP_204_NO_CONTENT, response_class=Response) 

384def delete_channel( 

385 channel_id: int, 

386 current_user: dict = Depends(get_current_user_required), 

387): 

388 _owned_channel(channel_id, current_user) 

389 try: 

390 _dao().delete_by_id(channel_id) 

391 except ChannelWriteError: 

392 raise HTTPException(status_code=500, detail="Failed to delete notification channel") from None 

393 return Response(status_code=status.HTTP_204_NO_CONTENT) 

394 

395 

396def _test_error(exc: Exception) -> str: 

397 """What a manager is told. Never a destination, env var or stack detail.""" 

398 if isinstance(exc, DeliveryError): 

399 return str(exc) 

400 if isinstance(exc, NotificationConfigError): 

401 return "This platform is not available on Missing Table right now. Contact support." 

402 return "The test message could not be sent" 

403 

404 

405@router.post("/{channel_id}/test", response_model=TestSendResult) 

406def test_channel( 

407 channel_id: int, 

408 current_user: dict = Depends(get_current_user_required), 

409) -> TestSendResult: 

410 """Post a test message. Not recorded in the delivery ledger: it is not a match event.""" 

411 row = _owned_channel(channel_id, current_user) 

412 if not is_notifications_enabled(): 

413 raise HTTPException( 

414 status_code=status.HTTP_503_SERVICE_UNAVAILABLE, 

415 detail="Notifications are turned off on Missing Table right now", 

416 ) 

417 if not check_rate_limit(f"ratelimit:notify-test:channel:{channel_id}", max_per_minute=5): 

418 raise HTTPException( 

419 status_code=status.HTTP_429_TOO_MANY_REQUESTS, 

420 detail="Too many test messages. Wait a minute and try again.", 

421 ) 

422 adapter = _adapter(row["platform"]) 

423 try: 

424 if row.get("post_as_threads") and Capability.THREADS in adapter.capabilities: 

425 # A forum channel: create a test post, then reply into it with the 

426 # id that came back, which proves follow-ups find their thread. 

427 first = adapter.send_in_thread(row["destination"], TEST_MESSAGE, None, TEST_THREAD_NAME) 

428 if not first.thread_ref: 

429 return TestSendResult(success=False, error="The post was created, but its thread id did not come back") 

430 adapter.send_in_thread(row["destination"], TEST_THREAD_REPLY, first.thread_ref, None) 

431 else: 

432 adapter.send(row["destination"], TEST_MESSAGE) 

433 except Exception as exc: 

434 logger.warning("channel_test_send_failed", channel_id=channel_id, error_type=type(exc).__name__) 

435 return TestSendResult(success=False, error=_test_error(exc)) 

436 return TestSendResult(success=True)