Coverage for dao/player_dao.py: 26.04%

292 statements  

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

1""" 

2Player Data Access Object. 

3 

4Handles all database operations related to players/user profiles including: 

5- User profile CRUD operations 

6- Team-player associations 

7- Player team history 

8- Admin player management 

9""" 

10 

11import structlog 

12 

13from dao.base_dao import BaseDAO, clear_cache, dao_cache, invalidates_cache 

14 

15logger = structlog.get_logger() 

16 

17# Cache patterns for invalidation 

18PLAYERS_CACHE_PATTERN = "mt:dao:players:*" 

19 

20 

21def _season_sort_key(row: dict) -> tuple: 

22 """Newest season first, then newest row first. Missing dates sort last.""" 

23 season = row.get("season") or {} 

24 start = season.get("start_date") or "" 

25 # Empty start_date must sort last, so flag it separately rather than relying 

26 # on "" comparing low under reverse ordering. 

27 return (bool(start), start, row.get("id") or 0) 

28 

29 

30def select_current_teams(rows: list[dict], current_season_id: int | None) -> list[dict]: 

31 """Pick the rows describing the teams a player is on *now*. 

32 

33 `is_current` alone is not enough: nothing clears the flag when a player moves 

34 to a new season, so rows accumulate across seasons and the caller (My Club) 

35 ends up showing whichever one Postgres returned first (SB-441). 

36 

37 Args: 

38 rows: player_team_history rows with `is_current=true`, each carrying an 

39 embedded `season` object. 

40 current_season_id: id of the season the app considers current, or None 

41 when that can't be resolved. 

42 

43 Returns: 

44 The current season's rows when the player has any; otherwise every row 

45 from the newest season they do have, so a player not yet rostered for 

46 the new season still sees their last team instead of nothing. Always 

47 ordered newest season first. 

48 """ 

49 if not rows: 

50 return [] 

51 

52 ordered = sorted(rows, key=_season_sort_key, reverse=True) 

53 

54 if current_season_id is not None: 

55 in_current = [r for r in ordered if r.get("season_id") == current_season_id] 

56 if in_current: 

57 return in_current 

58 

59 # No row for the current season — fall back to the newest season present, 

60 # keeping every team from that season (a player can be on two at once). 

61 newest_season_id = ordered[0].get("season_id") 

62 return [r for r in ordered if r.get("season_id") == newest_season_id] 

63 

64 

65class PlayerDAO(BaseDAO): 

66 """Data access object for player/user profile operations.""" 

67 

68 # === User Profile Query Methods === 

69 

70 @dao_cache("players:profile:{user_id}") 

71 def get_user_profile_with_relationships(self, user_id: str) -> dict | None: 

72 """ 

73 Get user profile with team relationship. 

74 

75 Args: 

76 user_id: User ID to fetch profile for 

77 

78 Returns: 

79 User profile dict with team data, or None if not found 

80 """ 

81 try: 

82 # Explicit FK names required: SB-51's user_team_follows table created 

83 # a many-to-many path between user_profiles and teams in addition to 

84 # the direct team_id FK, which makes PostgREST throw PGRST201 unless 

85 # we name the relationship we want. Same hint needed for `clubs` 

86 # because user_profiles has both a direct club_id FK and a path via 

87 # teams.club_id (also detected as ambiguous). 

88 response = ( 

89 self.client.table("user_profiles") 

90 .select(""" 

91 *, 

92 team:teams!user_profiles_team_id_fkey( 

93 id, name, city, 

94 club:clubs(id, name, primary_color, secondary_color, logo_url) 

95 ), 

96 club:clubs!user_profiles_club_id_fkey( 

97 id, name, primary_color, secondary_color, logo_url 

98 ) 

99 """) 

100 .eq("id", user_id) 

101 .execute() 

102 ) 

103 

104 if response.data and len(response.data) > 0: 

105 profile = response.data[0] 

106 if len(response.data) > 1: 

107 logger.warning(f"Multiple profiles found for user {user_id}, using first one") 

108 return profile 

109 return None 

110 except Exception as e: 

111 logger.error(f"Error fetching user profile: {e}") 

112 return None 

113 

114 def get_user_profile_by_email(self, email: str, exclude_user_id: str | None = None) -> dict | None: 

115 """ 

116 Get user profile by email, optionally excluding a specific user ID. 

117 

118 Useful for checking if an email is already in use by another user. 

119 No caching - used for auth/validation. 

120 

121 Args: 

122 email: Email address to search for 

123 exclude_user_id: Optional user ID to exclude from search 

124 

125 Returns: 

126 User profile dict if found, None otherwise 

127 """ 

128 try: 

129 query = self.client.table("user_profiles").select("id").eq("email", email) 

130 if exclude_user_id: 

131 query = query.neq("id", exclude_user_id) 

132 response = query.execute() 

133 if response.data and len(response.data) > 0: 

134 return response.data[0] 

135 return None 

136 except Exception as e: 

137 logger.error(f"Error checking user profile by email: {e}") 

138 return None 

139 

140 def get_user_profile_by_username(self, username: str, exclude_user_id: str | None = None) -> dict | None: 

141 """ 

142 Get user profile by username, optionally excluding a specific user ID. 

143 

144 Useful for checking if a username is already taken. 

145 No caching - used for auth/validation. 

146 

147 Args: 

148 username: Username to search for (will be lowercased) 

149 exclude_user_id: Optional user ID to exclude from search 

150 

151 Returns: 

152 User profile dict if found, None otherwise 

153 """ 

154 try: 

155 query = self.client.table("user_profiles").select("id").eq("username", username.lower()) 

156 if exclude_user_id: 

157 query = query.neq("id", exclude_user_id) 

158 response = query.execute() 

159 if response.data and len(response.data) > 0: 

160 return response.data[0] 

161 return None 

162 except Exception as e: 

163 logger.error(f"Error checking user profile by username: {e}") 

164 return None 

165 

166 def get_user_for_password_reset(self, identifier: str) -> dict | None: 

167 """ 

168 Look up a user by username or email for the password reset flow. 

169 

170 If ``@`` appears in the identifier it is treated as an email address; 

171 otherwise it is treated as a username (lowercased). 

172 

173 Selects only ``id``, ``username``, and ``email`` — no caching because 

174 this is used in an auth-sensitive path. 

175 

176 Args: 

177 identifier: Username or email address supplied by the user 

178 

179 Returns: 

180 Dict with ``id``, ``username``, ``email`` keys, or None if not found 

181 """ 

182 try: 

183 if "@" in identifier: 

184 # Lowercased like the username branch below. Addresses are 

185 # stored lowercase and mail providers treat them that way in 

186 # practice, so an exact match turned "Ericgsenk@gmail.com" 

187 # into "no such account" — indistinguishable, to the user and 

188 # to us, from having no account at all (SB-1130). 

189 query = ( 

190 self.client.table("user_profiles") 

191 .select("id, username, email") 

192 .eq("email", identifier.strip().lower()) 

193 ) 

194 else: 

195 query = ( 

196 self.client.table("user_profiles") 

197 .select("id, username, email") 

198 .eq("username", identifier.lower()) 

199 ) 

200 response = query.execute() 

201 if response.data and len(response.data) > 0: 

202 return response.data[0] 

203 return None 

204 except Exception as e: 

205 logger.error(f"Error looking up user for password reset: {e}") 

206 return None 

207 

208 @dao_cache("players:all") 

209 def get_all_user_profiles(self) -> list[dict]: 

210 """ 

211 Get all user profiles with team relationships. 

212 

213 Returns: 

214 List of user profile dicts 

215 """ 

216 try: 

217 # Explicit FK name: see comment in get_user_profile_with_relationships. 

218 response = ( 

219 self.client.table("user_profiles") 

220 .select(""" 

221 *, 

222 team:teams!user_profiles_team_id_fkey(id, name, city) 

223 """) 

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

225 .execute() 

226 ) 

227 return response.data or [] 

228 except Exception as e: 

229 logger.error(f"Error fetching all user profiles: {e}") 

230 return [] 

231 

232 # === User Profile CRUD Methods === 

233 

234 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

235 def create_or_update_user_profile(self, profile_data: dict) -> dict | None: 

236 """ 

237 Create or update a user profile. 

238 

239 Args: 

240 profile_data: Dictionary containing user profile data 

241 

242 Returns: 

243 Created/updated profile dict, or None on error 

244 """ 

245 try: 

246 response = self.client.table("user_profiles").upsert(profile_data).execute() 

247 if response.data and len(response.data) > 0: 

248 return response.data[0] 

249 return None 

250 except Exception as e: 

251 logger.error(f"Error creating/updating user profile: {e}") 

252 return None 

253 

254 def set_filter_memory(self, user_id: str, view: str, patch: dict) -> None: 

255 """Merge one view's remembered filters into ``user_profiles.filter_memory`` (SB-1715). 

256 

257 Atomic in the database (``set_filter_memory`` RPC), so Table and Matches 

258 saving at once cannot drop each other's entry. 

259 

260 Invalidates only this user's cached profile. ``update_user_profile`` 

261 clears ``mt:dao:players:*`` — every user's — which is fine for a Profile 

262 save and not for a write that follows filter clicks. 

263 

264 Raises on failure; the endpoint decides what the client sees. 

265 """ 

266 self.client.rpc( 

267 "set_filter_memory", 

268 {"p_user_id": user_id, "p_view": view, "p_patch": patch}, 

269 ).execute() 

270 clear_cache(f"mt:dao:players:profile:{user_id}") 

271 

272 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

273 def update_user_profile(self, user_id: str, update_data: dict) -> dict | None: 

274 """ 

275 Update user profile fields. 

276 

277 Args: 

278 user_id: User ID to update 

279 update_data: Dictionary of fields to update 

280 

281 Returns: 

282 Updated profile dict, or None on error 

283 """ 

284 try: 

285 response = self.client.table("user_profiles").update(update_data).eq("id", user_id).execute() 

286 if response.data and len(response.data) > 0: 

287 return response.data[0] 

288 return None 

289 except Exception as e: 

290 logger.error(f"Error updating user profile: {e}") 

291 return None 

292 

293 # === Team Players Methods === 

294 

295 @dao_cache("players:by_team:{team_id}:age:{age_group_id}") 

296 def get_team_players( 

297 self, 

298 team_id: int, 

299 age_group_id: int | None = None, 

300 ) -> list[dict]: 

301 """ 

302 Get all players currently on a team for the team roster page. 

303 

304 Uses player_team_history to support multi-team players, scoped to the 

305 current season: `is_current` rows can exist for the same player and team 

306 in more than one season, which listed them once per row (SB-442). 

307 

308 Returns player profiles with fields needed for player cards: 

309 - id, display_name, player_number, positions 

310 - photo_1_url, photo_2_url, photo_3_url, profile_photo_slot 

311 - overlay_style, primary_color, text_color, accent_color 

312 - instagram_handle, snapchat_handle, tiktok_handle 

313 

314 Args: 

315 team_id: The team ID to get players for 

316 age_group_id: Optional age group filter (SB-68). When set, 

317 filters `player_team_history.age_group_id` strictly. When 

318 None, returns all current roster entries regardless of age 

319 (current behavior preserved for the team roster page). 

320 

321 Returns: 

322 List of player profile dicts 

323 """ 

324 try: 

325 # Query player_team_history for current team members 

326 query = ( 

327 self.client.table("player_team_history") 

328 .select(""" 

329 id, 

330 player_id, 

331 jersey_number, 

332 positions, 

333 season_id, 

334 season:seasons(id, start_date), 

335 user_profiles!player_team_history_player_id_fkey( 

336 id, 

337 display_name, 

338 player_number, 

339 positions, 

340 photo_1_url, 

341 photo_2_url, 

342 photo_3_url, 

343 profile_photo_slot, 

344 overlay_style, 

345 primary_color, 

346 text_color, 

347 accent_color, 

348 instagram_handle, 

349 snapchat_handle, 

350 tiktok_handle 

351 ) 

352 """) 

353 .eq("team_id", team_id) 

354 .eq("is_current", True) 

355 ) 

356 if age_group_id is not None: 

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

358 response = query.execute() 

359 

360 # Same rule as get_all_current_player_teams: this season's rows, or 

361 # the newest season present if the roster hasn't been rebuilt yet — 

362 # better than showing an empty squad in the pre-season gap. 

363 entries = select_current_teams(response.data or [], self._current_season_id()) 

364 

365 # Flatten the results - extract user_profiles and merge with history data 

366 players = [] 

367 for entry in entries: 

368 profile = entry.get("user_profiles") 

369 if profile: 

370 # Use jersey_number from history if available, fallback to profile 

371 player = {**profile} 

372 if entry.get("jersey_number") is not None: 

373 player["player_number"] = entry["jersey_number"] 

374 # Use positions from history if available, fallback to profile 

375 if entry.get("positions"): 

376 player["positions"] = entry["positions"] 

377 players.append(player) 

378 

379 # Sort by player_number 

380 players.sort(key=lambda p: p.get("player_number") or 999) 

381 return players 

382 except Exception as e: 

383 logger.error(f"Error fetching team players for team {team_id}: {e}") 

384 return [] 

385 

386 # === Player Team History Methods === 

387 

388 @dao_cache("players:history:{player_id}") 

389 def get_player_team_history(self, player_id: str) -> list[dict]: 

390 """ 

391 Get complete team history for a player across all seasons. 

392 

393 Returns history entries ordered by season (most recent first), 

394 with full team, season, age_group, league, and division details. 

395 

396 Args: 

397 player_id: User ID of the player 

398 

399 Returns: 

400 List of history entry dicts with related data 

401 """ 

402 try: 

403 response = ( 

404 self.client.table("player_team_history") 

405 .select(""" 

406 *, 

407 team:teams(id, name, city, 

408 club:clubs(id, name, primary_color, secondary_color) 

409 ), 

410 season:seasons(id, name, start_date, end_date), 

411 age_group:age_groups(id, name), 

412 league:leagues(id, name), 

413 division:divisions(id, name) 

414 """) 

415 .eq("player_id", player_id) 

416 .order("season_id", desc=True) 

417 .execute() 

418 ) 

419 return response.data or [] 

420 except Exception as e: 

421 logger.error(f"Error fetching player team history: {e}") 

422 return [] 

423 

424 def get_current_player_team_assignment(self, player_id: str) -> dict | None: 

425 """ 

426 Get the current team assignment for a player (is_current=true). 

427 

428 No caching - this is used for real-time checks. 

429 

430 Args: 

431 player_id: User ID of the player 

432 

433 Returns: 

434 Current history entry dict with related data, or None if not found 

435 """ 

436 try: 

437 response = ( 

438 self.client.table("player_team_history") 

439 .select(""" 

440 *, 

441 team:teams(id, name, city, 

442 club:clubs(id, name, primary_color, secondary_color) 

443 ), 

444 season:seasons(id, name, start_date, end_date), 

445 age_group:age_groups(id, name), 

446 league:leagues(id, name), 

447 division:divisions(id, name) 

448 """) 

449 .eq("player_id", player_id) 

450 .eq("is_current", True) 

451 .limit(1) 

452 .execute() 

453 ) 

454 

455 if response.data and len(response.data) > 0: 

456 return response.data[0] 

457 return None 

458 except Exception as e: 

459 logger.error(f"Error fetching current player team assignment: {e}") 

460 return None 

461 

462 def get_all_current_player_teams(self, player_id: str) -> list[dict]: 

463 """ 

464 Get the player's team assignments for the current season. 

465 

466 Still supports players being on multiple teams simultaneously 

467 (e.g. futsal + outdoor) — but only within one season. `is_current` rows 

468 left behind by earlier seasons are filtered out here, and the result is 

469 ordered newest season first so callers that take the first entry get a 

470 stable answer (SB-441). 

471 No caching - this is used for real-time checks. 

472 

473 Args: 

474 player_id: User ID of the player 

475 

476 Returns: 

477 List of current history entries with related team and club data 

478 """ 

479 try: 

480 response = ( 

481 self.client.table("player_team_history") 

482 .select(""" 

483 *, 

484 team:teams(id, name, city, 

485 club:clubs(id, name, logo_url, primary_color, secondary_color), 

486 league:leagues(id, name), 

487 division:divisions(id, name) 

488 ), 

489 season:seasons(id, name, start_date, end_date), 

490 age_group:age_groups(id, name), 

491 league:leagues(id, name), 

492 division:divisions(id, name) 

493 """) 

494 .eq("player_id", player_id) 

495 .eq("is_current", True) 

496 .execute() 

497 ) 

498 return select_current_teams(response.data or [], self._current_season_id()) 

499 except Exception as e: 

500 logger.error(f"Error fetching all current player teams: {e}") 

501 return [] 

502 

503 def _current_season_id(self) -> int | None: 

504 """Id of the season the app treats as current, or None if unresolvable. 

505 

506 Delegates to SeasonDAO so this follows the same rule as everywhere else: 

507 the admin-set `seasons.is_current` flag, falling back to whichever season 

508 spans today. 

509 """ 

510 try: 

511 from dao.season_dao import SeasonDAO 

512 

513 season = SeasonDAO(self.connection_holder).get_current_season() 

514 return season.get("id") if season else None 

515 except Exception as e: 

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

517 return None 

518 

519 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

520 def create_player_history_entry( 

521 self, 

522 player_id: str, 

523 team_id: int, 

524 season_id: int, 

525 jersey_number: int | None = None, 

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

527 notes: str | None = None, 

528 is_current: bool = False, 

529 age_group_id: int | None = None, 

530 ) -> dict | None: 

531 """ 

532 Create or update a player team history entry. 

533 

534 Uses UPSERT to handle the unique constraint on (player_id, team_id, season_id). 

535 If an entry already exists for the same player/team/season, it updates that 

536 entry instead of failing. This supports: 

537 - Re-adding a player to a team they were previously on 

538 - Updating is_current flag on existing entries 

539 - Players on multiple teams simultaneously (futsal use case) 

540 

541 Args: 

542 player_id: User ID of the player 

543 team_id: Team ID 

544 season_id: Season ID 

545 jersey_number: Optional jersey number for that season 

546 positions: Optional list of positions played 

547 notes: Optional notes about the assignment 

548 is_current: Whether this is the current assignment 

549 age_group_id: Explicit age group override. Required for clubs with multiple 

550 age groups (e.g. IFA runs U13/U14/U15/U16). When omitted, falls back 

551 to the first team_mapping row — unreliable for multi-age-group clubs. 

552 

553 Returns: 

554 Created/updated history entry dict, or None on error 

555 """ 

556 try: 

557 # Get team details for league_id, division_id 

558 team_response = ( 

559 self.client.table("teams").select("league_id, division_id").eq("id", team_id).execute() 

560 ) 

561 

562 team_data = team_response.data[0] if team_response.data else {} 

563 

564 # Resolve age_group_id: use caller-supplied value when available. 

565 # Falling back to team_mappings is only reliable for teams with a single 

566 # age-group mapping; clubs like IFA have multiple rows and limit(1) is 

567 # non-deterministic without an explicit age_group_id. 

568 if age_group_id is None: 

569 mapping_response = ( 

570 self.client.table("team_mappings") 

571 .select("age_group_id") 

572 .eq("team_id", team_id) 

573 .order("age_group_id") 

574 .limit(1) 

575 .execute() 

576 ) 

577 age_group_id = mapping_response.data[0]["age_group_id"] if mapping_response.data else None 

578 

579 upsert_data = { 

580 "player_id": player_id, 

581 "team_id": team_id, 

582 "season_id": season_id, 

583 "age_group_id": age_group_id, 

584 "league_id": team_data.get("league_id"), 

585 "division_id": team_data.get("division_id"), 

586 "jersey_number": jersey_number, 

587 "positions": positions, 

588 "is_current": is_current, 

589 "notes": notes, 

590 } 

591 

592 # Use upsert to handle existing entries - if (player_id, team_id, season_id) 

593 # already exists, update it instead of failing 

594 response = ( 

595 self.client.table("player_team_history") 

596 .upsert(upsert_data, on_conflict="player_id,team_id,season_id") 

597 .execute() 

598 ) 

599 if response.data and len(response.data) > 0: 

600 if is_current: 

601 self._clear_current_in_other_seasons(player_id, season_id) 

602 return self.get_player_history_entry_by_id(response.data[0]["id"]) 

603 return None 

604 except Exception as e: 

605 logger.error(f"Error creating/updating player history entry: {e}") 

606 return None 

607 

608 def _clear_current_in_other_seasons(self, player_id: str, season_id: int) -> None: 

609 """Drop `is_current` from this player's rows in every other season. 

610 

611 A player can hold several current teams at once (futsal + outdoor), but 

612 only inside one season. Without this, last season's rows keep the flag 

613 forever and My Club can land on a team the player has moved on from 

614 (SB-441). Best-effort: a failure here must not fail the write that 

615 triggered it. 

616 """ 

617 try: 

618 ( 

619 self.client.table("player_team_history") 

620 .update({"is_current": False, "updated_at": "now()"}) 

621 .eq("player_id", player_id) 

622 .eq("is_current", True) 

623 .neq("season_id", season_id) 

624 .execute() 

625 ) 

626 except Exception as e: 

627 logger.error(f"Error clearing is_current on other seasons: {e}") 

628 

629 def get_player_history_entry_by_id(self, history_id: int) -> dict | None: 

630 """ 

631 Get a single player history entry by ID with related data. 

632 

633 Args: 

634 history_id: History entry ID 

635 

636 Returns: 

637 History entry dict with related data, or None if not found 

638 """ 

639 try: 

640 response = ( 

641 self.client.table("player_team_history") 

642 .select(""" 

643 *, 

644 team:teams(id, name, city, 

645 club:clubs(id, name, primary_color, secondary_color) 

646 ), 

647 season:seasons(id, name, start_date, end_date), 

648 age_group:age_groups(id, name), 

649 league:leagues(id, name), 

650 division:divisions(id, name) 

651 """) 

652 .eq("id", history_id) 

653 .execute() 

654 ) 

655 

656 if response.data and len(response.data) > 0: 

657 return response.data[0] 

658 return None 

659 except Exception as e: 

660 logger.error(f"Error fetching player history entry: {e}") 

661 return None 

662 

663 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

664 def update_player_history_entry( 

665 self, 

666 history_id: int, 

667 jersey_number: int | None = None, 

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

669 notes: str | None = None, 

670 is_current: bool | None = None, 

671 ) -> dict | None: 

672 """ 

673 Update a player team history entry. 

674 

675 Args: 

676 history_id: History entry ID to update 

677 jersey_number: Optional new jersey number 

678 positions: Optional new positions list 

679 notes: Optional new notes 

680 is_current: Optional new is_current flag 

681 

682 Returns: 

683 Updated history entry dict, or None on error 

684 """ 

685 try: 

686 update_data = {"updated_at": "now()"} 

687 

688 if jersey_number is not None: 

689 update_data["jersey_number"] = jersey_number 

690 if positions is not None: 

691 update_data["positions"] = positions 

692 if notes is not None: 

693 update_data["notes"] = notes 

694 if is_current is not None: 

695 update_data["is_current"] = is_current 

696 

697 response = self.client.table("player_team_history").update(update_data).eq("id", history_id).execute() 

698 

699 if response.data and len(response.data) > 0: 

700 if is_current: 

701 row = response.data[0] 

702 # Multiple current teams within one season stay allowed 

703 # (futsal + outdoor); other seasons' rows get cleared. 

704 self._clear_current_in_other_seasons(row["player_id"], row["season_id"]) 

705 return self.get_player_history_entry_by_id(history_id) 

706 return None 

707 except Exception as e: 

708 logger.error(f"Error updating player history entry: {e}") 

709 return None 

710 

711 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

712 def delete_player_history_entry(self, history_id: int) -> bool: 

713 """ 

714 Delete a player team history entry. 

715 

716 Args: 

717 history_id: History entry ID to delete 

718 

719 Returns: 

720 True if deleted successfully, False otherwise 

721 """ 

722 try: 

723 self.client.table("player_team_history").delete().eq("id", history_id).execute() 

724 return True 

725 except Exception as e: 

726 logger.error(f"Error deleting player history entry: {e}") 

727 return False 

728 

729 # === Admin Player Management Methods === 

730 

731 def get_all_players_admin( 

732 self, 

733 search: str | None = None, 

734 club_id: int | None = None, 

735 team_id: int | None = None, 

736 limit: int = 50, 

737 offset: int = 0, 

738 include_roster_only: bool = False, 

739 season_id: int | None = None, 

740 ) -> dict: 

741 """ 

742 Get all players with their current team assignments for admin management. 

743 No caching - admin queries should always be fresh. 

744 

745 Two populations are merged (SB-286): 

746 - "account" players: user_profiles with role team-player 

747 - "roster" players: players-table rows with no linked account 

748 (user_profile_id IS NULL) - kids added by jersey number. 

749 Linked roster rows are excluded automatically, so a player never 

750 appears twice. 

751 Each item carries source: 'account' | 'roster'; ids come from 

752 different tables, so consumers must key on (source, id). 

753 

754 Args: 

755 search: Optional text search on display_name or email 

756 club_id: Optional filter by club ID 

757 team_id: Optional filter by team ID 

758 limit: Max number of results (default 50) 

759 offset: Offset for pagination (default 0) 

760 include_roster_only: Also include roster-only players 

761 season_id: Season scope for the roster-only population (defaults 

762 to the current season by date; account players are not 

763 season-scoped) 

764 

765 Returns: 

766 Dict with 'players' list and 'total' count 

767 """ 

768 try: 

769 # Build the base query for players (team-player role) 

770 query = ( 

771 self.client.table("user_profiles") 

772 .select( 

773 """ 

774 id, 

775 email, 

776 display_name, 

777 player_number, 

778 positions, 

779 photo_1_url, 

780 profile_photo_slot, 

781 team_id, 

782 created_at, 

783 team:teams!user_profiles_team_id_fkey(id, name, club_id) 

784 """, 

785 count="exact", 

786 ) 

787 .eq("role", "team-player") 

788 ) 

789 

790 # Apply text search filter 

791 if search: 

792 query = query.or_(f"display_name.ilike.%{search}%,email.ilike.%{search}%") 

793 

794 # Apply team filter 

795 if team_id: 

796 query = query.eq("team_id", team_id) 

797 # Apply club filter (via team) 

798 elif club_id: 

799 # Need to get team IDs for this club first 

800 teams_response = self.client.table("teams").select("id").eq("club_id", club_id).execute() 

801 if teams_response.data: 

802 team_ids = [t["id"] for t in teams_response.data] 

803 query = query.in_("team_id", team_ids) 

804 

805 # Apply pagination and ordering 

806 query = query.order("display_name").range(offset, offset + limit - 1) 

807 

808 response = query.execute() 

809 

810 players = response.data or [] 

811 total = response.count or 0 

812 

813 # Enrich with current team assignments from player_team_history 

814 for player in players: 

815 history_response = ( 

816 self.client.table("player_team_history") 

817 .select( 

818 """ 

819 id, 

820 team_id, 

821 season_id, 

822 jersey_number, 

823 is_current, 

824 created_at, 

825 team:teams(id, name, club:clubs(id, name)), 

826 season:seasons(id, name) 

827 """ 

828 ) 

829 .eq("player_id", player["id"]) 

830 .eq("is_current", True) 

831 .execute() 

832 ) 

833 player["current_teams"] = history_response.data or [] 

834 player["source"] = "account" 

835 

836 # Merge in roster-only players (players table, no linked account). 

837 # Linked rows have user_profile_id set and are excluded, so an 

838 # account holder never appears twice. Appended after the account 

839 # page rather than interleaved - roster-only counts are small at 

840 # MT scale, so cross-source pagination isn't worth the complexity. 

841 if include_roster_only: 

842 roster_players = self._get_roster_only_players( 

843 search=search, club_id=club_id, team_id=team_id, season_id=season_id 

844 ) 

845 players.extend(roster_players) 

846 total += len(roster_players) 

847 

848 return {"players": players, "total": total} 

849 

850 except Exception as e: 

851 logger.error(f"Error fetching players for admin: {e}") 

852 return {"players": [], "total": 0} 

853 

854 def _get_roster_only_players( 

855 self, 

856 search: str | None = None, 

857 club_id: int | None = None, 

858 team_id: int | None = None, 

859 season_id: int | None = None, 

860 ) -> list[dict]: 

861 """Roster entries (players table) with no linked account, shaped like 

862 admin player items: source='roster', synthetic current_teams entry so 

863 the admin UI renders them without branching.""" 

864 try: 

865 if season_id is None: 

866 # Prefer the admin-set current season (is_current flag), else 

867 # the date-spanning season. 

868 flagged = ( 

869 self.client.table("seasons").select("id").eq("is_current", True).limit(1).execute() 

870 ) 

871 if flagged.data: 

872 season_id = flagged.data[0]["id"] 

873 else: 

874 from datetime import date 

875 

876 today = date.today().isoformat() 

877 season_response = ( 

878 self.client.table("seasons") 

879 .select("id") 

880 .lte("start_date", today) 

881 .gte("end_date", today) 

882 .limit(1) 

883 .execute() 

884 ) 

885 if not season_response.data: 

886 return [] 

887 season_id = season_response.data[0]["id"] 

888 

889 query = ( 

890 self.client.table("players") 

891 .select( 

892 """ 

893 id, 

894 team_id, 

895 season_id, 

896 jersey_number, 

897 first_name, 

898 last_name, 

899 positions, 

900 age_group_id, 

901 is_active, 

902 team:teams(id, name, club_id, club:clubs(id, name)), 

903 season:seasons(id, name), 

904 age_group:age_groups(id, name) 

905 """ 

906 ) 

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

908 .eq("season_id", season_id) 

909 .eq("is_active", True) 

910 ) 

911 if search: 

912 query = query.or_(f"first_name.ilike.%{search}%,last_name.ilike.%{search}%") 

913 if team_id: 

914 query = query.eq("team_id", team_id) 

915 elif club_id: 

916 teams_response = self.client.table("teams").select("id").eq("club_id", club_id).execute() 

917 team_ids = [t["id"] for t in (teams_response.data or [])] 

918 if not team_ids: 

919 return [] 

920 query = query.in_("team_id", team_ids) 

921 

922 response = query.order("jersey_number").limit(500).execute() 

923 

924 items = [] 

925 for row in response.data or []: 

926 name = " ".join(filter(None, [row.get("first_name"), row.get("last_name")])) 

927 items.append( 

928 { 

929 "id": row["id"], 

930 "source": "roster", 

931 "display_name": name or f"#{row['jersey_number']}", 

932 "email": None, 

933 "player_number": row["jersey_number"], 

934 "positions": row.get("positions"), 

935 "photo_1_url": None, 

936 "profile_photo_slot": None, 

937 "team_id": row["team_id"], 

938 "age_group": row.get("age_group"), 

939 "current_teams": [ 

940 { 

941 "id": f"roster-{row['id']}", 

942 "team_id": row["team_id"], 

943 "season_id": row["season_id"], 

944 "jersey_number": row["jersey_number"], 

945 "is_current": True, 

946 "team": row.get("team"), 

947 "season": row.get("season"), 

948 } 

949 ], 

950 } 

951 ) 

952 return items 

953 

954 except Exception as e: 

955 logger.error(f"Error fetching roster-only players: {e}") 

956 return [] 

957 

958 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

959 def update_player_admin( 

960 self, 

961 player_id: str, 

962 display_name: str | None = None, 

963 player_number: int | None = None, 

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

965 ) -> dict | None: 

966 """ 

967 Update player profile info (admin/manager operation). 

968 

969 Args: 

970 player_id: User ID of the player 

971 display_name: Optional new display name 

972 player_number: Optional new jersey number 

973 positions: Optional new positions list 

974 

975 Returns: 

976 Updated player profile dict, or None on error 

977 """ 

978 try: 

979 update_data = {"updated_at": "now()"} 

980 

981 if display_name is not None: 

982 update_data["display_name"] = display_name 

983 if player_number is not None: 

984 update_data["player_number"] = player_number 

985 if positions is not None: 

986 update_data["positions"] = positions 

987 

988 response = self.client.table("user_profiles").update(update_data).eq("id", player_id).execute() 

989 

990 if response.data and len(response.data) > 0: 

991 return response.data[0] 

992 return None 

993 

994 except Exception as e: 

995 logger.error(f"Error updating player admin: {e}") 

996 return None 

997 

998 @invalidates_cache(PLAYERS_CACHE_PATTERN) 

999 def end_player_team_assignment(self, history_id: int) -> dict | None: 

1000 """ 

1001 End a player's team assignment by setting is_current=false. 

1002 

1003 Args: 

1004 history_id: Player team history ID 

1005 

1006 Returns: 

1007 Updated history entry dict, or None on error 

1008 """ 

1009 try: 

1010 update_data = {"is_current": False, "updated_at": "now()"} 

1011 

1012 response = self.client.table("player_team_history").update(update_data).eq("id", history_id).execute() 

1013 

1014 if response.data and len(response.data) > 0: 

1015 return self.get_player_history_entry_by_id(history_id) 

1016 return None 

1017 

1018 except Exception as e: 

1019 logger.error(f"Error ending player team assignment: {e}") 

1020 return None