Coverage for dao/tournament_dao.py: 49.80%

521 statements  

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

1""" 

2Tournament Data Access Object. 

3 

4Handles all database operations for tournaments, including: 

5- Tournament CRUD 

6- Tournament match creation (with auto-create of lightweight opponent teams) 

7- Public read: tournament list and detail with match results 

8""" 

9 

10import structlog 

11from postgrest.exceptions import APIError 

12 

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

14from dao.tournament_filters import ( 

15 DEFAULT_LIMIT, 

16 TEAM_SEARCH_DEFAULT_LIMIT, 

17 build_filters_payload, 

18 build_schedule_facets, 

19 build_team_index, 

20 conference_divisions, 

21 conference_match_filter, 

22 empty_page, 

23 league_conference_ids, 

24 league_match_ids, 

25 league_team_ages, 

26 match_sides, 

27 match_stage, 

28 normalize_team_query, 

29 search_team_index, 

30 stage_needs_groups, 

31 stage_query_filter, 

32 team_league, 

33 unavailable_filters_payload, 

34) 

35 

36logger = structlog.get_logger() 

37 

38TOURNAMENTS_CACHE_PATTERN = "mt:dao:tournaments:*" 

39# Tournament matches ARE matches — writing one must also bust the matches 

40# cache (get_match_by_id is @dao_cache under mt:dao:matches:by_id:*). Without 

41# this, a re-read after a tournament-score write returns the stale pre-write 

42# row: the SB-77 follower-notify detector sees no change and never fires, and 

43# even when it does the dispatcher formats the push with the stale score. 

44MATCHES_CACHE_PATTERN = "mt:dao:matches:*" 

45# Creating a lightweight opponent adds a row the cached team lists must show — 

46# otherwise the next Add Match still can't pick it and creates it again (SB-817). 

47TEAMS_CACHE_PATTERN = "mt:dao:teams:*" 

48 

49# match_type_id=2 is "Tournament" (seed data) 

50TOURNAMENT_MATCH_TYPE_ID = 2 

51 

52VALID_ROUNDS = { 

53 "group_stage", 

54 "crossover", 

55 "round_of_32", 

56 "round_of_16", 

57 "quarterfinal", 

58 "semifinal", 

59 "final", 

60 "third_place", 

61 "wildcard", 

62 "silver_semifinal", 

63 "bronze_semifinal", 

64 "silver_final", 

65 "bronze_final", 

66 "showcase", 

67 "consolation", 

68 "placement_final", 

69} 

70 

71# The columns of one tournament, shared by every tournament read so a new 

72# column (announcement, SB-1797) reaches the index, the admin list and the 

73# detail endpoint alike. 

74TOURNAMENT_SELECT = ( 

75 "id, name, season_id, start_date, end_date, location, description, is_active, logo_url, announcement" 

76) 

77 

78# The columns of one match in a tournament's match list. Shared by the detail 

79# endpoint and the paged one so a row is the same shape from either (SB-1749). 

80TOURNAMENT_MATCH_SELECT = """ 

81 id, 

82 match_date, 

83 scheduled_kickoff, 

84 match_status, 

85 home_score, 

86 away_score, 

87 home_penalty_score, 

88 away_penalty_score, 

89 tournament_group, 

90 tournament_round, 

91 tournament_round_order, 

92 location, 

93 age_group:age_groups!matches_age_group_id_fkey(id, name), 

94 home_team:teams!matches_home_team_id_fkey(id, name, club:clubs(id, name, logo_url)), 

95 away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, name, logo_url)) 

96 """ 

97 

98# The same columns without matches.location, for a database the SB-1874 

99# migration has not reached: the match list loses its pitch, not its page. 

100TOURNAMENT_MATCH_SELECT_WITHOUT_LOCATION = TOURNAMENT_MATCH_SELECT.replace("\n location,", "", 1) 

101 

102# Postgres's "column does not exist", passed through by PostgREST. 

103_UNDEFINED_COLUMN = "42703" 

104 

105 

106def _location_not_migrated(error: APIError) -> bool: 

107 """Whether a match read failed only because matches.location does not exist yet (SB-1874).""" 

108 return error.code == _UNDEFINED_COLUMN and "location" in str(error.message or "") 

109 

110 

111# PostgREST's "requested range not satisfiable": an offset past the last row 

112# of a counted query. For a pager that is an empty page, not a failure. 

113_RANGE_NOT_SATISFIABLE = "PGRST103" 

114 

115# PostgREST's "could not find the function in the schema cache": the facets 

116# migration has not reached this database yet. The one facet failure that 

117# degrades to "unavailable"; anything else is a real error. 

118_FUNCTION_NOT_FOUND = "PGRST202" 

119 

120# How long a tournament read that carries scores or match counts stays cached. 

121# The ingest worker cannot clear this cache: it runs without CACHE_ENABLED or 

122# REDIS_URL, in a different cluster from the API's Redis, so @invalidates_cache 

123# is a no-op there. These reads are bounded by this TTL instead, and a scraped 

124# score or a newly created match shows within about a minute (SB-1756). 

125TOURNAMENT_SCORE_CACHE_TTL = 60 

126 

127# The match pages and their facets are score-bearing too. Short also keeps the 

128# keys of a big event expiring on their own instead of piling up for a day. 

129TOURNAMENT_PAGE_CACHE_TTL = TOURNAMENT_SCORE_CACHE_TTL 

130 

131# PostgREST's row cap per response; lookups that can exceed it are read in 

132# pages of this size. 

133_READ_PAGE = 1000 

134 

135# The match columns the day, conference, league and stage facets are computed from. 

136_SIDE_SELECT = ( 

137 "id, match_date, age_group_id, home_team_id, away_team_id, home_age_group_id, away_age_group_id," 

138 " tournament_round, tournament_group" 

139) 

140 

141# The match columns a league page is cut from: the page order and both sides. 

142_PAGE_ORDER_SELECT = ( 

143 "id, match_date, scheduled_kickoff, age_group_id, home_team_id, away_team_id, home_age_group_id, away_age_group_id" 

144) 

145 

146# The match columns the team search is built from: both sides' teams, with clubs. 

147_TEAM_SIDE_SELECT = ( 

148 "id, age_group_id, home_age_group_id, away_age_group_id," 

149 " home_team:teams!matches_home_team_id_fkey(id, name, club:clubs(id, name, logo_url))," 

150 " away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, name, logo_url))" 

151) 

152 

153 

154def tournament_visible(tournament: dict | None, include_test: bool, is_admin: bool = False) -> bool: 

155 """Whether a viewer may open one tournament (SB-1768). 

156 

157 Mirrors the index (get_active_tournaments): an inactive or is_test 

158 tournament is not listed for a real user, so it must not be reachable by 

159 id either. include_test (admins and test users) waives only the is_test 

160 check; only an admin may open an inactive tournament, as the admin panel 

161 edits drafts by id. 

162 """ 

163 if not tournament: 

164 return False 

165 if is_admin: 

166 return True 

167 if not tournament.get("is_active"): 

168 return False 

169 return include_test or not tournament.get("is_test") 

170 

171 

172class TournamentDAO(BaseDAO): 

173 """Data access object for tournament operations.""" 

174 

175 # ========================================================================= 

176 # Public read 

177 # ========================================================================= 

178 

179 def _attach_age_groups(self, tournaments: list[dict]) -> list[dict]: 

180 """Fetch age groups from the junction table and attach to each tournament.""" 

181 if not tournaments: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true

182 return tournaments 

183 ids = [t["id"] for t in tournaments] 

184 try: 

185 rows = ( 

186 self.client.table("tournament_age_groups") 

187 .select("tournament_id, age_group:age_groups(id, name)") 

188 .in_("tournament_id", ids) 

189 .execute() 

190 ).data or [] 

191 except Exception: 

192 logger.exception("Error fetching tournament age groups") 

193 rows = [] 

194 

195 by_tid: dict[int, list] = {t["id"]: [] for t in tournaments} 

196 for row in rows: 

197 tid = row["tournament_id"] 

198 if tid in by_tid: 198 ↛ 196line 198 didn't jump to line 196 because the condition on line 198 was always true

199 by_tid[tid].append(row["age_group"]) 

200 

201 for t in tournaments: 

202 t["age_groups"] = by_tid[t["id"]] 

203 return tournaments 

204 

205 def _attach_match_counts(self, tournaments: list[dict], include_test: bool = False) -> list[dict]: 

206 """Fetch match counts from the matches table and attach to each tournament. 

207 

208 include_test gates the SB-591 test partition, so a test fixture entered 

209 into a real tournament does not inflate its published match count. 

210 """ 

211 if not tournaments: 

212 return tournaments 

213 for t in tournaments: 

214 # An exact count per tournament, asked of the database. Counting the 

215 # rows of one .in_() select is capped at PostgREST's 1,000-row 

216 # response limit, so a big tournament under-reported (SB-1752). 

217 try: 

218 count_query = ( 

219 self.client.table(MATCHES_READ_RELATION) 

220 .select("id", count="exact", head=True) 

221 .eq("tournament_id", t["id"]) 

222 ) 

223 if not include_test: 

224 count_query = count_query.eq("is_test", False) 

225 # No count in the response is unknown, not zero: None, so a 

226 # client renders no number (SB-1767). A real 0 stays 0. 

227 t["match_count"] = count_query.execute().count 

228 except Exception: 

229 logger.exception("Error fetching tournament match count", tournament_id=t["id"]) 

230 t["match_count"] = None 

231 return tournaments 

232 

233 def _sync_age_groups(self, tournament_id: int, age_group_ids: list[int]) -> None: 

234 """Replace all age group links for a tournament.""" 

235 self.client.table("tournament_age_groups").delete().eq("tournament_id", tournament_id).execute() 

236 if age_group_ids: 

237 rows = [{"tournament_id": tournament_id, "age_group_id": ag_id} for ag_id in age_group_ids] 

238 self.client.table("tournament_age_groups").insert(rows).execute() 

239 

240 @dao_cache("tournaments:active:{include_test}:{season_id}", ttl=TOURNAMENT_SCORE_CACHE_TTL) 

241 def get_active_tournaments(self, include_test: bool = False, season_id: int | None = None) -> list[dict]: 

242 """Return all active tournaments ordered by start date descending. 

243 

244 include_test gates the SB-85 test partition: real/anonymous viewers pass 

245 False (test tournaments hidden); admins + test users pass True. 

246 season_id, when provided, restricts results to that season. 

247 """ 

248 try: 

249 query = self.client.table("tournaments").select(TOURNAMENT_SELECT).eq("is_active", True) 

250 if not include_test: 250 ↛ 252line 250 didn't jump to line 252 because the condition on line 250 was always true

251 query = query.eq("is_test", False) 

252 if season_id is not None: 252 ↛ 254line 252 didn't jump to line 254 because the condition on line 252 was always true

253 query = query.eq("season_id", season_id) 

254 response = query.order("start_date", desc=True).execute() 

255 data = self._attach_age_groups(response.data or []) 

256 return self._attach_match_counts(data, include_test=include_test) 

257 except Exception: 

258 logger.exception("Error fetching active tournaments") 

259 return [] 

260 

261 @dao_cache("tournaments:all", ttl=TOURNAMENT_SCORE_CACHE_TTL) 

262 def get_all_tournaments(self) -> list[dict]: 

263 """Return all tournaments (admin use). 

264 

265 Admin-only, so match counts deliberately include test fixtures — this is 

266 the view an admin uses to confirm the TSC test world exists (SB-591). 

267 """ 

268 try: 

269 response = ( 

270 self.client.table("tournaments").select(TOURNAMENT_SELECT).order("start_date", desc=True).execute() 

271 ) 

272 data = self._attach_age_groups(response.data or []) 

273 return self._attach_match_counts(data, include_test=True) 

274 except Exception: 

275 logger.exception("Error fetching all tournaments") 

276 return [] 

277 

278 @dao_cache("tournaments:by_id:{tournament_id}:test{include_test}", ttl=TOURNAMENT_SCORE_CACHE_TTL) 

279 def get_tournament_by_id(self, tournament_id: int, include_test: bool = False) -> dict | None: 

280 """Return tournament with all matches for tracked teams. 

281 

282 Matches are enriched with home/away team names so the frontend 

283 can display them without additional lookups. 

284 

285 include_test gates the SB-591 test partition on the match list; it is 

286 part of the cache key so the two audiences never share a response. 

287 

288 None means no such tournament. A database error is raised, not turned 

289 into None: "the lookup failed" must not read as "not found". 

290 """ 

291 rows = ( 

292 self.client.table("tournaments").select(TOURNAMENT_SELECT).eq("id", tournament_id).limit(1).execute().data 

293 or [] 

294 ) 

295 if not rows: 295 ↛ 296line 295 didn't jump to line 296 because the condition on line 295 was never true

296 return None 

297 

298 tournament = self._attach_age_groups([rows[0]])[0] 

299 

300 # Fetch matches linked to this tournament 

301 def m_query(select: str): 

302 query = self.client.table(MATCHES_READ_RELATION).select(select).eq("tournament_id", tournament_id) 

303 if not include_test: 303 ↛ 305line 303 didn't jump to line 305 because the condition on line 303 was always true

304 query = query.eq("is_test", False) 

305 return query.order("match_date", desc=False) 

306 

307 m_response = self._execute_match_select(m_query) 

308 

309 tournament["matches"] = self._flatten_clubs(m_response.data or []) 

310 return tournament 

311 

312 @staticmethod 

313 def _execute_match_select(build): 

314 """Run a tournament match query, once more without `location` if the column is missing. 

315 

316 ``build(select)`` returns the query for a select string. The match 

317 list selects matches.location (SB-1874); on a database the migration 

318 has not reached, the page still loads and every row's location is None. 

319 """ 

320 try: 

321 return build(TOURNAMENT_MATCH_SELECT).execute() 

322 except APIError as exc: 

323 if not _location_not_migrated(exc): 

324 raise 

325 logger.warning("matches.location is not migrated here; reading tournament matches without it") 

326 response = build(TOURNAMENT_MATCH_SELECT_WITHOUT_LOCATION).execute() 

327 for row in response.data or []: 

328 row.setdefault("location", None) 

329 return response 

330 

331 @staticmethod 

332 def _flatten_clubs(matches: list[dict]) -> list[dict]: 

333 """Lift each team's nested club to `home_team_club` / `away_team_club`, 

334 and add `stage_key` / `stage_label` (``match_stage``). 

335 

336 Matches the shape used by `/api/matches` and consumed by 

337 MatchDetailView / MatchesView, so the frontend club-logo code paths 

338 stay consistent across endpoints. 

339 """ 

340 for m in matches: 

341 home = m.get("home_team") or {} 

342 away = m.get("away_team") or {} 

343 m["home_team_club"] = home.pop("club", None) 

344 m["away_team_club"] = away.pop("club", None) 

345 # The stage the Stage chips call this match (SB-1873), so the page 

346 # heads its sections by the same key. 

347 m.update(match_stage(m)) 

348 return matches 

349 

350 # ------------------------------------------------------------------------- 

351 # Paged matches and filter facets (SB-1749) 

352 # ------------------------------------------------------------------------- 

353 

354 # The index this mirrors (get_active_tournaments) is cached for the same 

355 # TTL, so a tournament is openable by id exactly when it is listed. is_test 

356 # is only ever set by SQL (scripts/mark_tsc_test_data.sql), which never 

357 # clears Redis, so the default day-long TTL would let the two disagree. 

358 @dao_cache("tournaments:visibility:{tournament_id}", ttl=TOURNAMENT_SCORE_CACHE_TTL) 

359 def get_tournament_visibility(self, tournament_id: int) -> dict | None: 

360 """`{id, is_active, is_test}` of one tournament, or None when there is no such tournament. 

361 

362 A database error is raised, not turned into None: "the lookup failed" 

363 must not read as "not found". 

364 """ 

365 rows = ( 

366 self.client.table("tournaments") 

367 .select("id, is_active, is_test") 

368 .eq("id", tournament_id) 

369 .limit(1) 

370 .execute() 

371 .data 

372 or [] 

373 ) 

374 return rows[0] if rows else None 

375 

376 # Default TTL: a tournament's age groups do not depend on its matches. 

377 @dao_cache("tournaments:age_groups:{tournament_id}") 

378 def get_tournament_age_groups(self, tournament_id: int) -> list[dict] | None: 

379 """The tournament's own age groups, or None when there is no such tournament. 

380 

381 A database error is raised, not turned into None: "the lookup failed" 

382 must not read as "not found". 

383 """ 

384 rows = self.client.table("tournaments").select("id").eq("id", tournament_id).limit(1).execute().data or [] 

385 if not rows: 385 ↛ 386line 385 didn't jump to line 386 because the condition on line 385 was never true

386 return None 

387 return self._attach_age_groups(rows)[0]["age_groups"] 

388 

389 def get_tournament_matches( 

390 self, 

391 tournament_id: int, 

392 *, 

393 age_group_id: int | None = None, 

394 group: str | None = None, 

395 round: str | None = None, 

396 limit: int = DEFAULT_LIMIT, 

397 offset: int = 0, 

398 include_test: bool = False, 

399 on_date: str | None = None, 

400 conference_id: int | None = None, 

401 league: str | None = None, 

402 team_id: int | None = None, 

403 stage: str | None = None, 

404 ) -> dict: 

405 """One page of a tournament's matches: ``{matches, total, limit, offset}``. 

406 

407 Rows have the same shape as ``get_tournament_by_id``'s ``matches``. 

408 ``total`` is the exact number of matches the filters select, however 

409 many that is — it comes from the database's count, not from the page. 

410 Ordered by day, then kickoff, then id, so pages neither overlap nor 

411 skip. ``on_date`` keeps one ``match_date``; ``conference_id`` keeps 

412 the matches where either team is placed in that conference at its age 

413 group (SB-1753) — a division that is not a conference, or one with no 

414 teams, is an empty page. 

415 

416 SB-1870: ``league`` keeps the matches where either team is placed in 

417 any of that league's conferences; with a ``conference_id`` of the other 

418 league it is an empty page. ``team_id`` keeps that team's matches, home 

419 or away. ``stage`` keeps one stage (``match_stage_of``: the competition 

420 a match's group names — on the group stage a namespace, on any other 

421 round the stored competition — else its round, SB-1873, SB-1875), 

422 ``STAGE_NONE`` the matches with no round. Raises on a database error. 

423 """ 

424 if conference_id is not None: 424 ↛ 425line 424 didn't jump to line 425 because the condition on line 424 was never true

425 if not self._conference_team_ages_or_none(conference_id): 

426 return empty_page(limit, offset) 

427 if league is not None: 

428 if conference_id not in league_conference_ids(self._conferences(), league): 

429 return empty_page(limit, offset) 

430 # The conference is one of the league's: its filter is the narrower. 

431 league = None 

432 # Worked out once per request, and cached per scope so a cached page 

433 # does not cost a read of the scope's groups (SB-1873, SB-1875). 

434 stage_filter = None 

435 if stage is not None: 435 ↛ 436line 435 didn't jump to line 436 because the condition on line 435 was never true

436 stage_filter = self._stage_filter(tournament_id, age_group_id, include_test, stage) 

437 filters = { 

438 "tournament_id": tournament_id, 

439 "age_group_id": age_group_id, 

440 "group": group, 

441 "round": round, 

442 "include_test": include_test, 

443 "on_date": on_date, 

444 "conference_id": conference_id, 

445 "team_id": team_id, 

446 "stage_filter": stage_filter, 

447 } 

448 if league is not None: 448 ↛ 449line 448 didn't jump to line 449 because the condition on line 448 was never true

449 ids = self._league_match_ids(league=league, stage=stage, **filters) 

450 return self._league_page(ids, limit, offset, tournament_id) 

451 # Only the pages the site itself asks for are cached: the default page 

452 # size at a multiple of it. Any other limit or offset is served 

453 # uncached, so sweeping them cannot fill the cache with keys. 

454 if limit == DEFAULT_LIMIT and offset % DEFAULT_LIMIT == 0: 454 ↛ 457line 454 didn't jump to line 457 because the condition on line 454 was always true

455 page = self._tournament_matches_page(limit=limit, offset=offset, stage=stage, **filters) 

456 else: 

457 page = self._fetch_tournament_matches_page(limit=limit, offset=offset, **filters) 

458 if page is not None: 458 ↛ 460line 458 didn't jump to line 460 because the condition on line 458 was always true

459 return page 

460 if offset == 0: 

461 return empty_page(limit, offset) 

462 # Past the last row: nothing to show, but the total is still true. 

463 head = self._filter_tournament_matches( 

464 self.client.table(MATCHES_READ_RELATION).select("id", count="exact", head=True), **filters 

465 ) 

466 return {**empty_page(limit, offset), "total": head.execute().count or 0} 

467 

468 # The filter's or= string per scope and stage, so every page of it, cached 

469 # or not, reuses it. Short like the pages it filters. 

470 @dao_cache( 

471 "tournaments:stage_filter:{tournament_id}:age{age_group_id}:test{include_test}:stage{stage}", 

472 ttl=TOURNAMENT_PAGE_CACHE_TTL, 

473 ) 

474 def _stage_filter(self, tournament_id: int, age_group_id: int | None, include_test: bool, stage: str) -> str: 

475 """The ``stage=`` filter (``stage_query_filter``) over the scope's stored groups.""" 

476 rows = ( 

477 self._tournament_side_rows(tournament_id, age_group_id, include_test) if stage_needs_groups(stage) else [] 

478 ) 

479 return stage_query_filter(stage, rows).either 

480 

481 def _filter_tournament_matches( 

482 self, 

483 query, 

484 *, 

485 tournament_id: int, 

486 age_group_id: int | None, 

487 group: str | None, 

488 round: str | None, 

489 include_test: bool, 

490 on_date: str | None = None, 

491 conference_id: int | None = None, 

492 team_id: int | None = None, 

493 stage_filter: str | None = None, 

494 ): 

495 """Apply the paged endpoint's filters, all but ``league``, to a matches query. 

496 

497 ``league`` is applied by ``_league_match_ids``: as an ``or`` filter it 

498 would name every team of the league that plays, which for a whole 

499 event is past the URL length PostgREST accepts. 

500 """ 

501 query = query.eq("tournament_id", tournament_id) 

502 if not include_test: 502 ↛ 504line 502 didn't jump to line 504 because the condition on line 502 was always true

503 query = query.eq("is_test", False) 

504 if age_group_id is not None: 504 ↛ 505line 504 didn't jump to line 505 because the condition on line 504 was never true

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

506 if group is not None: 506 ↛ 507line 506 didn't jump to line 507 because the condition on line 506 was never true

507 query = query.eq("tournament_group", group) 

508 if round is not None: 508 ↛ 509line 508 didn't jump to line 509 because the condition on line 508 was never true

509 query = query.eq("tournament_round", round) 

510 if on_date is not None: 510 ↛ 511line 510 didn't jump to line 511 because the condition on line 510 was never true

511 query = query.eq("match_date", on_date) 

512 if conference_id is not None: 512 ↛ 515line 512 didn't jump to line 515 because the condition on line 512 was never true

513 # get_tournament_matches has already answered an empty conference 

514 # with an empty page; an empty filter here would select everything. 

515 either_team = conference_match_filter(self._conference_team_ages_or_none(conference_id) or []) 

516 if either_team is None: 

517 raise ValueError("conference filter has no teams") 

518 query = query.or_(either_team) 

519 if team_id is not None: 519 ↛ 521line 519 didn't jump to line 521 because the condition on line 519 was never true

520 # A second or= is ANDed with the first by PostgREST. 

521 query = query.or_(f"home_team_id.eq.{team_id},away_team_id.eq.{team_id}") 

522 if stage_filter is not None: 522 ↛ 526line 522 didn't jump to line 526 because the condition on line 522 was never true

523 # Built by get_tournament_matches from the same rows and rule the 

524 # Stage facet counts with (SB-1873, SB-1875); ANDed with any 

525 # conference or team or= above, as those are with each other. 

526 query = query.or_(stage_filter) 

527 return query 

528 

529 def _league_team_ages( 

530 self, 

531 tournament_id: int, 

532 age_group_id: int | None, 

533 include_test: bool, 

534 on_date: str | None, 

535 league: str, 

536 ) -> list[dict]: 

537 """The sides of this scope's matches placed in ``league``: ``[{team_id, age_group_id}]``. 

538 

539 Built from the cached side rows, conferences and placements, so it is 

540 bounded by the teams that play rather than by the whole league. 

541 """ 

542 sides = match_sides(self._tournament_side_rows(tournament_id, age_group_id, include_test), on_date=on_date) 

543 placements = [p for age in sorted({a for _, a in sides}) for p in self._conference_placements(age)] 

544 return league_team_ages(self._conferences(), sides, placements, league) 

545 

546 # One ordered id list per filter set, so "load more" slices it instead of 

547 # re-reading the event. Short like the pages it is cut into. 

548 @dao_cache( 

549 "tournaments:league_ids:{tournament_id}:{league}:age{age_group_id}:round{round}" 

550 ":test{include_test}:group{group}:on{on_date}:conf{conference_id}:team{team_id}:stage{stage}", 

551 ttl=TOURNAMENT_PAGE_CACHE_TTL, 

552 ) 

553 def _league_match_ids( 

554 self, 

555 league: str, 

556 tournament_id: int, 

557 age_group_id: int | None, 

558 group: str | None, 

559 round: str | None, 

560 include_test: bool, 

561 on_date: str | None, 

562 conference_id: int | None, 

563 team_id: int | None, 

564 stage: str | None, 

565 stage_filter: str | None = None, 

566 ) -> list[int]: 

567 """Ids of the matches the filters select with either side in ``league``, in page order. 

568 

569 ``stage`` is the cache key's; ``stage_filter`` is what the query uses. 

570 The league's placed sides are worked out once here. When none play in 

571 this scope the answer is ``[]`` without reading the matches. 

572 """ 

573 placed = { 

574 (r["team_id"], r["age_group_id"]) 

575 for r in self._league_team_ages(tournament_id, age_group_id, include_test, on_date, league) 

576 } 

577 if not placed: 

578 return [] 

579 filters = { 

580 "tournament_id": tournament_id, 

581 "age_group_id": age_group_id, 

582 "group": group, 

583 "round": round, 

584 "include_test": include_test, 

585 "on_date": on_date, 

586 "conference_id": conference_id, 

587 "team_id": team_id, 

588 "stage_filter": stage_filter, 

589 } 

590 rows = self._read_all( 

591 lambda: self._filter_tournament_matches( 

592 self.client.table(MATCHES_READ_RELATION).select(_PAGE_ORDER_SELECT), **filters 

593 ) 

594 ) 

595 return league_match_ids(rows, placed) 

596 

597 def _league_page(self, ids: list[int], limit: int, offset: int, tournament_id: int) -> dict: 

598 """One page cut from a league's ordered ids; only that page's rows are fetched. 

599 

600 ``total`` is every id, so a page past the end still reports it. 

601 """ 

602 page_ids = ids[offset : offset + limit] 

603 if not page_ids: 603 ↛ 604line 603 didn't jump to line 604 because the condition on line 603 was never true

604 return {**empty_page(limit, offset), "total": len(ids)} 

605 try: 

606 rows = ( 

607 self._execute_match_select( 

608 lambda select: ( 

609 self.client.table(MATCHES_READ_RELATION) 

610 .select(select) 

611 .in_("id", page_ids) 

612 .order("match_date", desc=False) 

613 .order("scheduled_kickoff", desc=False) 

614 .order("id", desc=False) 

615 ) 

616 ).data 

617 or [] 

618 ) 

619 except APIError: 

620 logger.exception("Error fetching tournament matches page", tournament_id=tournament_id) 

621 raise 

622 return {"matches": self._flatten_clubs(rows), "total": len(ids), "limit": limit, "offset": offset} 

623 

624 @dao_cache( 

625 "tournaments:matches:{tournament_id}:age{age_group_id}:round{round}" 

626 ":l{limit}:o{offset}:test{include_test}:group{group}:on{on_date}:conf{conference_id}" 

627 ":team{team_id}:stage{stage}", 

628 ttl=TOURNAMENT_PAGE_CACHE_TTL, 

629 ) 

630 def _tournament_matches_page( 

631 self, 

632 tournament_id: int, 

633 age_group_id: int | None, 

634 group: str | None, 

635 round: str | None, 

636 limit: int, 

637 offset: int, 

638 include_test: bool, 

639 on_date: str | None, 

640 conference_id: int | None, 

641 team_id: int | None = None, 

642 stage: str | None = None, 

643 stage_filter: str | None = None, 

644 ) -> dict | None: 

645 """The cached page, for canonical requests only. None when it has no rows. 

646 

647 ``stage`` is the cache key's; ``stage_filter`` is what the query uses. 

648 """ 

649 return self._fetch_tournament_matches_page( 

650 tournament_id=tournament_id, 

651 age_group_id=age_group_id, 

652 group=group, 

653 round=round, 

654 limit=limit, 

655 offset=offset, 

656 include_test=include_test, 

657 on_date=on_date, 

658 conference_id=conference_id, 

659 team_id=team_id, 

660 stage_filter=stage_filter, 

661 ) 

662 

663 def _fetch_tournament_matches_page( 

664 self, 

665 tournament_id: int, 

666 age_group_id: int | None, 

667 group: str | None, 

668 round: str | None, 

669 limit: int, 

670 offset: int, 

671 include_test: bool, 

672 on_date: str | None = None, 

673 conference_id: int | None = None, 

674 team_id: int | None = None, 

675 stage_filter: str | None = None, 

676 ) -> dict | None: 

677 """One page from the database. None when there are no rows on it. 

678 

679 None is deliberate: ``dao_cache`` does not store it, so a caller 

680 guessing at group names or offsets cannot fill the cache with empty 

681 answers. Any other database error is raised. 

682 """ 

683 try: 

684 response = self._execute_match_select( 

685 lambda select: ( 

686 self._filter_tournament_matches( 

687 self.client.table(MATCHES_READ_RELATION).select(select, count="exact"), 

688 tournament_id=tournament_id, 

689 age_group_id=age_group_id, 

690 group=group, 

691 round=round, 

692 include_test=include_test, 

693 on_date=on_date, 

694 conference_id=conference_id, 

695 team_id=team_id, 

696 stage_filter=stage_filter, 

697 ) 

698 .order("match_date", desc=False) 

699 .order("scheduled_kickoff", desc=False) 

700 .order("id", desc=False) 

701 .range(offset, offset + limit - 1) 

702 ) 

703 ) 

704 except APIError as exc: 

705 if exc.code == _RANGE_NOT_SATISFIABLE: 705 ↛ 706line 705 didn't jump to line 706 because the condition on line 705 was never true

706 return None 

707 logger.exception("Error fetching tournament matches page", tournament_id=tournament_id) 

708 raise 

709 

710 rows = response.data or [] 

711 if not rows: 711 ↛ 712line 711 didn't jump to line 712 because the condition on line 711 was never true

712 return None 

713 return { 

714 "matches": self._flatten_clubs(rows), 

715 "total": response.count or 0, 

716 "limit": limit, 

717 "offset": offset, 

718 } 

719 

720 def get_tournament_filters( 

721 self, 

722 tournament_id: int, 

723 *, 

724 age_group_id: int | None = None, 

725 include_test: bool = False, 

726 on_date: str | None = None, 

727 ) -> dict: 

728 """Age groups and groups a tournament can be filtered by, with match counts. 

729 

730 ``groups`` are the groups, pools and brackets inside each stage of 

731 ``age_group_id`` (of every age group when it is None), on every round 

732 (SB-1875, ``build_stage_group_options``, from the same match rows as 

733 ``stages``); when those rows could not be read, the SQL function's 

734 group-stage groups stand. ``[]`` means there are none. ``on_date`` 

735 adds each age group's count for that day. 

736 

737 ``days``, ``conferences``, ``unplaced``, ``leagues``, ``stages``, 

738 ``unstaged_count`` and ``today`` (SB-1753, SB-1865, SB-1870) are added 

739 in every case; see ``_schedule_facets``. 

740 

741 The counts come from the ``tournament_filter_facets`` SQL function, 

742 which reaches production separately from this code. Until it exists 

743 the facets are reported unavailable — ``groups`` None and every 

744 ``matches`` None — rather than as empty lists and zeros, and the age 

745 groups fall back to the tournament's own. Any other database error is 

746 raised. 

747 """ 

748 rows = self._tournament_facet_rows( 

749 tournament_id=tournament_id, 

750 age_group_id=age_group_id, 

751 include_test=include_test, 

752 on_date=on_date, 

753 ) 

754 if rows is None: 

755 payload = unavailable_filters_payload(self.get_tournament_age_groups(tournament_id)) 

756 else: 

757 payload = build_filters_payload(rows, on_date=on_date) 

758 out = { 

759 **payload, 

760 **self._schedule_facets( 

761 tournament_id, age_group_id=age_group_id, include_test=include_test, on_date=on_date 

762 ), 

763 } 

764 if not payload["facets_available"]: 

765 # Unavailable means no counts: the groups stay unknown with them. 

766 out["groups"] = None 

767 return out 

768 

769 def _schedule_facets( 

770 self, 

771 tournament_id: int, 

772 *, 

773 age_group_id: int | None, 

774 include_test: bool, 

775 on_date: str | None, 

776 ) -> dict: 

777 """Days, conferences, unplaced teams, leagues and stages of ``age_group_id``'s matches. 

778 

779 Each lookup degrades on its own: one that fails is logged and its 

780 fields are None — unknown, never zero — while the others still answer. 

781 """ 

782 rows = conferences = placements = None 

783 try: 

784 rows = self._tournament_side_rows(tournament_id, age_group_id, include_test) 

785 except Exception: 

786 logger.exception("Error fetching tournament days", tournament_id=tournament_id) 

787 try: 

788 conferences = self._conferences() 

789 except Exception: 

790 logger.exception("Error fetching conferences", tournament_id=tournament_id) 

791 if rows is not None and conferences is not None: 

792 try: 

793 ages = sorted({age for _, age in match_sides(rows, on_date=on_date)}) 

794 placements = [p for age in ages for p in self._conference_placements(age)] 

795 except Exception: 

796 logger.exception("Error fetching conference placements", tournament_id=tournament_id) 

797 return build_schedule_facets(rows, conferences, placements, on_date=on_date) 

798 

799 def _read_all(self, make_query) -> list[dict]: 

800 """Every row of ``make_query()``, read past the row cap in id order.""" 

801 rows: list[dict] = [] 

802 while True: 

803 page = make_query().order("id", desc=False).range(len(rows), len(rows) + _READ_PAGE - 1).execute() 

804 batch = page.data or [] 

805 rows.extend(batch) 

806 if len(batch) < _READ_PAGE: 

807 return rows 

808 

809 @dao_cache( 

810 "tournaments:facets:sides:{tournament_id}:age{age_group_id}:test{include_test}", 

811 ttl=TOURNAMENT_PAGE_CACHE_TTL, 

812 ) 

813 def _tournament_side_rows(self, tournament_id: int, age_group_id: int | None, include_test: bool) -> list[dict]: 

814 """Date, age group and both teams of each match, with the endpoint's filters.""" 

815 

816 def query(): 

817 q = self.client.table(MATCHES_READ_RELATION).select(_SIDE_SELECT).eq("tournament_id", tournament_id) 

818 if not include_test: 

819 q = q.eq("is_test", False) 

820 if age_group_id is not None: 

821 q = q.eq("age_group_id", age_group_id) 

822 return q 

823 

824 return self._read_all(query) 

825 

826 def search_tournament_teams( 

827 self, 

828 tournament_id: int, 

829 q: str | None, 

830 *, 

831 limit: int = TEAM_SEARCH_DEFAULT_LIMIT, 

832 include_test: bool = False, 

833 ) -> list[dict]: 

834 """Teams playing in this tournament whose team or club name contains ``q`` (SB-1870). 

835 

836 ``[]`` for a query shorter than two characters. Each entry is 

837 ``{team_id, name, club_id, club_name, logo_url, age_groups, league, 

838 league_known}``; ``league`` is the one league the team is placed in at 

839 the ages it plays here, None when it is in none or in both. 

840 ``league_known`` is False when the placements could not be looked up 

841 (logged): ``league`` None then means unknown, not "no conference". 

842 Raises when the teams themselves cannot be read. 

843 """ 

844 query = normalize_team_query(q) 

845 if query is None: 

846 return [] 

847 hits = search_team_index(self._tournament_teams(tournament_id, include_test), query, limit) 

848 try: 

849 conferences = self._conferences() 

850 ages = sorted({a["id"] for t in hits for a in t["age_groups"]}) 

851 placements = [p for age in ages for p in self._conference_placements(age)] 

852 except Exception: 

853 logger.exception("Error fetching team placements", tournament_id=tournament_id) 

854 return [{**t, "league": None, "league_known": False} for t in hits] 

855 return [ 

856 { 

857 **t, 

858 "league": team_league(conferences, placements, t["team_id"], {a["id"] for a in t["age_groups"]}), 

859 "league_known": True, 

860 } 

861 for t in hits 

862 ] 

863 

864 @dao_cache("tournaments:teams:{tournament_id}:test{include_test}", ttl=TOURNAMENT_PAGE_CACHE_TTL) 

865 def _tournament_teams(self, tournament_id: int, include_test: bool) -> list[dict]: 

866 """Every team in the tournament's matches, with its club and ages, by name. 

867 

868 One entry per tournament rather than per query, so typing cannot fill 

869 the cache with keys. 

870 """ 

871 

872 def query(): 

873 q = self.client.table(MATCHES_READ_RELATION).select(_TEAM_SIDE_SELECT).eq("tournament_id", tournament_id) 

874 if not include_test: 

875 q = q.eq("is_test", False) 

876 return q 

877 

878 rows = self._read_all(query) 

879 age_names = { 

880 r["id"]: r.get("name") for r in self.client.table("age_groups").select("id, name").execute().data or [] 

881 } 

882 return build_team_index(rows, age_names) 

883 

884 # Short like the pages: a division moved between leagues, or a team 

885 # placed by the conference backfill (SB-1748), shows within a minute. 

886 @dao_cache("tournaments:conferences", ttl=TOURNAMENT_PAGE_CACHE_TTL) 

887 def _conferences(self) -> list[dict]: 

888 """Every Homegrown and Academy conference, league then name.""" 

889 rows = self.client.table("divisions").select("id, name, league:leagues(name, is_test)").execute().data or [] 

890 return conference_divisions(rows) 

891 

892 @dao_cache("tournaments:conference_placements:age{age_group_id}", ttl=TOURNAMENT_PAGE_CACHE_TTL) 

893 def _conference_placements(self, age_group_id: int) -> list[dict]: 

894 """``team_mappings`` rows placing a team in a conference at this age group.""" 

895 conference_ids = [c["id"] for c in self._conferences()] 

896 if not conference_ids: 

897 return [] 

898 return self._read_all( 

899 lambda: self.client.table("team_mappings") 

900 .select("id, team_id, age_group_id, division_id") 

901 .eq("age_group_id", age_group_id) 

902 .in_("division_id", conference_ids) 

903 ) 

904 

905 def _conference_team_ages_or_none(self, division_id: int) -> list[dict] | None: 

906 """The conference's ``[{team_id, age_group_id}]``; None when it is not a conference. 

907 

908 Checked against the conference list first, so a caller sweeping 

909 division ids creates no cache keys. 

910 """ 

911 if division_id not in {c["id"] for c in self._conferences()}: 

912 return None 

913 return self._conference_team_ages(division_id) 

914 

915 @dao_cache("tournaments:conference_teams:{division_id}", ttl=TOURNAMENT_PAGE_CACHE_TTL) 

916 def _conference_team_ages(self, division_id: int) -> list[dict]: 

917 """Every team placed in this conference, with the age group it is placed at.""" 

918 rows = self._read_all( 

919 lambda: self.client.table("team_mappings") 

920 .select("id, team_id, age_group_id") 

921 .eq("division_id", division_id) 

922 ) 

923 return [{"team_id": r["team_id"], "age_group_id": r["age_group_id"]} for r in rows] 

924 

925 # Short-lived for the same reason as the match pages: on_date and 

926 # age_group_id are caller-supplied, so a day-long TTL would let a visitor 

927 # pile up keys that every score write then has to scan. 

928 @dao_cache( 

929 "tournaments:facets:{tournament_id}:age{age_group_id}:test{include_test}:on{on_date}", 

930 ttl=TOURNAMENT_PAGE_CACHE_TTL, 

931 ) 

932 def _tournament_facet_rows( 

933 self, 

934 tournament_id: int, 

935 age_group_id: int | None, 

936 include_test: bool, 

937 on_date: str | None, 

938 ) -> list[dict] | None: 

939 """Raw facet rows, or None when the SQL function does not exist yet. 

940 

941 None is not cached, so the first request after the migration is applied 

942 gets real counts instead of a day-old "unavailable". Only the missing 

943 function degrades: a timeout, a revoked grant or a changed signature is 

944 raised, so it is seen instead of passing for "not migrated". 

945 """ 

946 try: 

947 response = self.client.rpc( 

948 "tournament_filter_facets", 

949 { 

950 "p_tournament_id": tournament_id, 

951 "p_age_group_id": age_group_id, 

952 "p_include_test": include_test, 

953 "p_on_date": on_date, 

954 }, 

955 ).execute() 

956 return response.data or [] 

957 except APIError as exc: 

958 if exc.code == _FUNCTION_NOT_FOUND: 

959 logger.warning( 

960 "tournament_filter_facets not found; serving filters without counts", 

961 tournament_id=tournament_id, 

962 ) 

963 return None 

964 logger.exception("Error fetching tournament filter facets", tournament_id=tournament_id) 

965 raise 

966 

967 # ========================================================================= 

968 # Admin write 

969 # ========================================================================= 

970 

971 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN) 

972 def create_tournament( 

973 self, 

974 name: str, 

975 season_id: int, 

976 start_date: str, 

977 end_date: str | None = None, 

978 location: str | None = None, 

979 description: str | None = None, 

980 age_group_ids: list[int] | None = None, 

981 is_active: bool = True, 

982 announcement: str | None = None, 

983 ) -> dict: 

984 """Create a new tournament. 

985 

986 Args: 

987 name: Tournament name (e.g. '2026 Generation adidas Cup') 

988 season_id: Season the tournament belongs to 

989 start_date: ISO date string 

990 end_date: ISO date string (optional) 

991 location: Venue/city (optional) 

992 description: Free text notes (optional) 

993 age_group_ids: Age groups for the tournament (optional) 

994 is_active: Controls public visibility (default True) 

995 announcement: One-line announcement (optional; blank = none) 

996 

997 Returns: 

998 Created tournament record with age_groups list 

999 """ 

1000 data = { 

1001 "name": name, 

1002 "season_id": season_id, 

1003 "start_date": start_date, 

1004 "is_active": is_active, 

1005 } 

1006 if end_date: 1006 ↛ 1007line 1006 didn't jump to line 1007 because the condition on line 1006 was never true

1007 data["end_date"] = end_date 

1008 if location: 1008 ↛ 1009line 1008 didn't jump to line 1009 because the condition on line 1008 was never true

1009 data["location"] = location 

1010 if description: 1010 ↛ 1011line 1010 didn't jump to line 1011 because the condition on line 1010 was never true

1011 data["description"] = description 

1012 if announcement and announcement.strip(): 

1013 data["announcement"] = announcement.strip() 

1014 

1015 try: 

1016 response = self.client.table("tournaments").insert(data).execute() 

1017 tournament = response.data[0] 

1018 if age_group_ids: 1018 ↛ 1019line 1018 didn't jump to line 1019 because the condition on line 1018 was never true

1019 self._sync_age_groups(tournament["id"], age_group_ids) 

1020 return self._attach_age_groups([tournament])[0] 

1021 except Exception: 

1022 logger.exception("Error creating tournament", name=name) 

1023 raise 

1024 

1025 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN) 

1026 def update_tournament( 

1027 self, 

1028 tournament_id: int, 

1029 name: str | None = None, 

1030 season_id: int | None = None, 

1031 start_date: str | None = None, 

1032 end_date: str | None = None, 

1033 location: str | None = None, 

1034 description: str | None = None, 

1035 age_group_ids: list[int] | None = None, 

1036 is_active: bool | None = None, 

1037 logo_url: str | None = None, 

1038 announcement: str | None = None, 

1039 ) -> dict | None: 

1040 """Update tournament fields. Only provided (non-None) fields are changed. 

1041 

1042 age_group_ids replaces all existing age group links when provided. 

1043 announcement is stripped; a blank string clears it to NULL (SB-1797), 

1044 since None already means "leave unchanged". 

1045 """ 

1046 updates: dict = {} 

1047 if name is not None: 

1048 updates["name"] = name 

1049 if season_id is not None: 1049 ↛ 1050line 1049 didn't jump to line 1050 because the condition on line 1049 was never true

1050 updates["season_id"] = season_id 

1051 if start_date is not None: 1051 ↛ 1052line 1051 didn't jump to line 1052 because the condition on line 1051 was never true

1052 updates["start_date"] = start_date 

1053 if end_date is not None: 1053 ↛ 1054line 1053 didn't jump to line 1054 because the condition on line 1053 was never true

1054 updates["end_date"] = end_date 

1055 if location is not None: 1055 ↛ 1056line 1055 didn't jump to line 1056 because the condition on line 1055 was never true

1056 updates["location"] = location 

1057 if description is not None: 1057 ↛ 1058line 1057 didn't jump to line 1058 because the condition on line 1057 was never true

1058 updates["description"] = description 

1059 if is_active is not None: 1059 ↛ 1060line 1059 didn't jump to line 1060 because the condition on line 1059 was never true

1060 updates["is_active"] = is_active 

1061 if logo_url is not None: 1061 ↛ 1062line 1061 didn't jump to line 1062 because the condition on line 1061 was never true

1062 updates["logo_url"] = logo_url 

1063 if announcement is not None: 

1064 updates["announcement"] = announcement.strip() or None 

1065 

1066 try: 

1067 if updates: 1067 ↛ 1069line 1067 didn't jump to line 1069 because the condition on line 1067 was always true

1068 self.client.table("tournaments").update(updates).eq("id", tournament_id).execute() 

1069 if age_group_ids is not None: 1069 ↛ 1070line 1069 didn't jump to line 1070 because the condition on line 1069 was never true

1070 self._sync_age_groups(tournament_id, age_group_ids) 

1071 return self.get_tournament_by_id(tournament_id) 

1072 except Exception: 

1073 logger.exception("Error updating tournament", tournament_id=tournament_id) 

1074 raise 

1075 

1076 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN) 

1077 def delete_tournament(self, tournament_id: int) -> bool: 

1078 """Delete a tournament and cascade-nullify match links (via FK ON DELETE SET NULL).""" 

1079 try: 

1080 self.client.table("tournaments").delete().eq("id", tournament_id).execute() 

1081 return True 

1082 except Exception: 

1083 logger.exception("Error deleting tournament", tournament_id=tournament_id) 

1084 return False 

1085 

1086 # ========================================================================= 

1087 # Tournament match management 

1088 # ========================================================================= 

1089 

1090 @staticmethod 

1091 def _normalize_team_name(name: str) -> str: 

1092 """Normalize a team name for comparison (trim, collapse whitespace).""" 

1093 return " ".join(name.strip().split()) 

1094 

1095 def lookup_teams_by_name(self, name: str) -> dict: 

1096 """Look up teams by name without creating anything. 

1097 

1098 Returns a dict with: 

1099 - exact: team dict if an exact (case-insensitive) match exists, else None 

1100 - similar: list of team dicts whose names contain any word from the query 

1101 """ 

1102 normalized = self._normalize_team_name(name) 

1103 

1104 # Exact case-insensitive match 

1105 exact_response = ( 

1106 self.client.table("teams") 

1107 .select("id, name, league_id, division_id, club_id") 

1108 .ilike("name", normalized) 

1109 .limit(1) 

1110 .execute() 

1111 ) 

1112 exact = exact_response.data[0] if exact_response.data else None 

1113 

1114 # Fall back to aliases so the combobox finds a team by any string a 

1115 # feed uses for it — typing the long official name should surface the 

1116 # team, not report it as new (SB-822). 

1117 if not exact: 

1118 alias_response = ( 

1119 self.client.table("team_aliases") 

1120 .select("team_id") 

1121 .ilike("external_name", normalized) 

1122 .limit(1) 

1123 .execute() 

1124 ) 

1125 if alias_response.data: 

1126 aliased = ( 

1127 self.client.table("teams") 

1128 .select("id, name, league_id, division_id, club_id") 

1129 .eq("id", alias_response.data[0]["team_id"]) 

1130 .limit(1) 

1131 .execute() 

1132 ) 

1133 exact = aliased.data[0] if aliased.data else None 

1134 

1135 # Similar: name contains any significant word (>= 4 chars) from query 

1136 similar: list[dict] = [] 

1137 if not exact: 

1138 _skip = {"city", "club", "team", "boys", "girls", "academy", "united", "soccer", "football"} 

1139 words = [w for w in normalized.split() if len(w) >= 4 and w.lower() not in _skip] 

1140 seen_ids: set[int] = set() 

1141 for word in words: 

1142 rows = ( 

1143 self.client.table("teams") 

1144 .select("id, name, league_id, division_id, club_id") 

1145 .ilike("name", f"%{word}%") 

1146 .limit(5) 

1147 .execute() 

1148 ).data or [] 

1149 for row in rows: 

1150 if row["id"] not in seen_ids: 

1151 seen_ids.add(row["id"]) 

1152 similar.append(row) 

1153 

1154 return {"exact": exact, "similar": similar} 

1155 

1156 @invalidates_cache(TEAMS_CACHE_PATTERN) 

1157 def get_or_create_opponent_team(self, name: str, age_group_id: int) -> int: 

1158 """Find an existing team by name or create a lightweight tournament-only team. 

1159 

1160 Tournament opponents are created with no league, division, or club so 

1161 they don't pollute league standings or admin team lists. 

1162 

1163 Args: 

1164 name: Opponent team name (e.g. 'Cedar Stars Academy') 

1165 age_group_id: Age group for the team 

1166 

1167 Returns: 

1168 Team ID (existing or newly created) 

1169 """ 

1170 normalized = self._normalize_team_name(name) 

1171 

1172 # Exact case-insensitive match 

1173 response = self.client.table("teams").select("id, name").ilike("name", normalized).limit(1).execute() 

1174 if response.data: 

1175 team_id = response.data[0]["id"] 

1176 logger.info("Found existing team for tournament opponent", name=normalized, team_id=team_id) 

1177 return team_id 

1178 

1179 # Then aliases (SB-822). This check is the reason the table exists: a 

1180 # miss here does not fail, it CREATES a team. That is how 

1181 # 'Intercontinental Football Academy of New England' became a duplicate 

1182 # IFA, and how a post-rename feed carrying 'Long Island Soccer Club' 

1183 # would split that club's history. 

1184 alias_response = ( 

1185 self.client.table("team_aliases").select("team_id").ilike("external_name", normalized).limit(1).execute() 

1186 ) 

1187 if alias_response.data: 

1188 team_id = alias_response.data[0]["team_id"] 

1189 logger.info( 

1190 "Resolved tournament opponent via alias — no team created", 

1191 alias=normalized, 

1192 team_id=team_id, 

1193 ) 

1194 return team_id 

1195 

1196 # Create lightweight team: no league, division, or club 

1197 team_response = ( 

1198 self.client.table("teams") 

1199 .insert( 

1200 { 

1201 "name": name, 

1202 "city": "", 

1203 "academy_team": False, 

1204 "club_id": None, 

1205 "league_id": None, 

1206 "division_id": None, 

1207 } 

1208 ) 

1209 .execute() 

1210 ) 

1211 if not team_response.data: 1211 ↛ 1212line 1211 didn't jump to line 1212 because the condition on line 1211 was never true

1212 raise RuntimeError(f"Failed to create opponent team: {name}") 

1213 

1214 team_id = team_response.data[0]["id"] 

1215 

1216 # Add age group mapping so the team can appear in age-group-filtered queries 

1217 self.client.table("team_mappings").insert( 

1218 { 

1219 "team_id": team_id, 

1220 "age_group_id": age_group_id, 

1221 "division_id": None, 

1222 } 

1223 ).execute() 

1224 

1225 logger.info("Created tournament opponent team", name=name, team_id=team_id, age_group_id=age_group_id) 

1226 return team_id 

1227 

1228 def _resolve_side( 

1229 self, 

1230 side: str, 

1231 team_id: int | None, 

1232 team_name: str | None, 

1233 age_group_id: int, 

1234 ) -> int: 

1235 """Resolve one side of a fixture to a team id. 

1236 

1237 A picked id wins over a name: the name may be stale text left in the 

1238 form after the pick (SB-817). 

1239 """ 

1240 if team_id is not None: 

1241 return team_id 

1242 if team_name and team_name.strip(): 

1243 return self.get_or_create_opponent_team(team_name.strip(), age_group_id) 

1244 raise ValueError(f"Either {side}_team_id or {side}_team_name is required") 

1245 

1246 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN, MATCHES_CACHE_PATTERN) 

1247 def create_tournament_match( 

1248 self, 

1249 tournament_id: int, 

1250 match_date: str, 

1251 age_group_id: int, 

1252 season_id: int, 

1253 home_team_id: int | None = None, 

1254 home_team_name: str | None = None, 

1255 away_team_id: int | None = None, 

1256 away_team_name: str | None = None, 

1257 our_team_id: int | None = None, 

1258 opponent_name: str | None = None, 

1259 is_home: bool = True, 

1260 home_score: int | None = None, 

1261 away_score: int | None = None, 

1262 home_penalty_score: int | None = None, 

1263 away_penalty_score: int | None = None, 

1264 match_status: str = "scheduled", 

1265 tournament_group: str | None = None, 

1266 tournament_round: str | None = None, 

1267 tournament_round_order: int | None = None, 

1268 scheduled_kickoff: str | None = None, 

1269 opponent_team_id: int | None = None, 

1270 ) -> dict: 

1271 """Create a match linked to a tournament. 

1272 

1273 Each side is either picked by id or resolved by name, and an unknown 

1274 name creates a lightweight tournament-only team. Picking is preferred: 

1275 name resolution matches exactly, so a typo mints a duplicate (SB-817). 

1276 

1277 Sides are named home/away because a tournament often has no "our team" 

1278 at all — an admin loading a bracket may track neither side (SB-819). 

1279 The older `our_team_id` + `is_home` + `opponent_*` form still works and 

1280 is mapped onto home/away here. 

1281 

1282 Args: 

1283 tournament_id: Tournament this match belongs to 

1284 match_date: ISO date string (YYYY-MM-DD) 

1285 age_group_id: Age group for both teams 

1286 season_id: Season this match falls within 

1287 home_team_id / away_team_id: existing teams chosen by the caller 

1288 home_team_name / away_team_name: team names, created if unknown. 

1289 Per side, give exactly one of id / name. 

1290 our_team_id, opponent_name, opponent_team_id, is_home: deprecated 

1291 pre-SB-819 form, mapped onto the home/away pair 

1292 home_score / away_score: Scores (None = not yet played) 

1293 match_status: 'scheduled', 'completed', etc. 

1294 tournament_group: e.g. 'Group A' 

1295 tournament_round: e.g. 'group_stage', 'quarterfinal' 

1296 scheduled_kickoff: ISO datetime string (optional) 

1297 

1298 Returns: 

1299 Created match record dict 

1300 """ 

1301 if tournament_round and tournament_round not in VALID_ROUNDS: 1301 ↛ 1302line 1301 didn't jump to line 1302 because the condition on line 1301 was never true

1302 raise ValueError(f"Invalid tournament_round '{tournament_round}'. Must be one of {VALID_ROUNDS}") 

1303 

1304 # Deprecated form: map "our team + opponent" onto the home/away pair. 

1305 if home_team_id is None and home_team_name is None and our_team_id is not None: 

1306 if is_home: 

1307 home_team_id = our_team_id 

1308 away_team_id, away_team_name = opponent_team_id, opponent_name 

1309 else: 

1310 away_team_id = our_team_id 

1311 home_team_id, home_team_name = opponent_team_id, opponent_name 

1312 

1313 home_id = self._resolve_side("home", home_team_id, home_team_name, age_group_id) 

1314 away_id = self._resolve_side("away", away_team_id, away_team_name, age_group_id) 

1315 

1316 if home_id == away_id: 

1317 raise ValueError("A team cannot play itself") 

1318 

1319 home_team_id, away_team_id = home_id, away_id 

1320 

1321 data: dict = { 

1322 "home_team_id": home_team_id, 

1323 "away_team_id": away_team_id, 

1324 "match_date": match_date, 

1325 "season_id": season_id, 

1326 "age_group_id": age_group_id, 

1327 "match_type_id": TOURNAMENT_MATCH_TYPE_ID, 

1328 "division_id": None, 

1329 "match_status": match_status, 

1330 "source": "manual", 

1331 "tournament_id": tournament_id, 

1332 } 

1333 

1334 if home_score is not None: 1334 ↛ 1335line 1334 didn't jump to line 1335 because the condition on line 1334 was never true

1335 data["home_score"] = home_score 

1336 if away_score is not None: 1336 ↛ 1337line 1336 didn't jump to line 1337 because the condition on line 1336 was never true

1337 data["away_score"] = away_score 

1338 if home_penalty_score is not None: 1338 ↛ 1339line 1338 didn't jump to line 1339 because the condition on line 1338 was never true

1339 data["home_penalty_score"] = home_penalty_score 

1340 if away_penalty_score is not None: 1340 ↛ 1341line 1340 didn't jump to line 1341 because the condition on line 1340 was never true

1341 data["away_penalty_score"] = away_penalty_score 

1342 if tournament_group: 1342 ↛ 1343line 1342 didn't jump to line 1343 because the condition on line 1342 was never true

1343 data["tournament_group"] = tournament_group 

1344 if tournament_round: 1344 ↛ 1345line 1344 didn't jump to line 1345 because the condition on line 1344 was never true

1345 data["tournament_round"] = tournament_round 

1346 if tournament_round_order is not None: 1346 ↛ 1347line 1346 didn't jump to line 1347 because the condition on line 1346 was never true

1347 data["tournament_round_order"] = tournament_round_order 

1348 if scheduled_kickoff: 1348 ↛ 1349line 1348 didn't jump to line 1349 because the condition on line 1348 was never true

1349 data["scheduled_kickoff"] = scheduled_kickoff 

1350 

1351 try: 

1352 response = self.client.table("matches").insert(data).execute() 

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

1354 raise RuntimeError("Match insert returned no data") 

1355 match = response.data[0] 

1356 logger.info( 

1357 "Created tournament match", 

1358 tournament_id=tournament_id, 

1359 match_id=match["id"], 

1360 home_team_id=home_team_id, 

1361 away_team_id=away_team_id, 

1362 ) 

1363 return match 

1364 except Exception: 

1365 logger.exception("Error creating tournament match", tournament_id=tournament_id) 

1366 raise 

1367 

1368 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN, MATCHES_CACHE_PATTERN) 

1369 def update_tournament_match( 

1370 self, 

1371 match_id: int, 

1372 home_score: int | None = None, 

1373 away_score: int | None = None, 

1374 home_penalty_score: int | None = None, 

1375 away_penalty_score: int | None = None, 

1376 match_status: str | None = None, 

1377 tournament_group: str | None = None, 

1378 tournament_round: str | None = None, 

1379 tournament_round_order: int | None = None, 

1380 scheduled_kickoff: str | None = None, 

1381 match_date: str | None = None, 

1382 swap_home_away: bool = False, 

1383 home_team_id: int | None = None, 

1384 away_team_id: int | None = None, 

1385 ) -> dict | None: 

1386 """Update score, status, or context fields on a tournament match. 

1387 

1388 home_team_id / away_team_id are the resolution path for TBD 

1389 placeholder matches: when the actual team is announced, callers 

1390 pass the new team's id and the placeholder reference is replaced. 

1391 Postgres enforces home_team_id <> away_team_id, so an accidental 

1392 self-pairing aborts the write instead of silently corrupting data. 

1393 """ 

1394 if tournament_round and tournament_round not in VALID_ROUNDS: 

1395 raise ValueError(f"Invalid tournament_round '{tournament_round}'. Must be one of {VALID_ROUNDS}") 

1396 if swap_home_away and (home_team_id is not None or away_team_id is not None): 

1397 raise ValueError("swap_home_away is mutually exclusive with home_team_id / away_team_id") 

1398 

1399 updates: dict = {} 

1400 if home_score is not None: 

1401 updates["home_score"] = home_score 

1402 if away_score is not None: 

1403 updates["away_score"] = away_score 

1404 if home_penalty_score is not None: 

1405 updates["home_penalty_score"] = home_penalty_score 

1406 if away_penalty_score is not None: 

1407 updates["away_penalty_score"] = away_penalty_score 

1408 if match_status is not None: 

1409 updates["match_status"] = match_status 

1410 if tournament_group is not None: 

1411 updates["tournament_group"] = tournament_group 

1412 if tournament_round is not None: 

1413 updates["tournament_round"] = tournament_round 

1414 if tournament_round_order is not None: 

1415 updates["tournament_round_order"] = tournament_round_order 

1416 if scheduled_kickoff is not None: 

1417 updates["scheduled_kickoff"] = scheduled_kickoff 

1418 if match_date is not None: 

1419 updates["match_date"] = match_date 

1420 if home_team_id is not None: 

1421 updates["home_team_id"] = home_team_id 

1422 if away_team_id is not None: 

1423 updates["away_team_id"] = away_team_id 

1424 

1425 if swap_home_away: 

1426 # Fetch current team IDs to swap them 

1427 current = ( 

1428 self.client.table("matches").select("home_team_id, away_team_id").eq("id", match_id).single().execute() 

1429 ).data 

1430 if current: 

1431 updates["home_team_id"] = current["away_team_id"] 

1432 updates["away_team_id"] = current["home_team_id"] 

1433 

1434 if not updates: 

1435 return None 

1436 

1437 try: 

1438 response = self.client.table("matches").update(updates).eq("id", match_id).execute() 

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

1440 except Exception: 

1441 logger.exception("Error updating tournament match", match_id=match_id) 

1442 raise 

1443 

1444 @invalidates_cache(TOURNAMENTS_CACHE_PATTERN, MATCHES_CACHE_PATTERN) 

1445 def delete_tournament_match(self, match_id: int) -> bool: 

1446 """Remove a match from a tournament (deletes the match record entirely).""" 

1447 try: 

1448 self.client.table("matches").delete().eq("id", match_id).execute() 

1449 return True 

1450 except Exception: 

1451 logger.exception("Error deleting tournament match", match_id=match_id) 

1452 return False