Coverage for dao/team_dao.py: 42.35%
470 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Team Data Access Object.
4Handles all database operations related to teams including:
5- Team CRUD operations
6- Team-age group mappings
7- Team-match type participations
8- Team queries and filters
9- Team-club associations
10"""
12import structlog
13from postgrest.exceptions import APIError
15from dao.base_dao import MATCHES_READ_RELATION, BaseDAO, clear_cache, dao_cache, invalidates_cache
16from dao.team_sides import (
17 AMBIGUOUS,
18 MISSING,
19 RESOLVED,
20 UNKNOWN_LEAGUE,
21 Candidate,
22 Resolution,
23 classify,
24 league_named,
25 sides_at_age,
26 team_sides,
27 top_level_league,
28)
30logger = structlog.get_logger()
33def like_literal(text: str) -> str:
34 """`text` as a LIKE pattern that matches only itself (SB-1748).
36 A feed name is data, not a pattern: unescaped, 'I%' is every name that
37 starts with I, and one ending in a backslash is a database error.
38 """
39 return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
42def _same_name(left: str | None, right: str) -> bool:
43 """Equal apart from letter case and runs of whitespace."""
44 return " ".join((left or "").split()).casefold() == " ".join(right.split()).casefold()
47def _is_unqueryable_name(exc: APIError) -> bool:
48 """Whether the database refused the name itself, rather than failing.
50 Postgres class 22 is a data exception (a pattern or byte it cannot read);
51 PGRST100 is PostgREST failing to parse the filter. Neither will be any
52 different on a retry.
53 """
54 code = exc.code or ""
55 return code.startswith("22") or code == "PGRST100"
58# Cache pattern for invalidation
59TEAMS_CACHE_PATTERN = "mt:dao:teams:*"
62def flatten_team_mappings(team: dict) -> None:
63 """Flatten a team's embedded ``team_mappings`` rows in place (SB-1468).
65 A team can be registered at one age group in several divisions — e.g.
66 Homegrown Northeast plus two Flex conferences. Sets:
68 - ``age_groups``: each age group once, in first-seen order.
69 - ``divisions_by_age_group_all``: ``{age_group_id: [division, ...]}`` —
70 every division, ordered home league first, then by division id.
71 - ``divisions_by_age_group``: ``{age_group_id: division}`` — the first of
72 the above. Kept for older clients; it cannot represent more than one
73 division, so league-aware callers must read the ``_all`` form.
74 """
75 home_league_id = team.get("league_id")
76 age_groups: list[dict] = []
77 seen: set = set()
78 all_divisions: dict = {}
79 for mapping in team.get("team_mappings") or []:
80 age_group = mapping.get("age_groups")
81 if not age_group:
82 continue
83 ag_id = age_group["id"]
84 if ag_id not in seen:
85 seen.add(ag_id)
86 age_groups.append(age_group)
87 division = mapping.get("divisions")
88 if division:
89 if division.get("leagues"):
90 division["league_name"] = division["leagues"]["name"]
91 division["sport_type"] = division["leagues"].get("sport_type", "soccer")
92 bucket = all_divisions.setdefault(ag_id, [])
93 if all(d.get("id") != division.get("id") for d in bucket):
94 bucket.append(division)
96 def rank(division: dict) -> tuple:
97 is_home = home_league_id is not None and division.get("league_id") == home_league_id
98 return (0 if is_home else 1, division.get("id") or 0)
100 for bucket in all_divisions.values():
101 bucket.sort(key=rank)
102 team["age_groups"] = age_groups
103 team["divisions_by_age_group_all"] = all_divisions
104 team["divisions_by_age_group"] = {ag_id: bucket[0] for ag_id, bucket in all_divisions.items()}
107class TeamDAO(BaseDAO):
108 """Data access object for team operations."""
110 # === Team Query Methods ===
112 @dao_cache("teams:all")
113 def get_all_teams(self) -> list[dict]:
114 """Get all teams with their age groups."""
115 response = (
116 self.client.table("teams")
117 .select("""
118 *,
119 leagues!teams_league_id_fkey (
120 id,
121 name,
122 sport_type
123 ),
124 team_mappings (
125 age_groups (
126 id,
127 name
128 ),
129 divisions (
130 id,
131 name,
132 league_id,
133 leagues!divisions_league_id_fkey (
134 id,
135 name,
136 sport_type
137 )
138 )
139 )
140 """)
141 .order("name")
142 .execute()
143 )
145 # Flatten the age groups and divisions for each team
146 teams = []
147 for team in response.data:
148 # Extract league_name from the joined leagues table
149 if team.get("leagues"):
150 team["league_name"] = team["leagues"]["name"]
152 flatten_team_mappings(team)
153 teams.append(team)
155 return teams
157 @dao_cache("teams:by_match_type:{match_type_id}:{age_group_id}:{division_id}")
158 def get_teams_by_match_type_and_age_group(
159 self, match_type_id: int, age_group_id: int, division_id: int | None = None
160 ) -> list[dict]:
161 """Get teams that can participate in a specific match type and age group.
163 Args:
164 match_type_id: Filter by match type (e.g., League, Cup)
165 age_group_id: Filter by age group (e.g., U14, U15)
166 division_id: Optional - Filter by division (e.g., Bracket A for Futsal)
168 Note: Due to PostgREST limitations with multiple inner joins, we query
169 junction tables directly and intersect results when filtering by division.
170 """
171 # Get team IDs that have the required match type
172 mt_response = (
173 self.client.table("team_match_types")
174 .select("team_id")
175 .eq("match_type_id", match_type_id)
176 .eq("age_group_id", age_group_id)
177 .eq("is_active", True)
178 .execute()
179 )
180 match_type_team_ids = {r["team_id"] for r in mt_response.data}
182 if not match_type_team_ids:
183 return []
185 # If division filter is specified, intersect with division teams
186 if division_id:
187 div_response = (
188 self.client.table("team_mappings")
189 .select("team_id")
190 .eq("age_group_id", age_group_id)
191 .eq("division_id", division_id)
192 .execute()
193 )
194 division_team_ids = {r["team_id"] for r in div_response.data}
195 final_team_ids = match_type_team_ids & division_team_ids
196 else:
197 final_team_ids = match_type_team_ids
199 if not final_team_ids:
200 return []
202 # Fetch full team data for the filtered IDs
203 response = (
204 self.client.table("teams")
205 .select("""
206 *,
207 team_mappings (
208 age_groups (
209 id,
210 name
211 ),
212 divisions (
213 id,
214 name
215 )
216 )
217 """)
218 .in_("id", list(final_team_ids))
219 .order("name")
220 .execute()
221 )
223 # Flatten the age groups and divisions for each team
224 teams = []
225 for team in response.data:
226 flatten_team_mappings(team)
227 teams.append(team)
229 return teams
231 @dao_cache("teams:by_age_group_mapping:{age_group_id}")
232 def get_teams_by_age_group_mapping(self, age_group_id: int) -> list[dict]:
233 """Get every team that has a team_mappings row for this age group.
235 This is the lookup used for tournament match editing: tournament-only
236 opponents (created via get_or_create_opponent_team) have a
237 team_mappings row for the age group but no team_match_types row, so
238 the stricter get_teams_by_match_type_and_age_group filter excludes
239 them. Use this to widen the candidate set when editing a tournament
240 match.
241 """
242 mapping_response = (
243 self.client.table("team_mappings").select("team_id").eq("age_group_id", age_group_id).execute()
244 )
245 team_ids = list({r["team_id"] for r in mapping_response.data})
246 if not team_ids:
247 return []
249 response = (
250 self.client.table("teams")
251 .select("""
252 *,
253 team_mappings (
254 age_groups (
255 id,
256 name
257 ),
258 divisions (
259 id,
260 name
261 )
262 )
263 """)
264 .in_("id", team_ids)
265 .order("name")
266 .execute()
267 )
269 teams = []
270 for team in response.data:
271 flatten_team_mappings(team)
272 teams.append(team)
274 return teams
276 @dao_cache("teams:by_name:{name}")
277 def get_team_by_name(self, name: str) -> dict | None:
278 """Get a team by name (case-insensitive exact match).
280 Returns the first matching team with basic info (id, name, city).
281 For match-scraper integration, this helps look up teams by name.
282 """
283 response = (
284 self.client.table("teams").select("id, name, city, academy_team").ilike("name", name).limit(1).execute()
285 )
287 if response.data and len(response.data) > 0:
288 return response.data[0]
289 return None
291 def resolve_team_by_name(self, name: str, league_id: int | None = None) -> dict | None:
292 """Resolve any string a source might use for a team to the team row.
294 Checks teams.name first, then team_aliases.external_name (SB-822).
295 Returns None only when the name is genuinely unknown.
297 This is the single resolution point every name-based lookup should use.
298 Before it existed, a feed spelling a team differently did not match —
299 and on the tournament path it did not fail either, it created a second
300 team. 'Intercontinental Football Academy of New England' produced a
301 duplicate IFA exactly that way.
303 Matching is case-insensitive and whitespace-normalised on both sides,
304 mirroring the unique index on lower(external_name).
306 Alias rows are scoped by (external_name, league_id, source), so the same
307 string CAN legitimately point at different teams in different leagues.
308 Pass `league_id` when the caller knows it (match ingest does) and the
309 ambiguity resolves; league-agnostic aliases (league_id IS NULL) still
310 match, so scoping never loses a hit. Without it — or when the name is
311 still ambiguous after scoping — this returns None rather than guessing,
312 because picking the wrong team silently is worse than reporting the
313 name as unresolved.
315 An alias scoped to `league_id` is checked BEFORE the exact team name
316 (SB-1652). Team names are globally unique, so a club's Homegrown team
317 holds the bare club name ('FC Greater Boston Bolts') that the Academy
318 feed also sends for the club's separate Academy team. With the exact
319 name first, Academy fixtures landed on the Homegrown row and no alias
320 could redirect them. A league-scoped alias is a deliberate statement
321 about that league, so it wins; with none, resolution is unchanged.
322 """
323 normalized = " ".join((name or "").strip().split())
324 if not normalized:
325 return None
327 rows: list[dict] | None = None
328 if league_id is not None:
329 rows = self._alias_rows(normalized)
330 in_league = [r for r in rows if r.get("league_id") == league_id]
331 if in_league:
332 return self._resolve_alias_rows(normalized, in_league, league_id)
334 direct = self.get_team_by_name(normalized)
335 if direct:
336 return direct
338 if rows is None:
339 rows = self._alias_rows(normalized)
340 if league_id is not None:
341 # A row with no league applies everywhere; a row with one applies
342 # only to that league. Narrow before checking for ambiguity.
343 scoped = [r for r in rows if r.get("league_id") in (None, league_id)]
344 if scoped:
345 rows = scoped
346 if not rows:
347 return None
348 return self._resolve_alias_rows(normalized, rows, league_id)
350 # What resolve_tournament_team reads for each candidate: the row the ingest
351 # task uses, plus where the team is registered to play.
352 _SIDE_COLUMNS = "id, name, city, club_id, league_id, team_mappings(age_group_id, divisions(league_id))"
354 def league_rows(self) -> list[dict]:
355 """Every league with its parent: what a team's side is folded with (SB-1748).
357 Six rows that change a few times a year, so the ingest worker reads
358 them once and hands them to resolve_tournament_team. Raises on a
359 database error.
360 """
361 return self.client.table("leagues").select("id, name, parent_league_id").execute().data or []
363 def resolve_tournament_team(
364 self, name: str, age_group_id: int | None, league: str | None, leagues: list[dict] | None = None
365 ) -> tuple[dict | None, Resolution]:
366 """The team a tournament message's name refers to, on the right side (SB-1748).
368 A tournament puts Homegrown and Academy in one event, and a club's two
369 teams share a name. resolve_team_by_name takes an exact teams.name hit
370 without asking which side it is on, which files an Academy fixture on
371 the Homegrown team's history. Here `league` — the side as the message
372 names it — decides, and a name that cannot be placed fails:
374 0. A `league` that names no league MT has is UNKNOWN_LEAGUE, and no
375 team is looked up: every name would otherwise fail as "wrong side",
376 one misleading row per team for one wrong string.
377 1. An alias scoped to the message's league (SB-1652). A deliberate
378 statement about that league, so it is trusted as it stands.
379 2. Every team whose name matches exactly — all of them, not the first.
380 3. Aliases with no league.
381 4. The side guard (dao.team_sides), on the first of 2 and 3 that found
382 anything: the candidate on the hinted side at this age group, or a
383 failure. With no hint, a single candidate.
385 `leagues` is the rows of league_rows(), for a caller that keeps them;
386 left out, they are read here when there is a hint to compare.
388 Returns `(team, resolution)`; `team` is None unless the resolution is
389 RESOLVED. No fuzzy matching, and nothing is created or guessed. The
390 name is matched as text, never as a pattern, and one the database
391 cannot be asked about at all is MISSING. Any other database error is
392 raised, so a blip is retried rather than recorded as an unknown name.
393 """
394 normalized = " ".join((name or "").strip().split())
395 if not normalized: 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 return None, Resolution(MISSING)
398 hint = (league or "").strip() or None
399 by_id: dict[int, dict] = {}
400 hint_league_id = None
401 if hint:
402 by_id = {row["id"]: row for row in (self.league_rows() if leagues is None else leagues)}
403 hint_league_id = league_named(hint, by_id)
404 if hint_league_id is None: 404 ↛ 405line 404 didn't jump to line 405 because the condition on line 404 was never true
405 return None, Resolution(UNKNOWN_LEAGUE, reason=f"unknown league '{hint}'")
407 try:
408 return self._place_tournament_team(normalized, age_group_id, hint, hint_league_id, by_id)
409 except APIError as exc:
410 if not _is_unqueryable_name(exc):
411 raise
412 logger.warning("Tournament team name could not be queried", team_name=normalized, code=exc.code)
413 return None, Resolution(MISSING)
415 def _place_tournament_team(
416 self,
417 normalized: str,
418 age_group_id: int | None,
419 hint: str | None,
420 hint_league_id: int | None,
421 leagues: dict[int, dict],
422 ) -> tuple[dict | None, Resolution]:
423 """Steps 1 to 4 of resolve_tournament_team."""
424 alias_rows: list[dict] | None = None
425 if hint_league_id is not None:
426 alias_rows = self._exact_alias_rows(normalized)
427 in_league = sorted({r["team_id"] for r in alias_rows if r.get("league_id") == hint_league_id})
428 if len(in_league) > 1: 428 ↛ 429line 428 didn't jump to line 429 because the condition on line 428 was never true
429 ids = ", ".join(str(team_id) for team_id in in_league)
430 return None, Resolution(AMBIGUOUS, reason=f"ambiguous: team ids {ids}")
431 if in_league:
432 rows = self._side_rows(ids=in_league)
433 if rows: 433 ↛ 436line 433 didn't jump to line 436 because the condition on line 433 was always true
434 return self._without_mappings(rows[0]), Resolution(RESOLVED, team_id=rows[0]["id"])
436 rows = self._side_rows(name=normalized)
437 if not rows:
438 if alias_rows is None:
439 alias_rows = self._exact_alias_rows(normalized)
440 agnostic = sorted({r["team_id"] for r in alias_rows if r.get("league_id") is None})
441 if agnostic:
442 rows = self._side_rows(ids=agnostic)
444 candidates = []
445 for row in rows:
446 mappings = [
447 (mapping.get("age_group_id"), (mapping.get("divisions") or {}).get("league_id"))
448 for mapping in row.get("team_mappings") or []
449 ]
450 candidates.append(
451 Candidate(
452 team_id=row["id"],
453 sides=team_sides(mappings, row.get("league_id"), age_group_id, leagues),
454 sides_at_age=sides_at_age(mappings, age_group_id, leagues),
455 )
456 )
457 # The hint is compared as its top-level league, as a team's sides are.
458 resolution = classify(candidates, top_level_league(hint_league_id, leagues) or hint)
459 if resolution.status != RESOLVED:
460 self._log_unresolved(normalized, hint, age_group_id, resolution)
461 return None, resolution
462 team = next(row for row in rows if row["id"] == resolution.team_id)
463 return self._without_mappings(team), resolution
465 def _log_unresolved(self, normalized: str, hint: str | None, age_group_id: int | None, resolution) -> None:
466 """Warn that a tournament name was not placed.
468 Its own method so that a caller classifying a whole event's names at
469 once (dao.ingest_plan_dao, SB-1763) can report them itself instead of
470 logging fifteen hundred lines. Ingest logs every one, as it did.
471 """
472 logger.warning(
473 "Tournament team name not resolved",
474 team_name=normalized,
475 league=hint,
476 age_group_id=age_group_id,
477 status=resolution.status,
478 reason=resolution.reason,
479 )
481 def _side_rows(self, *, name: str | None = None, ids: list[int] | None = None) -> list[dict]:
482 """Teams by exact name or by id, each with its mappings' leagues."""
483 query = self.client.table("teams").select(self._SIDE_COLUMNS)
484 if ids is not None:
485 return query.in_("id", ids).execute().data or []
486 rows = query.ilike("name", like_literal(name)).execute().data or []
487 # PostgREST still reads * as a wildcard; keep exact hits only.
488 return [row for row in rows if _same_name(row.get("name"), name)]
490 def _exact_alias_rows(self, normalized: str) -> list[dict]:
491 """team_aliases rows whose external_name is this name, any league.
493 _alias_rows, which league messages keep, hands the name to ilike as a
494 pattern. A tournament name is matched as text: escaped, then checked.
495 """
496 rows = (
497 self.client.table("team_aliases")
498 .select("team_id, league_id, source, external_name")
499 .ilike("external_name", like_literal(normalized))
500 .execute()
501 ).data or []
502 return [row for row in rows if _same_name(row.get("external_name"), normalized)]
504 @staticmethod
505 def _without_mappings(row: dict) -> dict:
506 return {key: value for key, value in row.items() if key != "team_mappings"}
508 def alias_conflict(self, name: str, team_id: int, league_id: int | None = None) -> dict | None:
509 """The team an alias for `team_id` would collide with, or None.
511 Without a league, any other team the string already resolves to is a
512 collision. With one, only a team the string reaches *inside that
513 league* is: an Academy-scoped 'FC Greater Boston Bolts' pointing at
514 the club's Academy team does not collide with the Homegrown team that
515 owns the bare name (SB-1652). That case is the reason league-scoped
516 aliases exist.
517 """
518 normalized = " ".join((name or "").strip().split())
519 if league_id is None:
520 existing = self.resolve_team_by_name(normalized)
521 return existing if existing and existing["id"] != team_id else None
523 for row in self._alias_rows(normalized):
524 if row["team_id"] == team_id: 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 continue
526 if row.get("league_id") == league_id or (
527 row.get("league_id") is None and self._team_league_id(row["team_id"]) == league_id
528 ):
529 return self.get_team_by_id(row["team_id"])
531 direct = self.get_team_by_name(normalized)
532 if direct and direct["id"] != team_id and self._team_league_id(direct["id"]) == league_id:
533 return direct
534 return None
536 def _team_league_id(self, team_id: int) -> int | None:
537 response = self.client.table("teams").select("league_id").eq("id", team_id).limit(1).execute()
538 return response.data[0].get("league_id") if response.data else None
540 def _alias_rows(self, normalized: str) -> list[dict]:
541 """Every team_aliases row whose external_name matches, any league."""
542 alias_resp = (
543 self.client.table("team_aliases")
544 .select("team_id, league_id, source")
545 .ilike("external_name", normalized)
546 .execute()
547 )
548 return alias_resp.data or []
550 def _resolve_alias_rows(self, normalized: str, rows: list[dict], league_id: int | None) -> dict | None:
551 """The team the alias rows point at, or None if they disagree."""
552 team_ids = {r["team_id"] for r in rows}
553 if len(team_ids) > 1:
554 logger.warning(
555 "Alias is ambiguous across leagues — refusing to guess",
556 alias=normalized,
557 league_id=league_id,
558 team_ids=sorted(team_ids),
559 )
560 return None
562 team_id = rows[0]["team_id"]
563 resolved = self.get_team_by_id(team_id)
564 if resolved: 564 ↛ 572line 564 didn't jump to line 572 because the condition on line 564 was always true
565 logger.info(
566 "Resolved team via alias",
567 alias=normalized,
568 team_id=team_id,
569 team_name=resolved.get("name"),
570 source=rows[0].get("source"),
571 )
572 return resolved
574 # Words too generic to be a useful near-match signal — every other club is
575 # a "Soccer Club" and matching on that returns noise, not candidates.
576 _SIMILAR_STOPWORDS = frozenset({"city", "club", "team", "boys", "girls", "academy", "united", "soccer", "football"})
578 def reconcile_names(self, names: list[str], league_id: int | None = None, similar_limit: int = 5) -> list[dict]:
579 """Report which of these names MT already knows. Creates nothing (SB-823).
581 The point is to let a load be dry-run before it writes. The failure this
582 prevents is not a crash — it is `get_or_create_opponent_team` quietly
583 inventing a lightweight team on a miss, which is how a duplicate IFA
584 appeared and had to be merged back by hand.
586 Each result carries a status:
587 known the name matches teams.name outright
588 alias it resolved through team_aliases to a different canonical name
589 unknown MT has never seen it
591 `alias` is reported separately from `known` on purpose. Both mean "will
592 resolve", but an alias hit tells the reader the feed and the database
593 disagree on spelling, which is worth seeing even when nothing is broken.
595 For unknown names, near-matches are returned. A name one word away from
596 an existing team is the signal a human needs — and this endpoint
597 deliberately does NOT guess from it. Whether "Red Bull New York" is a
598 rename of "New York Red Bulls" or a new club is a human judgement; the
599 evidence that settled it was the crest still being served from
600 kitman.imgix.net/newyorkredbulls/, which no string comparison would
601 think to look at.
602 """
603 results: list[dict] = []
604 for raw in names:
605 normalized = " ".join((raw or "").strip().split())
606 if not normalized:
607 results.append({"name": raw, "status": "unknown", "similar": []})
608 continue
610 direct = self.get_team_by_name(normalized)
611 if direct:
612 results.append({"name": raw, "status": "known", "team_id": direct["id"], "team_name": direct["name"]})
613 continue
615 resolved = self.resolve_team_by_name(normalized, league_id=league_id)
616 if resolved:
617 results.append(
618 {"name": raw, "status": "alias", "team_id": resolved["id"], "team_name": resolved.get("name")}
619 )
620 continue
622 results.append(
623 {"name": raw, "status": "unknown", "similar": self._similar_teams(normalized, similar_limit)}
624 )
626 return results
628 def _similar_teams(self, normalized: str, limit: int) -> list[dict]:
629 """Teams whose name shares a significant word with this one."""
630 words = [w for w in normalized.split() if len(w) >= 4 and w.lower() not in self._SIMILAR_STOPWORDS]
631 seen: set[int] = set()
632 out: list[dict] = []
633 for word in words:
634 try:
635 rows = (
636 self.client.table("teams")
637 .select("id, name, club_id, division_id")
638 .ilike("name", f"%{word}%")
639 .limit(limit)
640 .execute()
641 ).data or []
642 except Exception:
643 logger.exception("Near-match lookup failed", word=word)
644 continue
645 for row in rows:
646 if row["id"] not in seen:
647 seen.add(row["id"])
648 out.append(row)
649 if len(out) >= limit: 649 ↛ 650line 649 didn't jump to line 650 because the condition on line 649 was never true
650 break
651 return out[:limit]
653 @invalidates_cache(TEAMS_CACHE_PATTERN)
654 def add_team_alias(
655 self,
656 team_id: int,
657 external_name: str,
658 source: str = "mlssoccer.com",
659 kind: str = "feed_variant",
660 league_id: int | None = None,
661 ) -> dict:
662 """Record a string that should resolve to this team.
664 league_id is optional: a former name belongs to the club, not to a
665 league. source records which external system uses the spelling, which
666 matters now that MLS Next has moved from mlssoccer.com to kitman.
667 """
668 row = {
669 "team_id": team_id,
670 "external_name": " ".join(external_name.strip().split()),
671 "source": source,
672 "kind": kind,
673 "league_id": league_id,
674 }
675 response = self.client.table("team_aliases").insert(row).execute()
676 return response.data[0] if response.data else {}
678 def get_team_aliases(self, team_id: int) -> list[dict]:
679 """Every alias recorded for a team."""
680 response = (
681 self.client.table("team_aliases")
682 .select("id, external_name, source, kind, league_id, created_at")
683 .eq("team_id", team_id)
684 .order("external_name")
685 .execute()
686 )
687 return response.data or []
689 def merge_team(self, from_id: int, into_id: int, dry_run: bool = True) -> dict:
690 """Fold a duplicate team into its canonical row (SB-1822).
692 One transaction in the database (merge_team RPC): matches, mappings,
693 rosters, follows and every other team reference move to `into_id`,
694 collisions are dropped, the source name is kept as a former_name alias
695 so the feed still resolves it, and the source team is deleted. A dry
696 run reports the same per-table counts and changes nothing. A real run
697 raises while the dry run lists blockers.
698 """
699 response = self.client.rpc("merge_team", {"p_from": from_id, "p_into": into_id, "p_dry_run": dry_run}).execute()
700 if not dry_run:
701 # Matches, standings, stats and rosters all moved, not just teams.
702 clear_cache("mt:dao:*")
703 return response.data or {}
705 def get_team_by_name_and_division(self, name: str, division_id: int | None) -> dict | None:
706 """Get a team by name (exact match, case-sensitive) within a specific division.
708 Matches the teams_name_division_unique DB constraint exactly: team
709 names are unique within a division (and within the (name, NULL) slot
710 for guest/tournament teams with no division). The constraint is
711 case-sensitive, so this lookup is too — anything else risks returning
712 the wrong row when two rows differ only by case. Used by the
713 create-team endpoint to recover the existing row when the DB raises
714 that unique violation, so the endpoint becomes idempotent.
716 Returns the full team row if found, None otherwise.
717 """
718 query = self.client.table("teams").select("*").eq("name", name)
719 query = query.is_("division_id", "null") if division_id is None else query.eq("division_id", division_id)
720 response = query.limit(1).execute()
721 if response.data and len(response.data) > 0:
722 return response.data[0]
723 return None
725 @dao_cache("teams:by_id:{team_id}")
726 def get_team_by_id(self, team_id: int) -> dict | None:
727 """Get a team by ID.
729 Returns team info (id, name, city, club_id).
730 """
731 response = self.client.table("teams").select("id, name, city, club_id").eq("id", team_id).limit(1).execute()
733 if response.data and len(response.data) > 0:
734 return response.data[0]
735 return None
737 @dao_cache("teams:with_details:{team_id}")
738 def get_team_with_details(self, team_id: int) -> dict | None:
739 """Get a team with club, league, division, and age group details.
741 Returns enriched team info for the team roster page header.
742 """
743 response = (
744 self.client.table("teams")
745 .select("""
746 id, name, city, academy_team, league_id,
747 club:clubs(id, name, logo_url, primary_color, secondary_color),
748 division:divisions(id, name),
749 age_group:age_groups(id, name)
750 """)
751 .eq("id", team_id)
752 .limit(1)
753 .execute()
754 )
756 if not response.data or len(response.data) == 0:
757 return None
759 team = response.data[0]
760 result = {
761 "id": team.get("id"),
762 "name": team.get("name"),
763 "city": team.get("city"),
764 "academy_team": team.get("academy_team"),
765 "club": team.get("club"),
766 "league": None,
767 "division": team.get("division"),
768 "age_group": team.get("age_group"),
769 }
771 # Fetch league separately (no FK relationship)
772 league_id = team.get("league_id")
773 if league_id:
774 league_response = self.client.table("match_types").select("id, name").eq("id", league_id).limit(1).execute()
775 if league_response.data and len(league_response.data) > 0:
776 result["league"] = league_response.data[0]
778 return result
780 @dao_cache("teams:club_basic:{club_id}")
781 def get_club_teams_basic(self, club_id: int) -> list[dict]:
782 """Get teams for a club without match/player counts."""
783 response = (
784 self.client.table("teams_with_league_badges")
785 .select("id,name,club_id,league_id,league_name,mapping_league_names")
786 .eq("club_id", club_id)
787 .order("name")
788 .execute()
789 )
790 return [*response.data]
792 @dao_cache("teams:club:{club_id}:test{include_test}")
793 def get_club_teams(self, club_id: int, include_test: bool = False) -> list[dict]:
794 """Get all teams for a club across all leagues.
796 Args:
797 club_id: The club ID from the clubs table
798 include_test: SB-591 test partition gate for the match counts
800 Returns:
801 List of teams belonging to this club with team_mappings included,
802 plus match_count, player_count, age_group_name, and division_name
803 """
804 response = (
805 self.client.table("teams")
806 .select("""
807 *,
808 leagues!teams_league_id_fkey (
809 id,
810 name
811 ),
812 team_mappings (
813 age_groups (
814 id,
815 name
816 ),
817 divisions (
818 id,
819 name,
820 league_id,
821 leagues!divisions_league_id_fkey (
822 id,
823 name
824 )
825 )
826 )
827 """)
828 .eq("club_id", club_id)
829 .order("name")
830 .execute()
831 )
833 # Get team IDs for batch counting
834 team_ids = [team["id"] for team in response.data]
836 # Get match counts for all teams in one query
837 match_counts: dict[int, int] = {}
838 if team_ids:
839 # SB-591: count through the test-partition view so a test fixture
840 # never inflates a real team's match count.
841 home_q = self.client.table(MATCHES_READ_RELATION).select("home_team_id").in_("home_team_id", team_ids)
842 away_q = self.client.table(MATCHES_READ_RELATION).select("away_team_id").in_("away_team_id", team_ids)
843 if not include_test:
844 home_q = home_q.eq("is_test", False)
845 away_q = away_q.eq("is_test", False)
846 home_matches = home_q.execute()
847 away_matches = away_q.execute()
848 for match in home_matches.data:
849 tid = match["home_team_id"]
850 match_counts[tid] = match_counts.get(tid, 0) + 1
851 for match in away_matches.data:
852 tid = match["away_team_id"]
853 match_counts[tid] = match_counts.get(tid, 0) + 1
855 # Get player counts for all teams in one query
856 player_counts: dict[int, int] = {}
857 if team_ids:
858 players = self.client.table("user_profiles").select("team_id").in_("team_id", team_ids).execute()
859 for player in players.data:
860 tid = player["team_id"]
861 player_counts[tid] = player_counts.get(tid, 0) + 1
863 # Process teams to add league_name and age_groups
864 teams = []
865 for team in response.data:
866 team_data = {**team}
867 if team.get("leagues"):
868 team_data["league_name"] = team["leagues"].get("name")
869 else:
870 team_data["league_name"] = None
872 age_groups = []
873 first_division_name = None
874 if team.get("team_mappings"):
875 seen_age_groups = set()
876 for mapping in team["team_mappings"]:
877 if mapping.get("age_groups"):
878 ag_id = mapping["age_groups"]["id"]
879 if ag_id not in seen_age_groups:
880 age_groups.append(mapping["age_groups"])
881 seen_age_groups.add(ag_id)
882 if first_division_name is None and mapping.get("divisions"):
883 first_division_name = mapping["divisions"].get("name")
884 team_data["age_groups"] = age_groups
885 team_data["age_group_name"] = age_groups[0]["name"] if age_groups else None
886 team_data["division_name"] = first_division_name
887 team_data["match_count"] = match_counts.get(team["id"], 0)
888 team_data["player_count"] = player_counts.get(team["id"], 0)
890 teams.append(team_data)
892 return teams
894 # === Team CRUD Methods ===
896 @invalidates_cache(TEAMS_CACHE_PATTERN)
897 def add_team(
898 self,
899 name: str,
900 city: str,
901 age_group_ids: list[int],
902 match_type_ids: list[int] | None = None,
903 division_id: int | None = None,
904 club_id: int | None = None,
905 academy_team: bool = False,
906 ) -> dict | None:
907 """Add a new team with age groups, division, and optional club.
909 Args:
910 name: Team name
911 city: Team city
912 age_group_ids: List of age group IDs (required, at least one)
913 match_type_ids: List of match type IDs (optional)
914 division_id: Division ID (optional, only required for league teams)
915 club_id: Optional club ID
916 academy_team: Whether this is an academy team
918 Returns:
919 The created team row dict on success, None on failure. Callers
920 that previously checked truthiness (`if add_team(...)`) keep working.
921 """
922 logger.info(
923 "Creating team",
924 team_name=name,
925 city=city,
926 age_group_count=len(age_group_ids),
927 match_type_count=len(match_type_ids) if match_type_ids else 0,
928 division_id=division_id,
929 club_id=club_id,
930 academy_team=academy_team,
931 )
933 # Validate required fields
934 if not age_group_ids or len(age_group_ids) == 0:
935 raise ValueError("Team must have at least one age group")
937 # Get league_id from division (if division provided)
938 league_id = None
939 if division_id is not None:
940 division_response = self.client.table("divisions").select("league_id").eq("id", division_id).execute()
941 if not division_response.data:
942 raise ValueError(f"Division {division_id} not found")
943 league_id = division_response.data[0]["league_id"]
945 # Insert team
946 team_data = {
947 "name": name,
948 "city": city,
949 "academy_team": academy_team,
950 "club_id": club_id,
951 "league_id": league_id,
952 "division_id": division_id,
953 }
954 team_response = self.client.table("teams").insert(team_data).execute()
956 if not team_response.data:
957 return None
959 created_team = team_response.data[0]
960 team_id = created_team["id"]
961 logger.info("Team record created", team_id=team_id, team_name=name)
963 # Add age group associations
964 for age_group_id in age_group_ids:
965 data = {
966 "team_id": team_id,
967 "age_group_id": age_group_id,
968 "division_id": division_id,
969 }
970 self.client.table("team_mappings").insert(data).execute()
972 # Add game type participations
973 if match_type_ids:
974 for match_type_id in match_type_ids:
975 for age_group_id in age_group_ids:
976 match_type_data = {
977 "team_id": team_id,
978 "match_type_id": match_type_id,
979 "age_group_id": age_group_id,
980 "is_active": True,
981 }
982 self.client.table("team_match_types").insert(match_type_data).execute()
984 logger.info(
985 "Team creation completed",
986 team_id=team_id,
987 team_name=name,
988 age_groups=len(age_group_ids),
989 match_types=len(match_type_ids) if match_type_ids else 0,
990 )
991 return created_team
993 @invalidates_cache(TEAMS_CACHE_PATTERN)
994 def update_team(
995 self,
996 team_id: int,
997 name: str,
998 city: str,
999 academy_team: bool = False,
1000 club_id: int | None = None,
1001 ) -> dict | None:
1002 """Update a team."""
1003 update_data = {
1004 "name": name,
1005 "city": city,
1006 "academy_team": academy_team,
1007 "club_id": club_id,
1008 }
1009 logger.debug("DAO update_team", team_id=team_id, update_data=update_data)
1011 result = self.client.table("teams").update(update_data).eq("id", team_id).execute()
1013 return result.data[0] if result.data else None
1015 @invalidates_cache(TEAMS_CACHE_PATTERN)
1016 def delete_team(self, team_id: int) -> bool:
1017 """Delete a team and its related data.
1019 Cascades deletion of:
1020 - team_mappings (FK constraint)
1021 - team_match_types (FK constraint)
1022 - matches where team is home or away (FK constraint)
1023 """
1024 # Delete team_mappings first (FK constraint)
1025 self.client.table("team_mappings").delete().eq("team_id", team_id).execute()
1027 # Delete team_match_types (FK constraint)
1028 self.client.table("team_match_types").delete().eq("team_id", team_id).execute()
1030 # Delete matches where this team participates (FK constraint)
1031 self.client.table("matches").delete().eq("home_team_id", team_id).execute()
1032 self.client.table("matches").delete().eq("away_team_id", team_id).execute()
1034 # Now delete the team
1035 result = self.client.table("teams").delete().eq("id", team_id).execute()
1036 return len(result.data) > 0
1038 # === Team Mapping Methods ===
1040 @invalidates_cache(TEAMS_CACHE_PATTERN)
1041 def update_team_division(self, team_id: int, age_group_id: int, division_id: int) -> bool:
1042 """Update the division for a team in a specific age group."""
1043 response = (
1044 self.client.table("team_mappings")
1045 .update({"division_id": division_id})
1046 .eq("team_id", team_id)
1047 .eq("age_group_id", age_group_id)
1048 .execute()
1049 )
1050 return bool(response.data)
1052 @invalidates_cache(TEAMS_CACHE_PATTERN)
1053 def ensure_team_mapping(self, team_id: int, age_group_id: int, division_id: int) -> bool:
1054 """Register a team in an age group and division if it is not already.
1056 Idempotent, and deliberately narrower than create_team_mapping: it
1057 writes the team_mappings row and nothing else. The ingest path calls
1058 this per match, and create_team_mapping also rewrites
1059 teams.league_id/division_id — which SB-835 showed cannot represent a
1060 club that plays different divisions at different age groups, so having
1061 a match ingest churn them would make that worse.
1063 Returns True when a row was created.
1065 Never raises: a match landing matters more than its registration row,
1066 and this runs inside match ingest.
1067 """
1068 try:
1069 existing = (
1070 self.client.table("team_mappings")
1071 .select("id")
1072 .eq("team_id", team_id)
1073 .eq("age_group_id", age_group_id)
1074 .eq("division_id", division_id)
1075 .limit(1)
1076 .execute()
1077 )
1078 if existing.data: 1078 ↛ 1079line 1078 didn't jump to line 1079 because the condition on line 1078 was never true
1079 return False
1081 self.client.table("team_mappings").insert(
1082 {"team_id": team_id, "age_group_id": age_group_id, "division_id": division_id}
1083 ).execute()
1084 return True
1085 except Exception:
1086 logger.exception(
1087 "Could not ensure team mapping",
1088 team_id=team_id,
1089 age_group_id=age_group_id,
1090 division_id=division_id,
1091 )
1092 return False
1094 @invalidates_cache(TEAMS_CACHE_PATTERN)
1095 def create_team_mapping(self, team_id: int, age_group_id: int, division_id: int) -> dict:
1096 """Create a team mapping, update team's league_id, and enable League match participation.
1098 When assigning a team to a division (which belongs to a league), this method:
1099 1. Updates the team's league_id to match the division's league
1100 2. Creates the team_mapping entry
1101 3. Auto-creates a team_match_types entry for League matches (match_type_id=1)
1102 """
1103 # Get the league_id from the division
1104 division_response = self.client.table("divisions").select("league_id").eq("id", division_id).execute()
1105 if division_response.data:
1106 league_id = division_response.data[0]["league_id"]
1107 self.client.table("teams").update(
1108 {
1109 "league_id": league_id,
1110 "division_id": division_id,
1111 }
1112 ).eq("id", team_id).execute()
1114 # Create the team mapping
1115 result = (
1116 self.client.table("team_mappings")
1117 .insert(
1118 {
1119 "team_id": team_id,
1120 "age_group_id": age_group_id,
1121 "division_id": division_id,
1122 }
1123 )
1124 .execute()
1125 )
1127 # Auto-create team_match_types entry for League matches
1128 LEAGUE_MATCH_TYPE_ID = 1
1129 existing = (
1130 self.client.table("team_match_types")
1131 .select("id")
1132 .eq("team_id", team_id)
1133 .eq("match_type_id", LEAGUE_MATCH_TYPE_ID)
1134 .eq("age_group_id", age_group_id)
1135 .execute()
1136 )
1137 if not existing.data:
1138 self.client.table("team_match_types").insert(
1139 {
1140 "team_id": team_id,
1141 "match_type_id": LEAGUE_MATCH_TYPE_ID,
1142 "age_group_id": age_group_id,
1143 "is_active": True,
1144 }
1145 ).execute()
1146 logger.info(
1147 "Auto-created team_match_types entry for League",
1148 team_id=team_id,
1149 age_group_id=age_group_id,
1150 )
1152 return result.data[0]
1154 @invalidates_cache(TEAMS_CACHE_PATTERN)
1155 def delete_team_mapping(self, team_id: int, age_group_id: int, division_id: int) -> bool:
1156 """Delete a team mapping."""
1157 result = (
1158 self.client.table("team_mappings")
1159 .delete()
1160 .eq("team_id", team_id)
1161 .eq("age_group_id", age_group_id)
1162 .eq("division_id", division_id)
1163 .execute()
1164 )
1165 return len(result.data) > 0
1167 @invalidates_cache(TEAMS_CACHE_PATTERN)
1168 def update_team_club(self, team_id: int, club_id: int | None) -> dict:
1169 """Update the club for a team.
1171 Args:
1172 team_id: The team ID to update
1173 club_id: The club ID to assign (or None to remove club association)
1175 Returns:
1176 Updated team dict
1177 """
1178 result = self.client.table("teams").update({"club_id": club_id}).eq("id", team_id).execute()
1179 if not result.data or len(result.data) == 0:
1180 raise ValueError(f"Failed to update club for team {team_id}")
1181 return result.data[0]
1183 # === Team Match Type Participation Methods ===
1185 def get_team_match_type_participation(self, team_id: int) -> list[dict]:
1186 """Get a team's active per-age-group match-type participation rows.
1188 Returns [{match_type_id, age_group_id}] for rows with is_active=True.
1189 Used by the admin per-age participation matrix to render current state.
1190 """
1191 response = (
1192 self.client.table("team_match_types")
1193 .select("match_type_id, age_group_id")
1194 .eq("team_id", team_id)
1195 .eq("is_active", True)
1196 .execute()
1197 )
1198 return response.data
1200 def add_team_match_type_participation(self, team_id: int, match_type_id: int, age_group_id: int) -> bool:
1201 """Add (or reactivate) a team's participation in a match type + age group.
1203 remove_team_match_type_participation soft-deletes (is_active=False), so a
1204 prior removal leaves a row that a blind insert would collide with on the
1205 (team, match_type, age_group) unique key. Reactivate it when present;
1206 otherwise insert a fresh row.
1207 """
1208 try:
1209 existing = (
1210 self.client.table("team_match_types")
1211 .select("id")
1212 .eq("team_id", team_id)
1213 .eq("match_type_id", match_type_id)
1214 .eq("age_group_id", age_group_id)
1215 .execute()
1216 )
1217 if existing.data:
1218 self.client.table("team_match_types").update({"is_active": True}).eq(
1219 "id", existing.data[0]["id"]
1220 ).execute()
1221 else:
1222 self.client.table("team_match_types").insert(
1223 {
1224 "team_id": team_id,
1225 "match_type_id": match_type_id,
1226 "age_group_id": age_group_id,
1227 "is_active": True,
1228 }
1229 ).execute()
1230 return True
1231 except Exception:
1232 logger.exception("Error adding team match type participation")
1233 return False
1235 def remove_team_match_type_participation(self, team_id: int, match_type_id: int, age_group_id: int) -> bool:
1236 """Remove a team's participation in a specific match type and age group."""
1237 try:
1238 self.client.table("team_match_types").update({"is_active": False}).eq("team_id", team_id).eq(
1239 "match_type_id", match_type_id
1240 ).eq("age_group_id", age_group_id).execute()
1241 return True
1242 except Exception:
1243 logger.exception("Error removing team match type participation")
1244 return False
1246 # === Other Query Methods (not cached) ===
1248 def get_teams_by_club_ids(self, club_ids: list[int]) -> list[dict]:
1249 """Get teams for multiple clubs without match/player counts.
1251 This is optimized for admin club listings that only need team details.
1252 """
1253 if not club_ids:
1254 return []
1256 response = (
1257 self.client.table("teams_with_league_badges")
1258 .select("id,name,club_id,league_id,league_name,mapping_league_names")
1259 .in_("club_id", club_ids)
1260 .order("name")
1261 .execute()
1262 )
1264 return [{**team} for team in response.data]
1266 def get_club_for_team(self, team_id: int) -> dict | None:
1267 """Get the club for a team.
1269 Args:
1270 team_id: The team ID
1272 Returns:
1273 Club dict if team belongs to a club, None otherwise
1274 """
1275 team_response = self.client.table("teams").select("club_id").eq("id", team_id).execute()
1276 if not team_response.data or len(team_response.data) == 0:
1277 return None
1279 club_id = team_response.data[0].get("club_id")
1280 if not club_id:
1281 return None
1283 club_response = self.client.table("clubs").select("*").eq("id", club_id).execute()
1284 if club_response.data and len(club_response.data) > 0:
1285 return club_response.data[0]
1286 return None
1288 def get_team_game_counts(self, include_test: bool = False) -> dict[int, int]:
1289 """Get game counts for all teams in a single optimized query.
1291 Returns a dictionary mapping team_id -> game_count.
1293 include_test gates the SB-591 test partition. The RPC applies the same
1294 rule server-side; the Python fallback below mirrors it.
1295 """
1296 try:
1297 response = self.client.rpc("get_team_game_counts", {"p_include_test": include_test}).execute()
1299 if not response.data:
1300 # Fallback to Python aggregation
1301 fallback = self.client.table(MATCHES_READ_RELATION).select("home_team_id,away_team_id")
1302 if not include_test:
1303 fallback = fallback.eq("is_test", False)
1304 matches = fallback.execute()
1305 counts: dict[int, int] = {}
1306 for match in matches.data:
1307 home_id = match["home_team_id"]
1308 away_id = match["away_team_id"]
1309 counts[home_id] = counts.get(home_id, 0) + 1
1310 counts[away_id] = counts.get(away_id, 0) + 1
1311 return counts
1313 return {row["team_id"]: row["game_count"] for row in response.data}
1314 except Exception:
1315 logger.exception("Error getting team game counts")
1316 return {}