Coverage for api/channel_members.py: 28.49%

292 statements  

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

1""" 

2Channel access API (SB-1607): who may join which notification channel. 

3 

4- GET /api/teams/{team_id}/channels/available what the caller may see, always 200 

5- GET /api/me/channels[?team_id=] the same, with what the profile card needs 

6- POST /api/channels/{channel_id}/join join a channel the caller is entitled to 

7- POST /api/channels/{channel_id}/request ask a manager for access 

8- DELETE /api/channels/{channel_id}/request withdraw a pending request 

9- GET /api/channels/requests?team_id= pending requests a manager may decide 

10- GET /api/channels/members?team_id= active members a manager may revoke (SB-1671) 

11- GET /api/channels/{channel_id}/candidates fans a manager may invite (SB-1671) 

12- PUT /api/channels/{channel_id}/members/{user_id} approve, deny, invite or revoke 

13 

14The rules are in `notifications/membership.py`; the caller's standing comes from 

15`mt_tools/my_team.py`. A channel the caller may not see is 404, never 403, so a 

16fan cannot learn that a player channel exists. `destination` is never read here, 

17and `invite_url` is returned only to an active member who is still eligible. 

18""" 

19 

20from __future__ import annotations 

21 

22from datetime import UTC, datetime 

23from typing import Literal 

24 

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

26from pydantic import BaseModel 

27 

28from api.notification_channels import ChannelScope, _ensure_scope_access 

29from auth import get_current_user_required 

30from dao.channel_members_dao import ChannelMembersDAO, MemberWriteError 

31from dao.match_dao import SupabaseConnection 

32from dao.notification_channels_dao import actor_id 

33from mt_tools.my_team import ChannelViewer, channel_viewer 

34from notifications.adapters.base import UnsupportedPlatformError 

35from notifications.membership import ( 

36 Access, 

37 ChannelFacts, 

38 State, 

39 can_be_granted, 

40 channel_access, 

41 viewer_state, 

42) 

43from notifications.registry import get_adapter 

44 

45router = APIRouter(prefix="/api", tags=["channel-access"]) 

46 

47_connection: SupabaseConnection | None = None 

48 

49 

50def _dao() -> ChannelMembersDAO: 

51 global _connection 

52 if _connection is None: 

53 _connection = SupabaseConnection() 

54 return ChannelMembersDAO(_connection) 

55 

56 

57class AvailableChannel(BaseModel): 

58 id: int 

59 scope_type: str 

60 audience: str 

61 platform: str 

62 platform_label: str 

63 team_id: int | None 

64 age_group_id: int | None 

65 age_group_name: str | None 

66 state: State 

67 invite_url: str | None = None 

68 # The platform's minimum age, shown where the channel is offered (SB-1612). 

69 age_note: str | None = None 

70 

71 

72class SquadAgeGroup(BaseModel): 

73 id: int 

74 name: str 

75 

76 

77class MyChannels(BaseModel): 

78 """What the profile card renders (SB-1609). 

79 

80 `has_team`: the caller has a team or club to have channels for. 

81 `managed`: someone on MT manages that team or club (the claimed state); 

82 None when that could not be checked. 

83 `can_manage`: the caller manages it, so an empty card offers setup. 

84 `age_groups`: with `team_id` and `can_manage`, the squads the team is 

85 registered in, each of which can have channels. None when not asked for 

86 or when the lookup failed. 

87 """ 

88 

89 channels: list[AvailableChannel] 

90 # The club these channels belong to, for "Community channels for <club>" 

91 # (SB-1612). None when there is none, several, or the name could not be read. 

92 club_name: str | None = None 

93 has_team: bool 

94 managed: bool | None 

95 can_manage: bool 

96 age_groups: list[SquadAgeGroup] | None = None 

97 # Enabled channels this caller could see but that have no invite link yet 

98 # (SB-1671): the card then says "being set up", not "ask a manager". 

99 awaiting_link: int = 0 

100 

101 

102class MemberDecision(BaseModel): 

103 status: Literal["active", "denied", "revoked"] 

104 

105 

106class MemberOut(BaseModel): 

107 channel_id: int 

108 user_id: str 

109 status: str 

110 source: str 

111 

112 

113class PendingRequest(BaseModel): 

114 channel_id: int 

115 user_id: str 

116 display_name: str | None 

117 requested_at: str | None 

118 platform: str 

119 audience: str 

120 age_group_name: str | None 

121 

122 

123class ActiveMember(BaseModel): 

124 """Someone a manager can revoke (SB-1671). `source`: eligible, request or invite.""" 

125 

126 channel_id: int 

127 user_id: str 

128 display_name: str | None 

129 since: str | None 

130 source: str | None 

131 platform: str 

132 audience: str 

133 age_group_name: str | None 

134 

135 

136class InviteCandidate(BaseModel): 

137 user_id: str 

138 display_name: str | None 

139 

140 

141def _not_found() -> HTTPException: 

142 return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Channel not found") 

143 

144 

145def _caller_id(current_user: dict) -> str: 

146 user_id = actor_id(current_user) 

147 if user_id is None: 

148 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only a signed-in user can join channels") 

149 return user_id 

150 

151 

152def _viewer(dao: ChannelMembersDAO, user: dict, user_id: str) -> ChannelViewer: 

153 team_club = dao.team_club_id(user.get("team_id")) if user.get("club_id") is None else None 

154 squads = dao.current_squads(user_id) if (user.get("role") or "").replace("_", "-") == "team-player" else [] 

155 return channel_viewer(user, team_club, squads) 

156 

157 

158def _facts(dao: ChannelMembersDAO, row: dict, names: dict[int, str] | None = None) -> ChannelFacts: 

159 club_id = row.get("club_id") if row["scope_type"] != "team" else dao.team_club_id(row.get("team_id")) 

160 age_group_id = row.get("age_group_id") 

161 if names is None: 

162 names = dao.age_group_names({age_group_id} if age_group_id else set()) 

163 return ChannelFacts( 

164 scope_type=row["scope_type"], 

165 audience=row["audience"], 

166 club_id=club_id, 

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

168 age_group_id=age_group_id, 

169 age_group_name=names.get(age_group_id) if age_group_id else None, 

170 ) 

171 

172 

173def _joinable_link(row: dict) -> bool: 

174 """Only an enabled channel with an invite link can be joined.""" 

175 return bool(row.get("enabled")) and bool(row.get("invite_url")) 

176 

177 

178def _label(platform: str) -> str: 

179 try: 

180 return get_adapter(platform).label 

181 except UnsupportedPlatformError: 

182 return platform 

183 

184 

185def _age_note(platform: str) -> str | None: 

186 try: 

187 return get_adapter(platform).age_note 

188 except UnsupportedPlatformError: 

189 return None 

190 

191 

192def _to_available(row: dict, facts: ChannelFacts, state: State) -> AvailableChannel: 

193 return AvailableChannel( 

194 id=row["id"], 

195 scope_type=row["scope_type"], 

196 audience=row["audience"], 

197 platform=row["platform"], 

198 platform_label=_label(row["platform"]), 

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

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

201 age_group_name=facts.age_group_name, 

202 state=state, 

203 invite_url=row["invite_url"] if state == "member" else None, 

204 age_note=_age_note(row["platform"]), 

205 ) 

206 

207 

208def _visible_channel( 

209 dao: ChannelMembersDAO, channel_id: int, viewer: ChannelViewer 

210) -> tuple[dict, ChannelFacts, Access]: 

211 """The channel and the caller's access, or 404 when they may not see it.""" 

212 row = dao.channel(channel_id) 

213 if row is None or not _joinable_link(row): 

214 raise _not_found() 

215 facts = _facts(dao, row) 

216 access = channel_access(viewer, facts) 

217 if access == "hidden": 

218 raise _not_found() 

219 return row, facts, access 

220 

221 

222def _now() -> str: 

223 return datetime.now(UTC).isoformat() 

224 

225 

226@router.get("/teams/{team_id}/channels/available", response_model=list[AvailableChannel]) 

227def available_channels(team_id: int, current_user: dict = Depends(get_current_user_required)) -> list[AvailableChannel]: 

228 """The team's squad channels and its club's channels this caller may see. 

229 

230 An unknown team, a team with no channels, or channels without an invite link 

231 all answer 200 with an empty list. 

232 """ 

233 dao = _dao() 

234 user_id = actor_id(current_user) 

235 viewer = _viewer(dao, current_user, user_id) if user_id else channel_viewer(current_user, None, []) 

236 clubs = dao.team_clubs({team_id}) 

237 club_id = clubs.get(team_id) 

238 return _visible(dao, viewer, user_id, dao.channels_for_team(team_id, club_id), clubs) 

239 

240 

241def _visible( 

242 dao: ChannelMembersDAO, viewer: ChannelViewer, user_id: str | None, rows: list[dict], clubs: dict[int, int | None] 

243) -> list[AvailableChannel]: 

244 """The rows this viewer may see, with their state. `clubs` maps team id to club id.""" 

245 rows = [r for r in rows if _joinable_link(r)] 

246 names = dao.age_group_names({r["age_group_id"] for r in rows if r.get("age_group_id")}) 

247 statuses = dao.statuses(user_id, [r["id"] for r in rows]) if user_id else {} 

248 out: list[AvailableChannel] = [] 

249 for row in rows: 

250 facts = _row_facts(row, clubs, names) 

251 state = viewer_state(channel_access(viewer, facts), statuses.get(row["id"])) 

252 if state is not None: 

253 out.append(_to_available(row, facts, state)) 

254 return out 

255 

256 

257def _row_facts(row: dict, clubs: dict[int, int | None], names: dict[int, str]) -> ChannelFacts: 

258 return ChannelFacts( 

259 scope_type=row["scope_type"], 

260 audience=row["audience"], 

261 club_id=row.get("club_id") if row["scope_type"] == "club" else clubs.get(row.get("team_id")), 

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

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

264 age_group_name=names.get(row.get("age_group_id")), 

265 ) 

266 

267 

268def _awaiting_link( 

269 dao: ChannelMembersDAO, viewer: ChannelViewer, rows: list[dict], clubs: dict[int, int | None] 

270) -> int: 

271 """Enabled channels the viewer could see once they have an invite link.""" 

272 pending = [r for r in rows if r.get("enabled") and not r.get("invite_url")] 

273 if not pending: 

274 return 0 

275 names = dao.age_group_names({r["age_group_id"] for r in pending if r.get("age_group_id")}) 

276 return sum(channel_access(viewer, _row_facts(r, clubs, names)) != "hidden" for r in pending) 

277 

278 

279@router.get("/me/channels", response_model=MyChannels) 

280def my_channels(team_id: int | None = None, current_user: dict = Depends(get_current_user_required)) -> MyChannels: 

281 """Channels for the caller's own teams and club, or for `team_id` (the My Club page).""" 

282 dao = _dao() 

283 user_id = actor_id(current_user) 

284 viewer = _viewer(dao, current_user, user_id) if user_id else channel_viewer(current_user, None, []) 

285 if team_id is not None: 

286 team_ids = {team_id} 

287 clubs = dao.team_clubs(team_ids) 

288 club_ids = {c for c in clubs.values() if c is not None} 

289 can_manage = _can_manage(current_user, {"scope_type": "team", "team_id": team_id}) 

290 else: 

291 team_ids = {t for t in [current_user.get("team_id"), *(s.team_id for s in viewer.squads)] if t is not None} 

292 clubs = dao.team_clubs(team_ids) 

293 club_ids = {c for c in [viewer.club_id, *clubs.values(), *(s.club_id for s in viewer.squads)] if c is not None} 

294 can_manage = viewer.kind == "admin" or ( 

295 viewer.kind in ("club_manager", "team_manager") and bool(team_ids or club_ids) 

296 ) 

297 if not team_ids and not club_ids: 

298 return MyChannels(channels=[], has_team=False, managed=None, can_manage=False) 

299 rows = dao.channels_for_teams(team_ids, club_ids) 

300 squads = dao.team_age_groups(team_id) if team_id is not None and can_manage else None 

301 return MyChannels( 

302 channels=_visible(dao, viewer, user_id, rows, clubs), 

303 club_name=dao.club_name(next(iter(club_ids))) if len(club_ids) == 1 else None, 

304 has_team=True, 

305 managed=dao.is_managed(team_ids, club_ids), 

306 can_manage=can_manage, 

307 age_groups=None if squads is None else [SquadAgeGroup(**s) for s in squads], 

308 awaiting_link=_awaiting_link(dao, viewer, rows, clubs), 

309 ) 

310 

311 

312@router.post("/channels/{channel_id}/join", response_model=AvailableChannel) 

313def join_channel(channel_id: int, current_user: dict = Depends(get_current_user_required)) -> AvailableChannel: 

314 dao = _dao() 

315 user_id = _caller_id(current_user) 

316 row, facts, access = _visible_channel(dao, channel_id, _viewer(dao, current_user, user_id)) 

317 existing = dao.get(channel_id, user_id) 

318 if existing and existing["status"] in ("denied", "revoked"): 

319 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Ask a manager about this channel") 

320 if access != "joinable": 

321 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This channel needs a manager's approval") 

322 if not existing or existing["status"] != "active": 

323 try: 

324 dao.save(channel_id, user_id, {"status": "active", "source": "eligible", "decided_at": _now()}) 

325 except MemberWriteError: 

326 raise HTTPException(status_code=500, detail="Could not join the channel") from None 

327 return _to_available(row, facts, "member") 

328 

329 

330@router.post("/channels/{channel_id}/request", response_model=AvailableChannel) 

331def request_channel(channel_id: int, current_user: dict = Depends(get_current_user_required)) -> AvailableChannel: 

332 dao = _dao() 

333 user_id = _caller_id(current_user) 

334 row, facts, access = _visible_channel(dao, channel_id, _viewer(dao, current_user, user_id)) 

335 existing = dao.get(channel_id, user_id) 

336 current = existing["status"] if existing else None 

337 if current in ("denied", "revoked"): 

338 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Ask a manager about this channel") 

339 if current in ("requested", "active"): 

340 return _to_available(row, facts, viewer_state(access, current)) 

341 if access != "requestable": 

342 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="You can join this channel directly") 

343 try: 

344 dao.save(channel_id, user_id, {"status": "requested", "source": "request"}) 

345 except MemberWriteError: 

346 raise HTTPException(status_code=500, detail="Could not send the request") from None 

347 return _to_available(row, facts, "requested") 

348 

349 

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

351def withdraw_request(channel_id: int, current_user: dict = Depends(get_current_user_required)): 

352 dao = _dao() 

353 user_id = _caller_id(current_user) 

354 existing = dao.get(channel_id, user_id) 

355 if not existing or existing["status"] != "requested": 

356 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No pending request") 

357 try: 

358 dao.delete(channel_id, user_id) 

359 except MemberWriteError: 

360 raise HTTPException(status_code=500, detail="Could not withdraw the request") from None 

361 return Response(status_code=status.HTTP_204_NO_CONTENT) 

362 

363 

364def _scope(row: dict) -> ChannelScope: 

365 return ChannelScope( 

366 scope_type=row["scope_type"], 

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

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

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

370 ) 

371 

372 

373def _can_manage(current_user: dict, row: dict) -> bool: 

374 try: 

375 _ensure_scope_access(current_user, _scope(row)) 

376 except HTTPException: 

377 return False 

378 return True 

379 

380 

381def _managed_team_channels(dao: ChannelMembersDAO, team_id: int, current_user: dict) -> list[dict]: 

382 """This team's (and its club's) channels the caller manages; 403 when none.""" 

383 rows = [r for r in dao.channels_for_team(team_id, dao.team_club_id(team_id)) if _can_manage(current_user, r)] 

384 if not rows: 

385 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not allowed to review this team's channels") 

386 return rows 

387 

388 

389# Fan roles a manager can invite to a fan channel. Players join their own 

390# channels directly, so there is nobody to invite there. 

391_FAN_ROLES = ["team-fan", "club-fan", "team_fan", "club_fan"] 

392 

393 

394@router.get("/channels/members", response_model=list[ActiveMember]) 

395def active_members(team_id: int, current_user: dict = Depends(get_current_user_required)) -> list[ActiveMember]: 

396 """Who has access to this team's channels the caller manages, so it can be revoked (SB-1671).""" 

397 dao = _dao() 

398 rows = _managed_team_channels(dao, team_id, current_user) 

399 by_id = {r["id"]: r for r in rows} 

400 names = dao.age_group_names({r["age_group_id"] for r in rows if r.get("age_group_id")}) 

401 out = [] 

402 for grant in dao.with_status(list(by_id), "active"): 

403 channel = by_id[grant["channel_id"]] 

404 profile = grant.get("user_profiles") or {} 

405 out.append( 

406 ActiveMember( 

407 channel_id=grant["channel_id"], 

408 user_id=grant["user_id"], 

409 display_name=profile.get("display_name") or profile.get("username"), 

410 since=grant.get("decided_at") or grant.get("created_at"), 

411 source=grant.get("source"), 

412 platform=channel["platform"], 

413 audience=channel["audience"], 

414 age_group_name=names.get(channel.get("age_group_id")), 

415 ) 

416 ) 

417 return out 

418 

419 

420@router.get("/channels/{channel_id}/candidates", response_model=list[InviteCandidate]) 

421def invite_candidates( 

422 channel_id: int, current_user: dict = Depends(get_current_user_required) 

423) -> list[InviteCandidate]: 

424 """Fans a manager may invite to this fan channel without waiting for a request (SB-1671). 

425 

426 Only people the rules already let ask or join, minus anyone with access or 

427 a pending request. Empty for player channels: players join on their own. 

428 """ 

429 dao = _dao() 

430 row = dao.channel(channel_id) 

431 if row is None: 

432 raise _not_found() 

433 _ensure_scope_access(current_user, _scope(row)) 

434 if row["audience"] != "fans": 

435 return [] 

436 facts = _facts(dao, row) 

437 if facts.club_id is None: 

438 return [] 

439 taken = dao.granted_user_ids(channel_id) 

440 out = [] 

441 for person in dao.club_people(facts.club_id, _FAN_ROLES): 

442 if person["id"] in taken: 

443 continue 

444 if can_be_granted(channel_access(_viewer(dao, person, person["id"]), facts)): 

445 out.append( 

446 InviteCandidate(user_id=person["id"], display_name=person.get("display_name") or person.get("username")) 

447 ) 

448 return out 

449 

450 

451@router.get("/channels/requests", response_model=list[PendingRequest]) 

452def pending_requests(team_id: int, current_user: dict = Depends(get_current_user_required)) -> list[PendingRequest]: 

453 """Requests on this team's channels that the caller manages. Team managers included.""" 

454 dao = _dao() 

455 rows = _managed_team_channels(dao, team_id, current_user) 

456 by_id = {r["id"]: r for r in rows} 

457 names = dao.age_group_names({r["age_group_id"] for r in rows if r.get("age_group_id")}) 

458 out = [] 

459 for req in dao.requested(list(by_id)): 

460 channel = by_id[req["channel_id"]] 

461 profile = req.get("user_profiles") or {} 

462 out.append( 

463 PendingRequest( 

464 channel_id=req["channel_id"], 

465 user_id=req["user_id"], 

466 display_name=profile.get("display_name") or profile.get("username"), 

467 requested_at=req.get("created_at"), 

468 platform=channel["platform"], 

469 audience=channel["audience"], 

470 age_group_name=names.get(channel.get("age_group_id")), 

471 ) 

472 ) 

473 return out 

474 

475 

476@router.put("/channels/{channel_id}/members/{user_id}", response_model=MemberOut) 

477def decide_member( 

478 channel_id: int, 

479 user_id: str, 

480 body: MemberDecision, 

481 current_user: dict = Depends(get_current_user_required), 

482) -> MemberOut: 

483 """Approve or deny a request, invite someone, or revoke access. 

484 

485 `active` without a request is a manager invite. Either way the person must 

486 already be allowed to ask or join: no manager can put a fan in a player channel. 

487 """ 

488 dao = _dao() 

489 row = dao.channel(channel_id) 

490 if row is None: 

491 raise _not_found() 

492 _ensure_scope_access(current_user, _scope(row)) 

493 

494 existing = dao.get(channel_id, user_id) 

495 current = existing["status"] if existing else None 

496 fields = {"status": body.status, "decided_by": actor_id(current_user), "decided_at": _now()} 

497 

498 if body.status == "active": 

499 profile = dao.profile(user_id) 

500 if profile is None: 

501 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") 

502 target = _viewer(dao, profile, user_id) 

503 if not can_be_granted(channel_access(target, _facts(dao, row))): 

504 raise HTTPException( 

505 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

506 detail="This person can't be given access to this channel", 

507 ) 

508 fields["source"] = existing["source"] if current == "requested" else "invite" 

509 elif body.status == "denied": 

510 if current != "requested": 

511 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="There is no pending request to deny") 

512 fields["source"] = existing["source"] 

513 else: 

514 if current != "active": 

515 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This person has no access to revoke") 

516 fields["source"] = existing["source"] 

517 

518 try: 

519 saved = dao.save(channel_id, user_id, fields) 

520 except MemberWriteError: 

521 raise HTTPException(status_code=500, detail="Could not save channel access") from None 

522 return MemberOut(channel_id=channel_id, user_id=user_id, status=saved["status"], source=saved["source"])