Coverage for services/invite_service.py: 54.98%

453 statements  

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

1""" 

2Invite Service for Missing Table 

3Handles invite code generation, validation, and management 

4""" 

5 

6import hashlib 

7import logging 

8import secrets 

9from datetime import UTC, datetime, timedelta 

10from enum import Enum 

11 

12from dao.base_dao import clear_cache 

13from supabase import Client 

14 

15logger = logging.getLogger(__name__) 

16 

17 

18def invite_code_ref(code: str | None) -> str: 

19 """A log-safe reference to an invite code: a sha256 prefix, never the code (SB-1768). 

20 

21 A code is a bearer credential for signing up and reveals the invite's team, 

22 club and player, so the raw value must not reach the logs. The same code 

23 always maps to the same ref, so log lines about one invite still correlate. 

24 """ 

25 if not code: 

26 return "none" 

27 # surrogatepass: a lone surrogate (a JSON "\ud800" escape) must not raise here. 

28 return hashlib.sha256(code.encode("utf-8", "surrogatepass")).hexdigest()[:8] 

29 

30 

31class RedeemResult(Enum): 

32 """How a redemption ended (SB-1864). 

33 

34 Only UNAVAILABLE says the invite is not this caller's: it was used, expired 

35 or missing, or another redemption won the guarded update. ERROR means the 

36 database failed and the invite's state is unknown, so a caller must not 

37 treat it as a lost race. 

38 """ 

39 

40 REDEEMED = "redeemed" 

41 UNAVAILABLE = "unavailable" 

42 ERROR = "error" 

43 

44 

45class InviteService: 

46 """Service for managing invitations""" 

47 

48 def __init__(self, supabase_client: Client): 

49 self.supabase = supabase_client 

50 # Characters for invite codes (avoiding ambiguous characters) 

51 self.code_chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" 

52 

53 def generate_invite_code(self) -> str: 

54 """Generate a unique 12-character invite code""" 

55 max_attempts = 100 

56 

57 for _ in range(max_attempts): 

58 # Generate random code 

59 code = "".join(secrets.choice(self.code_chars) for _ in range(12)) 

60 

61 # Check if code already exists 

62 response = self.supabase.table("invitations").select("id").eq("invite_code", code).execute() 

63 

64 if not response.data: 

65 return code 

66 

67 raise Exception("Could not generate unique invite code after 100 attempts") 

68 

69 def _get_current_season_id(self) -> int | None: 

70 """Current season id — prefers the admin-set is_current flag, falling 

71 back to the date-spanning season (matches season_dao.get_current_season).""" 

72 try: 

73 flagged = self.supabase.table("seasons").select("id").eq("is_current", True).limit(1).execute() 

74 if flagged.data: 74 ↛ 77line 74 didn't jump to line 77 because the condition on line 74 was always true

75 return flagged.data[0]["id"] 

76 

77 from datetime import date 

78 

79 today = date.today().isoformat() 

80 response = ( 

81 self.supabase.table("seasons") 

82 .select("id") 

83 .lte("start_date", today) 

84 .gte("end_date", today) 

85 .limit(1) 

86 .execute() 

87 ) 

88 return response.data[0]["id"] if response.data else None 

89 except Exception as e: 

90 logger.error(f"Error resolving current season: {e}") 

91 return None 

92 

93 def _find_roster_spot( 

94 self, 

95 team_id: int, 

96 season_id: int, 

97 jersey_number: int, 

98 age_group_id: int | None, 

99 ) -> dict | None: 

100 """Find the roster row a jersey-number invite would claim. 

101 

102 Scoped to the age group to match the players unique constraint 

103 (team, season, age_group, jersey) - umbrella teams can field the same 

104 number in several squads. age_group_id=None matches NULL rows only. 

105 """ 

106 try: 

107 query = ( 

108 self.supabase.table("players") 

109 .select("id, user_profile_id, first_name, last_name") 

110 .eq("team_id", team_id) 

111 .eq("season_id", season_id) 

112 .eq("jersey_number", jersey_number) 

113 ) 

114 if age_group_id is None: 

115 query = query.is_("age_group_id", "null") 

116 else: 

117 query = query.eq("age_group_id", age_group_id) 

118 response = query.limit(1).execute() 

119 return response.data[0] if response.data else None 

120 except Exception as e: 

121 logger.error(f"Error looking up roster spot: {e}") 

122 return None 

123 

124 def create_invitation( 

125 self, 

126 invited_by_user_id: str, 

127 invite_type: str, 

128 team_id: int | None = None, 

129 age_group_id: int | None = None, 

130 club_id: int | None = None, 

131 email: str | None = None, 

132 player_id: int | None = None, 

133 jersey_number: int | None = None, 

134 expires_in_days: int = 7, 

135 note: str | None = None, 

136 season_id: int | None = None, 

137 ios_beta: bool = False, 

138 testflight_email: str | None = None, 

139 ) -> dict: 

140 """ 

141 Create a new invitation 

142 

143 Args: 

144 invited_by_user_id: ID of the user creating the invite 

145 invite_type: Type of invite ('club_manager', 'club_fan', 'team_manager', 'team_player', 'team_fan') 

146 team_id: ID of the team (required for team-level invite types) 

147 age_group_id: ID of the age group (required for team-level invite types) 

148 club_id: ID of the club (required for club_manager and club_fan invite types) 

149 email: Optional email to pre-fill during registration 

150 player_id: Optional roster entry ID (for team_player invites - links account to existing roster) 

151 jersey_number: Optional jersey number (for team_player invites - claims roster on redemption) 

152 expires_in_days: Number of days until invite expires 

153 season_id: Season the invite applies to (team_player roster claims). 

154 Defaults to the current season by date, stored on the invite so 

155 redemption doesn't guess. 

156 ios_beta: Also add the invitee to the external TestFlight group 

157 (SB-1314). Admin-only; the API layer enforces that. 

158 testflight_email: Apple Account email for TestFlight. Defaults to 

159 ``email`` - the two often differ. 

160 

161 Returns: 

162 Created invitation record 

163 

164 Raises: 

165 ValueError: On invalid parameters, including a team_player 

166 jersey-number invite with no matching unclaimed roster spot - 

167 caught at creation so the admin fixes it, not the registrant. 

168 """ 

169 try: 

170 if ios_beta: 

171 testflight_email = (testflight_email or email or "").strip() or None 

172 if not testflight_email: 

173 raise ValueError("A TestFlight email is required for an iPhone beta invite") 

174 else: 

175 testflight_email = None 

176 # Name for the TestFlight tester, when the invite is for a known roster spot. 

177 tester_name: tuple[str | None, str | None] = (None, None) 

178 

179 # Validate parameters based on invite type 

180 if invite_type in ("club_manager", "club_fan"): 

181 if not club_id: 

182 raise ValueError(f"club_id is required for {invite_type} invites") 

183 # Club-level invites don't need team_id or age_group_id 

184 team_id = None 

185 age_group_id = None 

186 player_id = None # No roster linking for club-level invites 

187 jersey_number = None 

188 season_id = None 

189 else: 

190 if not team_id: 

191 raise ValueError("team_id is required for team-level invites") 

192 if not age_group_id: 

193 raise ValueError("age_group_id is required for team-level invites") 

194 # Derive club_id from the team's parent club 

195 club_id = self._get_team_club_id(team_id) 

196 

197 if invite_type == "team_player": 

198 # Pin the season at creation time (SB-287). 

199 if season_id is None: 199 ↛ 206line 199 didn't jump to line 206 because the condition on line 199 was always true

200 season_id = self._get_current_season_id() 

201 if season_id is None: 

202 raise ValueError("No current season found; pass season_id explicitly") 

203 

204 # A jersey-number invite must point at an existing, unclaimed 

205 # roster spot - blocking here beats blocking the kid at signup. 

206 if jersey_number and not player_id: 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true

207 spot = self._find_roster_spot(team_id, season_id, jersey_number, age_group_id) 

208 if spot is None: 

209 raise ValueError( 

210 f"No roster spot with jersey #{jersey_number} for this " 

211 f"team/season/age group. Add the player to the roster first." 

212 ) 

213 if spot.get("user_profile_id"): 

214 raise ValueError(f"Jersey #{jersey_number} is already claimed by another account.") 

215 player_id = spot["id"] 

216 tester_name = (spot.get("first_name"), spot.get("last_name")) 

217 elif player_id: 217 ↛ 219line 217 didn't jump to line 219 because the condition on line 217 was never true

218 # Direct roster-entry invite: verify it exists and is unclaimed. 

219 check = ( 

220 self.supabase.table("players") 

221 .select("id, user_profile_id, jersey_number, first_name, last_name") 

222 .eq("id", player_id) 

223 .limit(1) 

224 .execute() 

225 ) 

226 if not check.data: 

227 raise ValueError("That roster entry no longer exists.") 

228 if check.data[0].get("user_profile_id"): 

229 raise ValueError("That roster spot is already claimed by another account.") 

230 jersey_number = jersey_number or check.data[0].get("jersey_number") 

231 tester_name = (check.data[0].get("first_name"), check.data[0].get("last_name")) 

232 else: 

233 season_id = None 

234 

235 # Generate unique invite code 

236 invite_code = self.generate_invite_code() 

237 

238 # Calculate expiration date 

239 expires_at = datetime.now(UTC) + timedelta(days=expires_in_days) 

240 

241 # Create invitation record 

242 invitation_data = { 

243 "invite_code": invite_code, 

244 "invited_by_user_id": invited_by_user_id, 

245 "invite_type": invite_type, 

246 "team_id": team_id, 

247 "age_group_id": age_group_id, 

248 "club_id": club_id, 

249 "email": email, 

250 "player_id": player_id, 

251 "jersey_number": jersey_number, 

252 "season_id": season_id, 

253 "status": "pending", 

254 "expires_at": expires_at.isoformat(), 

255 "note": note, 

256 } 

257 # Only written when requested, so a plain invite never depends on 

258 # the SB-1314 columns. 

259 if ios_beta: 

260 invitation_data["testflight_email"] = testflight_email 

261 invitation_data["testflight_status"] = "pending" 

262 

263 response = self.supabase.table("invitations").insert(invitation_data).execute() 

264 

265 if not response.data: 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true

266 raise Exception("Failed to create invitation") 

267 

268 invitation = response.data[0] 

269 

270 log_msg = f"Created {invite_type} invitation: {invite_code_ref(invite_code)}" 

271 if player_id: 271 ↛ 272line 271 didn't jump to line 272 because the condition on line 271 was never true

272 log_msg += f" linked to player {player_id}" 

273 elif jersey_number: 273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true

274 log_msg += f" with jersey #{jersey_number}" 

275 logger.info(log_msg) 

276 

277 # iPhone beta (SB-1314): add to the TestFlight group. Records its 

278 # own outcome on the row and never fails the invite. 

279 if ios_beta: 

280 self._add_to_testflight(invitation, testflight_email, *tester_name) 

281 

282 # Fire the invitation email if an address was provided. Email 

283 # failures are logged but never fail the invitation create — 

284 # admin can always copy the code manually as a fallback. 

285 if email: 

286 try: 

287 from services.email_service import EmailService 

288 

289 # send_invitation returns False rather than raising when 

290 # the provider refuses, so the result has to be checked: 

291 # ignoring it meant a refused invitation was recorded 

292 # nowhere at all (SB-1126). 

293 email_service = EmailService() 

294 sent = email_service.send_invitation( 

295 to_email=email, 

296 invite_code=invite_code, 

297 invite_type=invite_type, 

298 expires_at=expires_at.isoformat(), 

299 ios_beta=ios_beta, 

300 testflight_email=testflight_email, 

301 ) 

302 if sent: 302 ↛ 305line 302 didn't jump to line 305 because the condition on line 302 was always true

303 self._record_email_sent(invitation, email_service.last_email_id) 

304 else: 

305 logger.warning( 

306 "invitation_email_not_sent", 

307 extra={"invite_type": invite_type, "reason": "provider_rejected"}, 

308 ) 

309 except Exception as e: 

310 logger.warning( 

311 "invitation_email_not_sent", 

312 extra={"invite_type": invite_type, "reason": str(e)}, 

313 ) 

314 

315 return invitation 

316 

317 except Exception as e: 

318 logger.error(f"Error creating invitation: {e}") 

319 raise 

320 

321 def _add_to_testflight( 

322 self, 

323 invitation: dict, 

324 testflight_email: str | None, 

325 first_name: str | None = None, 

326 last_name: str | None = None, 

327 ) -> dict: 

328 """Add the invite's TestFlight email to the external beta group and 

329 record the outcome on the row (SB-1314). 

330 

331 Never raises: a TestFlight failure must not fail the invite. The 

332 outcome is merged into ``invitation`` (and returned) so the caller's 

333 response shows it. 

334 """ 

335 from services import testflight_client 

336 

337 try: 

338 result = testflight_client.add_tester(testflight_email, first_name, last_name) 

339 except Exception as e: # add_tester never raises; belt and braces 

340 result = testflight_client.TesterResult(status=testflight_client.STATUS_FAILED, error=str(e)) 

341 

342 update = {"testflight_status": result.status, "testflight_error": result.error} 

343 if result.tester_id: 

344 update["testflight_tester_id"] = result.tester_id 

345 if result.status == testflight_client.STATUS_ADDED: 

346 logger.info(f"Invitation {invitation.get('id')}: added to TestFlight") 

347 else: 

348 logger.warning(f"Invitation {invitation.get('id')}: TestFlight add failed: {result.error}") 

349 

350 try: 

351 self.supabase.table("invitations").update(update).eq("id", invitation["id"]).execute() 

352 except Exception as e: 

353 logger.error(f"Invitation {invitation.get('id')}: could not record TestFlight result: {e}") 

354 

355 invitation.update(update) 

356 return invitation 

357 

358 def retry_testflight(self, invite_id: str) -> dict: 

359 """Re-run the TestFlight add for an iPhone beta invite (admin retry). 

360 

361 Raises: 

362 LookupError: invitation missing. 

363 ValueError: TestFlight was never requested, or the tester was removed. 

364 """ 

365 response = self.supabase.table("invitations").select("*").eq("id", invite_id).execute() 

366 if not response.data: 

367 raise LookupError("Invitation not found") 

368 invitation = response.data[0] 

369 if not invitation.get("testflight_status"): 

370 raise ValueError("TestFlight was not requested for this invitation") 

371 if invitation.get("testflight_status") == "removed": 371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true

372 raise ValueError("This tester was removed when their account was deleted") 

373 return self._add_to_testflight(invitation, invitation.get("testflight_email")) 

374 

375 def resend_email(self, invite_id: str) -> bool: 

376 """Send a pending invitation's email again (admin resend, SB-1392). 

377 

378 Returns whether the provider accepted it. 

379 

380 Raises: 

381 LookupError: invitation missing. 

382 ValueError: no email on the invitation, or it is no longer pending. 

383 """ 

384 response = self.supabase.table("invitations").select("*").eq("id", invite_id).execute() 

385 if not response.data: 

386 raise LookupError("Invitation not found") 

387 invitation = response.data[0] 

388 if not invitation.get("email"): 

389 raise ValueError("This invitation has no email address") 

390 if invitation.get("status") != "pending": 

391 raise ValueError(f"This invitation is already {invitation.get('status')}") 

392 

393 from services.email_service import EmailService 

394 

395 email_service = EmailService() 

396 sent = email_service.send_invitation( 

397 to_email=invitation["email"], 

398 invite_code=invitation["invite_code"], 

399 invite_type=invitation.get("invite_type"), 

400 expires_at=invitation.get("expires_at"), 

401 ios_beta=bool(invitation.get("testflight_status")), 

402 testflight_email=invitation.get("testflight_email"), 

403 ) 

404 if sent: 

405 # A resend is a new email: its id replaces the old one, so events 

406 # for the earlier email no longer match this invite (SB-1814). 

407 self._record_email_sent(invitation, email_service.last_email_id) 

408 return sent 

409 

410 def _record_email_sent(self, invitation: dict, email_id: str | None) -> None: 

411 """Store the Resend email id and mark delivery 'sent' (SB-1814). 

412 

413 Delivery webhooks find the invite by this id. Best effort and never 

414 raises: an invite whose id could not be recorded still works, it just 

415 shows no delivery status. Nothing is recorded without an id, since no 

416 later event could ever move it past 'sent'. 

417 """ 

418 if not isinstance(email_id, str) or not email_id: 

419 return 

420 update = { 

421 "resend_email_id": email_id, 

422 "email_status": "sent", 

423 "email_status_at": datetime.now(UTC).isoformat(), 

424 "email_status_detail": None, 

425 } 

426 try: 

427 self.supabase.table("invitations").update(update).eq("id", invitation["id"]).execute() 

428 except Exception as e: 

429 logger.error(f"Invitation {invitation.get('id')}: could not record email id: {e}") 

430 return 

431 invitation.update(update) 

432 

433 def remove_testflight_for_user(self, user_id: str) -> int: 

434 """Remove a deleted user's TestFlight tester(s) from the beta group. 

435 

436 Best effort and never raises: called after the user is already gone. 

437 Returns how many were removed. 

438 """ 

439 from services import testflight_client 

440 

441 try: 

442 response = ( 

443 self.supabase.table("invitations") 

444 .select("id, testflight_tester_id") 

445 .eq("used_by_user_id", user_id) 

446 .eq("testflight_status", "added") 

447 .execute() 

448 ) 

449 except Exception as e: 

450 logger.error(f"Could not look up TestFlight testers for user {user_id}: {e}") 

451 return 0 

452 

453 removed = 0 

454 for inv in response.data or []: 

455 tester_id = inv.get("testflight_tester_id") 

456 if not tester_id: 456 ↛ 457line 456 didn't jump to line 457 because the condition on line 456 was never true

457 continue 

458 result = testflight_client.remove_tester(tester_id) 

459 if result.status == testflight_client.STATUS_REMOVED: 

460 update = {"testflight_status": "removed", "testflight_error": None} 

461 removed += 1 

462 logger.info(f"Invitation {inv['id']}: TestFlight tester removed") 

463 else: 

464 # Left as 'added' so the row still says Apple has them. 

465 update = {"testflight_error": f"remove failed: {result.error}"} 

466 logger.warning(f"Invitation {inv['id']}: TestFlight remove failed: {result.error}") 

467 try: 

468 self.supabase.table("invitations").update(update).eq("id", inv["id"]).execute() 

469 except Exception as e: 

470 logger.error(f"Invitation {inv['id']}: could not record TestFlight removal: {e}") 

471 return removed 

472 

473 def validate_invite_code(self, code: str, *, raise_errors: bool = False) -> dict | None: 

474 """ 

475 Validate an invite code 

476 

477 Args: 

478 code: The invite code to validate 

479 raise_errors: Re-raise a database error instead of returning None, 

480 so the caller can tell "not valid" from "could not check" 

481 

482 Returns: 

483 Invitation details if valid, None otherwise 

484 """ 

485 try: 

486 logger.info(f"Validating invite code: {invite_code_ref(code)}") 

487 

488 # Get invitation by code with related data including player roster entry 

489 response = ( 

490 self.supabase.table("invitations") 

491 .select( 

492 "*, teams(name), age_groups(name), clubs(name), players(id, jersey_number, first_name, last_name)" 

493 ) 

494 .eq("invite_code", code) 

495 .execute() 

496 ) 

497 

498 if not response.data or len(response.data) == 0: 

499 logger.warning(f"Invite code {invite_code_ref(code)} not found in database") 

500 return None 

501 

502 invitation = response.data[0] 

503 logger.info(f"Found invitation: status={invitation['status']}, expires_at={invitation['expires_at']}") 

504 

505 # Check if already used 

506 if invitation["status"] != "pending": 

507 logger.warning(f"Invite code {invite_code_ref(code)} has status '{invitation['status']}' (not pending)") 

508 return None 

509 

510 # Check if expired 

511 expires_at_str = invitation["expires_at"] 

512 if expires_at_str.endswith("Z"): 

513 expires_at_str = expires_at_str.replace("Z", "+00:00") 

514 expires_at = datetime.fromisoformat(expires_at_str) 

515 

516 # Make current time timezone-aware for comparison 

517 current_time = datetime.now(UTC) 

518 

519 is_expired = expires_at < current_time 

520 logger.info( 

521 f"Invite code {invite_code_ref(code)}: expires_at={expires_at}, " 

522 f"current={current_time}, is_expired={is_expired}" 

523 ) 

524 

525 if expires_at < current_time: 

526 # Update status to expired 

527 self.supabase.table("invitations").update({"status": "expired"}).eq("id", invitation["id"]).execute() 

528 logger.warning(f"Invite code {invite_code_ref(code)} expired at {expires_at}") 

529 return None 

530 

531 # Build player info if linked to roster 

532 player_info = None 

533 if invitation.get("players"): 533 ↛ 534line 533 didn't jump to line 534 because the condition on line 533 was never true

534 player = invitation["players"] 

535 player_info = { 

536 "id": player["id"], 

537 "jersey_number": player["jersey_number"], 

538 "first_name": player.get("first_name"), 

539 "last_name": player.get("last_name"), 

540 } 

541 

542 logger.info(f"Invite code {invite_code_ref(code)} is valid!") 

543 result = { 

544 "valid": True, 

545 "id": invitation["id"], 

546 "invite_type": invitation["invite_type"], 

547 "team_id": invitation["team_id"], 

548 "team_name": invitation["teams"]["name"] if invitation.get("teams") else None, 

549 "age_group_id": invitation["age_group_id"], 

550 "age_group_name": invitation["age_groups"]["name"] if invitation.get("age_groups") else None, 

551 "club_id": invitation.get("club_id"), 

552 "club_name": invitation["clubs"]["name"] if invitation.get("clubs") else None, 

553 "email": invitation["email"], 

554 "invited_by_user_id": invitation.get("invited_by_user_id"), 

555 "player_id": invitation.get("player_id"), 

556 "jersey_number": invitation.get("jersey_number"), 

557 "season_id": invitation.get("season_id"), 

558 "player": player_info, 

559 } 

560 

561 # Roster-claim preflight for team_player invites (SB-287): the 

562 # signup flow blocks registration when the spot can't be claimed. 

563 if invitation["invite_type"] == "team_player": 

564 claimable, reason = self.check_claimable(result) 

565 result["claimable"] = claimable 

566 result["claim_reason"] = reason 

567 

568 return result 

569 

570 except Exception as e: 

571 logger.error(f"Error validating invite code {invite_code_ref(code)}: {e}", exc_info=True) 

572 if raise_errors: 572 ↛ 574line 572 didn't jump to line 574 because the condition on line 572 was always true

573 raise 

574 return None 

575 

576 def check_claimable(self, invitation: dict) -> tuple[bool, str | None]: 

577 """Can this team_player invite's roster spot still be claimed? 

578 

579 Called BEFORE the auth user is created at signup, so a dead invite 

580 never produces an orphan account. Returns (claimable, reason). 

581 Invites with no roster hook (no player_id, no jersey_number) are 

582 trivially claimable. 

583 """ 

584 if invitation.get("invite_type") != "team_player": 584 ↛ 585line 584 didn't jump to line 585 because the condition on line 584 was never true

585 return True, None 

586 

587 player_id = invitation.get("player_id") 

588 jersey_number = invitation.get("jersey_number") 

589 

590 if player_id: 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true

591 try: 

592 response = ( 

593 self.supabase.table("players").select("id, user_profile_id").eq("id", player_id).limit(1).execute() 

594 ) 

595 except Exception as e: 

596 logger.error(f"Error checking roster spot {player_id}: {e}") 

597 return False, "Could not verify the roster spot. Please try again." 

598 if not response.data: 

599 return False, ( 

600 "The roster spot for this invite no longer exists. Ask your team manager for a new invite." 

601 ) 

602 if response.data[0].get("user_profile_id"): 

603 return False, ( 

604 "This roster spot has already been claimed by another account. " 

605 "Ask your team manager for a new invite." 

606 ) 

607 return True, None 

608 

609 if jersey_number: 609 ↛ 611line 609 didn't jump to line 611 because the condition on line 609 was never true

610 # Legacy invite (pre-SB-287) carrying only a jersey number. 

611 season_id = invitation.get("season_id") or self._get_current_season_id() 

612 if season_id is None: 

613 return False, "No current season found. Contact your team manager." 

614 spot = self._find_roster_spot( 

615 invitation["team_id"], season_id, jersey_number, invitation.get("age_group_id") 

616 ) 

617 if spot is None: 

618 return False, ( 

619 f"No roster spot with jersey #{jersey_number} exists for this team. " 

620 "Ask your team manager to add you to the roster first." 

621 ) 

622 if spot.get("user_profile_id"): 

623 return False, ( 

624 f"Jersey #{jersey_number} has already been claimed by another account. " 

625 "Ask your team manager for a new invite." 

626 ) 

627 return True, None 

628 

629 return True, None 

630 

631 def redeem_invitation(self, code: str, user_id: str) -> RedeemResult: 

632 """ 

633 Redeem an invitation code 

634 

635 Args: 

636 code: The invite code to redeem 

637 user_id: ID of the user redeeming the code 

638 

639 Returns: 

640 RedeemResult.REDEEMED when this call claimed the invite, 

641 UNAVAILABLE when it is not (or no longer) pending, ERROR when the 

642 database failed before the claim was known 

643 """ 

644 try: 

645 # First validate the code 

646 invitation = self.validate_invite_code(code, raise_errors=True) 

647 if not invitation: 

648 return RedeemResult.UNAVAILABLE 

649 

650 # Update invitation status. Only a still-pending row flips, so two 

651 # redemptions racing past validate_invite_code cannot both win 

652 # (SB-1864): the loser updates nothing and gets UNAVAILABLE. 

653 response = ( 

654 self.supabase.table("invitations") 

655 .update( 

656 { 

657 "status": "used", 

658 "used_at": datetime.now(UTC).isoformat(), 

659 "used_by_user_id": user_id, 

660 } 

661 ) 

662 .eq("invite_code", code) 

663 .eq("status", "pending") 

664 .execute() 

665 ) 

666 except Exception as e: 

667 logger.error(f"Error redeeming invitation {invite_code_ref(code)}: {e}") 

668 return RedeemResult.ERROR 

669 

670 if not response.data: 

671 # No row updated: another redemption got there first. 

672 logger.warning(f"Invitation {invite_code_ref(code)} was already used; not redeemed by user {user_id}") 

673 return RedeemResult.UNAVAILABLE 

674 

675 logger.info(f"Invitation {invite_code_ref(code)} redeemed by user {user_id}") 

676 

677 # The invite is this user's now; a failed side effect does not undo 

678 # that, so it is logged for an admin to reconcile. 

679 try: 

680 # Create team_manager_assignments entry for team_manager invites 

681 # This enables the team manager to create player/fan invites for their team 

682 if invitation.get("invite_type") == "team_manager": 

683 self._create_team_manager_assignment( 

684 user_id=user_id, 

685 team_id=invitation.get("team_id"), 

686 age_group_id=invitation.get("age_group_id"), 

687 assigned_by_user_id=invitation.get("invited_by_user_id"), 

688 ) 

689 

690 # Handle player roster linking for team_player invites 

691 if invitation.get("invite_type") == "team_player": 691 ↛ 738line 691 didn't jump to line 738 because the condition on line 691 was always true

692 logger.info( 

693 f"Processing team_player invite: " 

694 f"player_id={invitation.get('player_id')}, " 

695 f"jersey={invitation.get('jersey_number')}, " 

696 f"team={invitation.get('team_id')}, " 

697 f"age_group={invitation.get('age_group_id')}" 

698 ) 

699 if invitation.get("player_id"): 699 ↛ 701line 699 didn't jump to line 701 because the condition on line 699 was never true

700 # Link user to existing roster entry (also creates player_team_history) 

701 self._link_user_to_roster_entry( 

702 user_id=user_id, 

703 player_id=invitation.get("player_id"), 

704 team_id=invitation.get("team_id"), 

705 age_group_id=invitation.get("age_group_id"), 

706 ) 

707 elif invitation.get("jersey_number"): 707 ↛ 711line 707 didn't jump to line 711 because the condition on line 707 was never true

708 # Claim the existing roster entry for this jersey 

709 # number (SB-287: no auto-create - the spot must exist, 

710 # which check_claimable verified before signup). 

711 jersey = invitation.get("jersey_number") 

712 logger.info(f"Claiming roster spot for jersey #{jersey}") 

713 claimed = self._claim_roster_entry( 

714 user_id=user_id, 

715 team_id=invitation.get("team_id"), 

716 jersey_number=jersey, 

717 age_group_id=invitation.get("age_group_id"), 

718 season_id=invitation.get("season_id"), 

719 ) 

720 if not claimed: 

721 # Race: spot vanished/claimed between the signup 

722 # pre-check and redemption. The auth user exists 

723 # with its role but no roster link - loud log so 

724 # an admin can reconcile. 

725 logger.error( 

726 f"ROSTER CLAIM FAILED after signup: user {user_id}, " 

727 f"invite {invite_code_ref(code)}, jersey #{jersey}, " 

728 f"team {invitation.get('team_id')} - manual link needed" 

729 ) 

730 else: 

731 logger.info("No player_id or jersey_number on invite - skipping roster") 

732 except Exception as e: 

733 logger.error( 

734 f"Invitation {invite_code_ref(code)} redeemed by user {user_id}, but its follow-up failed: {e}", 

735 exc_info=True, 

736 ) 

737 

738 return RedeemResult.REDEEMED 

739 

740 def _get_team_club_id(self, team_id: int) -> int | None: 

741 """Look up a team's parent club_id.""" 

742 try: 

743 response = self.supabase.table("teams").select("club_id").eq("id", team_id).execute() 

744 if response.data: 744 ↛ 745line 744 didn't jump to line 745 because the condition on line 744 was never true

745 return response.data[0].get("club_id") 

746 except Exception as e: 

747 logger.warning(f"Could not look up club_id for team {team_id}: {e}") 

748 return None 

749 

750 def _link_user_to_roster_entry( 

751 self, 

752 user_id: str, 

753 player_id: int, 

754 team_id: int | None = None, 

755 season_id: int | None = None, 

756 age_group_id: int | None = None, 

757 league_id: int | None = None, 

758 division_id: int | None = None, 

759 jersey_number: int | None = None, 

760 ) -> bool: 

761 """ 

762 Link a user account to a roster entry in the players table. 

763 Also creates a player_team_history entry for the UI roster view. 

764 

765 Called when a player accepts an invitation that was tied to a roster entry. 

766 

767 Args: 

768 user_id: The user ID to link 

769 player_id: The roster entry ID to link to 

770 team_id: Team ID (optional, fetched from roster if not provided) 

771 season_id: Season ID (optional, fetched from roster if not provided) 

772 age_group_id: Age group ID from the invite 

773 league_id: League ID (optional, fetched from team if not provided) 

774 division_id: Division ID (optional, fetched from team if not provided) 

775 jersey_number: Jersey number (optional, fetched from roster if not provided) 

776 

777 Returns: 

778 True if successful, False otherwise 

779 """ 

780 try: 

781 # If we don't have the roster details, fetch them 

782 if team_id is None or season_id is None or jersey_number is None: 

783 roster_response = ( 

784 self.supabase.table("players") 

785 .select("team_id, season_id, jersey_number") 

786 .eq("id", player_id) 

787 .limit(1) 

788 .execute() 

789 ) 

790 

791 if roster_response.data: 

792 roster = roster_response.data[0] 

793 team_id = team_id or roster.get("team_id") 

794 season_id = season_id or roster.get("season_id") 

795 jersey_number = jersey_number or roster.get("jersey_number") 

796 

797 # If we don't have league/division, fetch from team 

798 if team_id and (league_id is None or division_id is None): 

799 team_response = ( 

800 self.supabase.table("teams").select("league_id, division_id").eq("id", team_id).limit(1).execute() 

801 ) 

802 

803 if team_response.data: 

804 team = team_response.data[0] 

805 league_id = league_id or team.get("league_id") 

806 division_id = division_id or team.get("division_id") 

807 

808 # Get age_group_id from team_mappings if not provided by the invite 

809 if team_id and age_group_id is None: 

810 mapping_response = ( 

811 self.supabase.table("team_mappings") 

812 .select("age_group_id") 

813 .eq("team_id", team_id) 

814 .limit(1) 

815 .execute() 

816 ) 

817 if mapping_response.data: 

818 age_group_id = mapping_response.data[0]["age_group_id"] 

819 

820 # Update the players table to link user_profile_id. The 

821 # user_profile_id IS NULL guard makes the claim atomic: if another 

822 # account claimed the spot since the signup pre-check, zero rows 

823 # update and we fail instead of stealing the link. 

824 response = ( 

825 self.supabase.table("players") 

826 .update({"user_profile_id": user_id}) 

827 .eq("id", player_id) 

828 .is_("user_profile_id", "null") 

829 .execute() 

830 ) 

831 

832 if response.data: 

833 logger.info(f"Linked user {user_id} to roster entry {player_id}") 

834 

835 # Also create player_team_history entry for UI roster view 

836 if team_id and season_id: 

837 self._create_player_team_history( 

838 user_id=user_id, 

839 team_id=team_id, 

840 season_id=season_id, 

841 age_group_id=age_group_id, 

842 league_id=league_id, 

843 division_id=division_id, 

844 jersey_number=jersey_number, 

845 ) 

846 

847 # Invalidate caches 

848 clear_cache("mt:dao:roster:*") 

849 clear_cache("mt:dao:players:*") 

850 return True 

851 

852 logger.warning(f"Failed to link user {user_id} to roster entry {player_id}") 

853 return False 

854 

855 except Exception as e: 

856 logger.error(f"Error linking user to roster entry: {e}") 

857 return False 

858 

859 def _claim_roster_entry( 

860 self, 

861 user_id: str, 

862 team_id: int, 

863 jersey_number: int, 

864 age_group_id: int | None = None, 

865 season_id: int | None = None, 

866 ) -> bool: 

867 """ 

868 Claim the existing unclaimed roster entry matching the invite's 

869 (team, season, age group, jersey). NO auto-create (SB-287): if the 

870 spot doesn't exist the claim fails - creation-time validation and the 

871 signup pre-check should have prevented reaching here. 

872 

873 Args: 

874 user_id: The user ID to link 

875 team_id: The team ID for the roster entry 

876 jersey_number: The jersey number for the roster entry 

877 age_group_id: The age group ID from the invite 

878 season_id: Season from the invitation; falls back to 

879 current-by-date only for legacy invites without one 

880 

881 Returns: 

882 True if successful, False otherwise 

883 """ 

884 try: 

885 if season_id is None: 

886 season_id = self._get_current_season_id() 

887 if season_id is None: 

888 logger.error("No current season found - cannot claim roster entry") 

889 return False 

890 

891 spot = self._find_roster_spot(team_id, season_id, jersey_number, age_group_id) 

892 if spot is None: 

893 logger.error( 

894 f"No roster spot for jersey #{jersey_number} " 

895 f"(team {team_id}, season {season_id}, age group {age_group_id})" 

896 ) 

897 return False 

898 if spot.get("user_profile_id"): 

899 logger.warning( 

900 f"Roster entry {spot['id']} (jersey #{jersey_number}) " 

901 f"already linked to user {spot['user_profile_id']}" 

902 ) 

903 return False 

904 

905 # Get team details for league_id and division_id 

906 team_response = ( 

907 self.supabase.table("teams").select("league_id, division_id").eq("id", team_id).limit(1).execute() 

908 ) 

909 league_id = None 

910 division_id = None 

911 if team_response.data: 

912 league_id = team_response.data[0].get("league_id") 

913 division_id = team_response.data[0].get("division_id") 

914 

915 # Link (atomic: guarded on user_profile_id IS NULL inside) 

916 return self._link_user_to_roster_entry( 

917 user_id=user_id, 

918 player_id=spot["id"], 

919 team_id=team_id, 

920 season_id=season_id, 

921 age_group_id=age_group_id, 

922 league_id=league_id, 

923 division_id=division_id, 

924 jersey_number=jersey_number, 

925 ) 

926 

927 except Exception as e: 

928 logger.error(f"Error claiming roster entry: {e}") 

929 return False 

930 

931 def _create_player_team_history( 

932 self, 

933 user_id: str, 

934 team_id: int, 

935 season_id: int, 

936 age_group_id: int | None = None, 

937 league_id: int | None = None, 

938 division_id: int | None = None, 

939 jersey_number: int | None = None, 

940 positions: list[str] | None = None, 

941 ) -> bool: 

942 """ 

943 Create a player_team_history entry for the UI roster view. 

944 

945 This is the primary table used by the UI to display team rosters. 

946 Called when a player accepts an invitation. 

947 

948 Args: 

949 user_id: The user ID (player_id in the table) 

950 team_id: Team ID 

951 season_id: Season ID 

952 age_group_id: Age group ID 

953 league_id: League ID 

954 division_id: Division ID 

955 jersey_number: Jersey number 

956 positions: List of position codes (e.g., ['CM', 'ST'] - validated 

957 against constants.positions.VALID_POSITIONS) 

958 

959 Returns: 

960 True if successful, False otherwise 

961 """ 

962 try: 

963 # Direct DB write bypasses the Pydantic models - validate here 

964 # so invalid/legacy codes can't re-enter the DB (SB-293). 

965 if positions: 

966 from constants.positions import normalize_positions 

967 

968 try: 

969 positions = normalize_positions(positions) 

970 except ValueError as e: 

971 logger.warning(f"Dropping invalid positions on history insert: {e}") 

972 positions = None 

973 # Check if entry already exists for this player/team/season 

974 existing = ( 

975 self.supabase.table("player_team_history") 

976 .select("id") 

977 .eq("player_id", user_id) 

978 .eq("team_id", team_id) 

979 .eq("season_id", season_id) 

980 .limit(1) 

981 .execute() 

982 ) 

983 

984 if existing.data: 

985 logger.info( 

986 f"player_team_history entry already exists for user {user_id}, team {team_id}, season {season_id}" 

987 ) 

988 return True 

989 

990 # Create new entry 

991 history_data = { 

992 "player_id": user_id, 

993 "team_id": team_id, 

994 "season_id": season_id, 

995 "is_current": True, 

996 } 

997 

998 if age_group_id is not None: 

999 history_data["age_group_id"] = age_group_id 

1000 if league_id is not None: 

1001 history_data["league_id"] = league_id 

1002 if division_id is not None: 

1003 history_data["division_id"] = division_id 

1004 if jersey_number is not None: 

1005 history_data["jersey_number"] = jersey_number 

1006 if positions: 

1007 history_data["positions"] = positions 

1008 

1009 response = self.supabase.table("player_team_history").insert(history_data).execute() 

1010 

1011 if response.data: 

1012 history_id = response.data[0]["id"] 

1013 logger.info( 

1014 f"Created player_team_history entry {history_id} for user {user_id} " 

1015 f"on team {team_id}, season {season_id}, jersey #{jersey_number}" 

1016 ) 

1017 return True 

1018 

1019 logger.warning(f"Failed to create player_team_history for user {user_id}") 

1020 return False 

1021 

1022 except Exception as e: 

1023 logger.error(f"Error creating player_team_history: {e}") 

1024 return False 

1025 

1026 def _create_team_manager_assignment( 

1027 self, user_id: str, team_id: int, age_group_id: int, assigned_by_user_id: str 

1028 ) -> bool: 

1029 """ 

1030 Create a team_manager_assignments entry to grant team management permissions. 

1031 

1032 Args: 

1033 user_id: The user being granted management rights 

1034 team_id: The team they can manage 

1035 age_group_id: The age group (not stored - table doesn't have this column) 

1036 assigned_by_user_id: The user who created the invite (not stored) 

1037 

1038 Returns: 

1039 True if successful, False otherwise 

1040 """ 

1041 try: 

1042 # Check if assignment already exists (table has unique constraint on user_id, team_id) 

1043 existing = ( 

1044 self.supabase.table("team_manager_assignments") 

1045 .select("id") 

1046 .eq("user_id", user_id) 

1047 .eq("team_id", team_id) 

1048 .execute() 

1049 ) 

1050 

1051 if existing.data: 

1052 logger.info(f"Team manager assignment already exists for user {user_id}, team {team_id}") 

1053 return True 

1054 

1055 # Create new assignment (table schema: id, user_id, team_id, created_at) 

1056 response = ( 

1057 self.supabase.table("team_manager_assignments") 

1058 .insert( 

1059 { 

1060 "user_id": user_id, 

1061 "team_id": team_id, 

1062 } 

1063 ) 

1064 .execute() 

1065 ) 

1066 

1067 if response.data: 

1068 logger.info(f"Created team manager assignment: user {user_id} -> team {team_id}") 

1069 return True 

1070 

1071 logger.warning(f"Failed to create team manager assignment for user {user_id}") 

1072 return False 

1073 

1074 except Exception as e: 

1075 logger.error(f"Error creating team manager assignment: {e}") 

1076 return False 

1077 

1078 def get_user_invitations(self, user_id: str) -> list[dict]: 

1079 """ 

1080 Get all invitations created by a user 

1081 

1082 Args: 

1083 user_id: ID of the user 

1084 

1085 Returns: 

1086 List of invitations, with used_by_user profile info merged in for used invites 

1087 """ 

1088 try: 

1089 response = ( 

1090 self.supabase.table("invitations") 

1091 .select("*, teams(name), age_groups(name), clubs(name)") 

1092 .eq("invited_by_user_id", user_id) 

1093 .order("created_at", desc=True) 

1094 .execute() 

1095 ) 

1096 

1097 invitations = response.data if response.data else [] 

1098 

1099 # Fetch user profiles for any "used" invites so we can show who redeemed them 

1100 used_user_ids = list({inv["used_by_user_id"] for inv in invitations if inv.get("used_by_user_id")}) 

1101 

1102 if used_user_ids: 

1103 profiles_response = ( 

1104 self.supabase.table("user_profiles") 

1105 .select("id, username, display_name") 

1106 .in_("id", used_user_ids) 

1107 .execute() 

1108 ) 

1109 profiles_by_id = {p["id"]: p for p in (profiles_response.data or [])} 

1110 

1111 for inv in invitations: 

1112 uid = inv.get("used_by_user_id") 

1113 inv["used_by_user"] = profiles_by_id.get(uid) if uid else None 

1114 

1115 return invitations 

1116 

1117 except Exception as e: 

1118 logger.error(f"Error getting user invitations: {e}") 

1119 return [] 

1120 

1121 def cancel_invitation(self, invite_id: str, user_id: str) -> bool: 

1122 """ 

1123 Cancel a pending invitation 

1124 

1125 Args: 

1126 invite_id: ID of the invitation to cancel 

1127 user_id: ID of the user cancelling (must be creator or admin) 

1128 

1129 Returns: 

1130 True if successful, False otherwise 

1131 """ 

1132 try: 

1133 # Check if user can cancel this invitation 

1134 response = ( 

1135 self.supabase.table("invitations") 

1136 .select("invited_by_user_id, status") 

1137 .eq("id", invite_id) 

1138 .single() 

1139 .execute() 

1140 ) 

1141 

1142 if not response.data: 

1143 return False 

1144 

1145 invitation = response.data 

1146 

1147 # Only pending invitations can be cancelled 

1148 if invitation["status"] != "pending": 

1149 return False 

1150 

1151 # Update status to expired 

1152 response = self.supabase.table("invitations").update({"status": "expired"}).eq("id", invite_id).execute() 

1153 

1154 if response.data: 1154 ↛ 1158line 1154 didn't jump to line 1158 because the condition on line 1154 was always true

1155 logger.info(f"Invitation {invite_id} cancelled by user {user_id}") 

1156 return True 

1157 

1158 return False 

1159 

1160 except Exception as e: 

1161 logger.error(f"Error cancelling invitation {invite_id}: {e}") 

1162 return False 

1163 

1164 def expire_old_invitations(self) -> int: 

1165 """ 

1166 Expire all old pending invitations 

1167 

1168 Returns: 

1169 Number of invitations expired 

1170 """ 

1171 try: 

1172 # Get all pending invitations that have expired 

1173 response = ( 

1174 self.supabase.table("invitations") 

1175 .select("id") 

1176 .eq("status", "pending") 

1177 .lt("expires_at", datetime.now(UTC).isoformat()) 

1178 .execute() 

1179 ) 

1180 

1181 if not response.data: 

1182 return 0 

1183 

1184 # Update all to expired 

1185 expired_ids = [inv["id"] for inv in response.data] 

1186 

1187 self.supabase.table("invitations").update({"status": "expired"}).in_("id", expired_ids).execute() 

1188 

1189 logger.info(f"Expired {len(expired_ids)} old invitations") 

1190 return len(expired_ids) 

1191 

1192 except Exception as e: 

1193 logger.error(f"Error expiring old invitations: {e}") 

1194 return 0