Coverage for dao/match_dao.py: 55.81%
835 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""
2Match data access layer for MissingTable.
4Provides data access objects for matches, teams, leagues, divisions, seasons,
5and related soccer/futbol data using Supabase.
6"""
8import os
9from datetime import UTC, datetime, timedelta
11import httpx
12import structlog
13from dotenv import load_dotenv
14from postgrest.exceptions import APIError
16from dao.base_dao import (
17 MATCHES_READ_RELATION,
18 BaseDAO,
19 clear_cache,
20 dao_cache,
21 invalidates_cache,
22)
23from dao.exceptions import DuplicateRecordError
24from dao.side_age_groups import side_age_group, team_age_group_filter
25from dao.standings import (
26 calculate_standings_with_extras,
27 count_outside_table_opponents,
28 filter_by_match_types,
29 filter_completed_matches,
30 filter_matches_in_division,
31 filter_matches_involving,
32 shootout_competitions,
33 teams_in_division,
34)
35from supabase import create_client
37logger = structlog.get_logger()
39# Cache patterns for invalidation
40MATCHES_CACHE_PATTERN = "mt:dao:matches:*"
43class _Unset:
44 """A field the caller never mentioned, as distinct from one set to null.
46 PATCH has to tell "leave the shootout alone" apart from "there was no
47 shootout after all", and None cannot carry both meanings (SB-913).
48 """
50 def __repr__(self) -> str: # pragma: no cover - debugging aid
51 return "UNSET"
53 def __bool__(self) -> bool:
54 return False
57UNSET = _Unset()
58PLAYOFF_CACHE_PATTERN = "mt:dao:playoffs:*"
59TOURNAMENTS_CACHE_PATTERN = "mt:dao:tournaments:*"
61# Values `match_type` accepts beyond a competition name.
62#
63# QUALIFYING is the union of the types flagged counts_for_qualification, read
64# from the data rather than named here — the whole point of SB-849 is that the
65# Matches chips, `mt team matches -c` and this table cannot disagree about what
66# qualifies. ALL is every competition, friendlies and tournaments included,
67# which is a different and much less useful question.
68STANDINGS_QUALIFYING = "qualifying"
69STANDINGS_ALL = "all"
71# PostgREST's "could not find the column in the schema cache": a column the
72# code writes has not been migrated into this database yet. `migrate prod` is
73# run by hand, and the ingest worker is rebuilt by hand, each on its own
74# schedule, so for matches.location (SB-1874) the ingest writes the match
75# without it rather than losing it.
76_COLUMN_NOT_FOUND = "PGRST204"
79def _location_not_migrated(error: APIError) -> bool:
80 """Whether a write failed only because matches.location does not exist yet."""
81 return error.code == _COLUMN_NOT_FOUND and "location" in str(error.message or "")
84def qualifying_match_type_ids(match_types: list[dict]) -> list[int] | None:
85 """The competitions flagged counts_for_qualification (League, Flex). None = all.
87 Read from the flag rather than named here, so every surface agrees on what
88 qualifies (SB-849). No flagged type at all means the lookup failed or the
89 data is unset; filtering on an empty list would blank the preview, so that
90 falls back to every competition instead.
91 """
92 return [t["id"] for t in match_types if t.get("counts_for_qualification")] or None
95def form_match_type_ids(match_types: list[dict], match_type_id: int | None) -> list[int] | None:
96 """Which competitions a match preview's recent form draws from. None = all.
98 A League or Flex match is previewed against League and Flex form only:
99 a tournament result says little about the competition at stake (SB-1346).
100 Any other match — a tournament, a friendly, or no type at all — keeps
101 every result.
102 """
103 qualifying = qualifying_match_type_ids(match_types)
104 if qualifying is None or match_type_id not in qualifying: 104 ↛ 106line 104 didn't jump to line 106 because the condition on line 104 was always true
105 return None
106 return qualifying
109def _birth_year_from_labels(age_group_name: str | None, season_name: str | None) -> int | None:
110 """Derive a squad's birth year from its age group + season.
112 Formula: season_end_year - age_number. For example, a U14 squad in
113 the "2025-2026" season has birth year 2026 - 14 = 2012. The same
114 cohort the prior year (U13 in "2024-2025") yields 2025 - 13 = 2012,
115 so the comparison correctly tracks the squad as it ages up.
116 """
117 try:
118 age_num = int(age_group_name.lstrip("Uu"))
119 end_year = int(season_name.split("-")[-1])
120 except (AttributeError, ValueError, TypeError, IndexError):
121 return None
122 return end_year - age_num
125# Load environment variables with environment-specific support
126def load_environment():
127 """Load environment variables based on APP_ENV or default to local."""
128 # First load base .env file
129 load_dotenv()
131 # Determine which environment to use
132 app_env = os.getenv("APP_ENV", "local") # Default to local
134 # Load environment-specific file
135 env_file = f".env.{app_env}"
136 if os.path.exists(env_file): 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true
137 load_dotenv(env_file, override=False)
138 else:
139 # Fallback to .env.local for backwards compatibility
140 if os.path.exists(".env.local"): 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true
141 load_dotenv(".env.local", override=False)
144class SupabaseConnection:
145 """Manage the connection to Supabase with SSL workaround."""
147 def __init__(self):
148 """Initialize Supabase client with custom SSL configuration."""
149 load_environment()
150 self.url = os.getenv("SUPABASE_URL")
151 # Backend should always use SERVICE_KEY for administrative operations
152 service_key = os.getenv("SUPABASE_SERVICE_KEY")
153 anon_key = os.getenv("SUPABASE_ANON_KEY")
154 self.key = service_key or anon_key
156 if not self.url or not self.key: 156 ↛ 157line 156 didn't jump to line 157 because the condition on line 156 was never true
157 raise ValueError("SUPABASE_URL and SUPABASE_ANON_KEY (or SUPABASE_SERVICE_KEY) must be set in .env file")
159 # Debug output - check what keys are actually set
160 key_type = "SERVICE_KEY" if service_key and self.key == service_key else "ANON_KEY"
161 logger.info(f"DEBUG SupabaseConnection: key_type={key_type}, service_key_present={bool(service_key)}")
163 try:
164 # Try with custom httpx client
165 transport = httpx.HTTPTransport(retries=3)
166 timeout = httpx.Timeout(30.0, connect=10.0)
168 # Create custom client with extended timeout and retries
169 http_client = httpx.Client(transport=transport, timeout=timeout, follow_redirects=True)
171 # Create Supabase client with custom HTTP client
172 self.client = create_client(self.url, self.key, options={"httpx_client": http_client})
173 logger.debug("Connection to Supabase established")
175 except Exception:
176 # Fallback to standard client
177 self.client = create_client(self.url, self.key)
178 logger.debug("Connection to Supabase established (fallback client)")
180 def get_client(self):
181 """Get the Supabase client instance."""
182 return self.client
185# How long after kick-off a result is expected to be published. A youth match
186# plus stoppage, admin, and someone actually entering the score: three hours is
187# late enough not to ask before anyone could have answered, early enough that a
188# midday match is chased the same afternoon (SB-1058).
189SCORE_GRACE = timedelta(hours=3)
191# How far ahead a missing kick-off time is worth chasing. Beyond this the
192# fixture is too far out for a missing time to mean anything is wrong.
193KICKOFF_HORIZON_DAYS = 14
196# The matches.source values the scraper writes. The live sender is
197# match-scraper-agent; match-scraper is the older one and the default for a
198# message that names none. A row with any other source was entered by a person
199# (SB-1747, SB-1787).
200FEED_SOURCES = frozenset({"match-scraper", "match-scraper-agent"})
202# PostgREST caps a response at max_rows (1000); a season read pages under it.
203_SEASON_PAGE = 1000
205# Rows per page of GET /api/agent/season-matches (SB-1787): the default, and the
206# most a caller may ask for — one PostgREST response at most.
207AGENT_SEASON_PAGE = 500
208AGENT_SEASON_PAGE_MAX = _SEASON_PAGE
210# What the reconcile reads of each match. Explicit rather than `*`: nothing
211# that names a user leaves this method.
212_AGENT_SEASON_COLUMNS = (
213 "id, match_id, match_date, match_status, home_team_id, away_team_id, "
214 "home_score, away_score, home_penalty_score, away_penalty_score, "
215 "division_id, source, score_locked, "
216 "home_team:teams!matches_home_team_id_fkey(name), "
217 "away_team:teams!matches_away_team_id_fkey(name), "
218 "match_type:match_types(name)"
219)
222def _age_group_or_side(age_group_id: int) -> str:
223 """PostgREST `or`: the match, or either side of it, is at the age group."""
224 a = int(age_group_id)
225 return f"age_group_id.eq.{a},home_age_group_id.eq.{a},away_age_group_id.eq.{a}"
228def _flatten_match(match: dict) -> dict:
229 """A match row with its embeds, as the flat dict get_all_matches returns."""
230 return {
231 "id": match["id"],
232 "match_date": match["match_date"],
233 "scheduled_kickoff": match.get("scheduled_kickoff"),
234 "home_team_id": match["home_team_id"],
235 "away_team_id": match["away_team_id"],
236 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
237 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
238 "home_team_club": match["home_team"].get("club") if match.get("home_team") else None,
239 "away_team_club": match["away_team"].get("club") if match.get("away_team") else None,
240 "home_score": match["home_score"],
241 "away_score": match["away_score"],
242 # A Flex draw is decided on penalties, and the pair is stored;
243 # leaving it out of the flatten is why the page showed a draw
244 # and why the ingest re-wrote it every run (SB-1026).
245 "home_penalty_score": match.get("home_penalty_score"),
246 "away_penalty_score": match.get("away_penalty_score"),
247 "season_id": match["season_id"],
248 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
249 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
250 "age_group_id": match["age_group_id"],
251 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
252 "home_age_group_id": match.get("home_age_group_id"),
253 "away_age_group_id": match.get("away_age_group_id"),
254 "match_type_id": match["match_type_id"],
255 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
256 "division_id": match.get("division_id"),
257 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
258 "league_id": match["division"]["league_id"] if match.get("division") else None,
259 "league_name": match["division"]["leagues"]["name"]
260 if match.get("division") and match["division"].get("leagues")
261 else "Unknown",
262 "division": match.get("division"), # Include full division object with leagues
263 "match_status": match.get("match_status"),
264 "scoring_mode": match.get("scoring_mode", "manual"),
265 "created_by": match.get("created_by"),
266 "updated_by": match.get("updated_by"),
267 "source": match.get("source", "manual"),
268 "match_id": match.get("match_id"), # External match identifier
269 "created_at": match["created_at"],
270 "updated_at": match["updated_at"],
271 }
274class MatchDAO(BaseDAO):
275 """Data Access Object for match and league data using normalized schema."""
277 # === Core Match Methods ===
279 def get_match_by_external_id(self, external_match_id: str) -> dict | None:
280 """Get a match by its external match_id (from match-scraper).
282 This is used for deduplication - checking if a match from match-scraper
283 already exists in the database.
285 Returns:
286 Match dict with flattened structure, or None if not found
287 """
288 try:
289 response = (
290 self.client.table("matches")
291 .select("""
292 *,
293 home_team:teams!matches_home_team_id_fkey(id, name),
294 away_team:teams!matches_away_team_id_fkey(id, name),
295 season:seasons(id, name, start_date),
296 age_group:age_groups(id, name),
297 match_type:match_types(id, name),
298 division:divisions(id, name)
299 """)
300 .eq("match_id", external_match_id)
301 .limit(1)
302 .execute()
303 )
305 if response.data and len(response.data) > 0: 305 ↛ 358line 305 didn't jump to line 358 because the condition on line 305 was always true
306 match = response.data[0]
307 # Flatten to match format from get_match_by_id
308 flat_match = {
309 "id": match["id"],
310 "match_date": match["match_date"],
311 "scheduled_kickoff": match.get("scheduled_kickoff"),
312 "home_team_id": match["home_team_id"],
313 "away_team_id": match["away_team_id"],
314 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
315 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
316 "home_score": match["home_score"],
317 "away_score": match["away_score"],
318 # A Flex draw is decided on penalties, and the pair is stored;
319 # leaving it out of the flatten is why the page showed a draw
320 # and why the ingest re-wrote it every run (SB-1026).
321 "home_penalty_score": match.get("home_penalty_score"),
322 "away_penalty_score": match.get("away_penalty_score"),
323 "season_id": match["season_id"],
324 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
325 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
326 "age_group_id": match["age_group_id"],
327 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
328 "home_age_group_id": match.get("home_age_group_id"),
329 "away_age_group_id": match.get("away_age_group_id"),
330 "match_type_id": match["match_type_id"],
331 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
332 "division_id": match.get("division_id"),
333 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
334 "match_status": match.get("match_status"),
335 "scoring_mode": match.get("scoring_mode", "manual"),
336 "created_by": match.get("created_by"),
337 "updated_by": match.get("updated_by"),
338 "source": match.get("source", "manual"),
339 "match_id": match.get("match_id"),
340 # A person locked the score; the ingest holds the feed's
341 # score and status for it (SB-1787).
342 "score_locked": bool(match.get("score_locked")),
343 # Tournament filing. Left out, an unchanged tournament
344 # rescrape reads as changed and is re-written every run
345 # (SB-1747) — the same trap as the shootout above.
346 "tournament_id": match.get("tournament_id"),
347 "tournament_group": match.get("tournament_group"),
348 "tournament_round": match.get("tournament_round"),
349 "tournament_round_order": match.get("tournament_round_order"),
350 "created_at": match["created_at"],
351 "updated_at": match["updated_at"],
352 }
353 # Only when the column exists: the ingest reads an absent key
354 # as "not migrated here" and leaves location alone (SB-1874).
355 if "location" in match:
356 flat_match["location"] = match["location"]
357 return flat_match
358 return None
360 except Exception:
361 logger.exception("Error getting match by external ID", external_match_id=external_match_id)
362 return None
364 def get_match_by_teams_and_date(
365 self, home_team_id: int, away_team_id: int, match_date: str, age_group_id: int | None = None
366 ) -> dict | None:
367 """Get a match by home/away teams, date, and optionally age group.
369 This is used as a fallback for deduplication when match_id is not populated
370 (e.g., manually-entered matches without external match IDs).
372 Args:
373 home_team_id: Database ID of home team
374 away_team_id: Database ID of away team
375 match_date: ISO format date string (YYYY-MM-DD)
376 age_group_id: Optional database ID of age group (recommended to avoid false matches)
378 Returns:
379 Match dict with flattened structure, or None if not found
380 """
381 try:
382 query = (
383 self.client.table("matches")
384 .select("""
385 *,
386 home_team:teams!matches_home_team_id_fkey(id, name),
387 away_team:teams!matches_away_team_id_fkey(id, name),
388 season:seasons(id, name, start_date),
389 age_group:age_groups(id, name),
390 match_type:match_types(id, name),
391 division:divisions(id, name)
392 """)
393 .eq("home_team_id", home_team_id)
394 .eq("away_team_id", away_team_id)
395 .eq("match_date", match_date)
396 )
398 # Add age_group filter if provided (prevents matching different age groups)
399 if age_group_id is not None: 399 ↛ 400line 399 didn't jump to line 400 because the condition on line 399 was never true
400 query = query.eq("age_group_id", age_group_id)
402 response = query.limit(1).execute()
404 if response.data and len(response.data) > 0: 404 ↛ 457line 404 didn't jump to line 457 because the condition on line 404 was always true
405 match = response.data[0]
406 # Flatten to match format from get_match_by_id
407 flat_match = {
408 "id": match["id"],
409 "match_date": match["match_date"],
410 "scheduled_kickoff": match.get("scheduled_kickoff"),
411 "home_team_id": match["home_team_id"],
412 "away_team_id": match["away_team_id"],
413 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
414 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
415 "home_score": match["home_score"],
416 "away_score": match["away_score"],
417 # A Flex draw is decided on penalties, and the pair is stored;
418 # leaving it out of the flatten is why the page showed a draw
419 # and why the ingest re-wrote it every run (SB-1026).
420 "home_penalty_score": match.get("home_penalty_score"),
421 "away_penalty_score": match.get("away_penalty_score"),
422 "season_id": match["season_id"],
423 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
424 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
425 "age_group_id": match["age_group_id"],
426 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
427 "home_age_group_id": match.get("home_age_group_id"),
428 "away_age_group_id": match.get("away_age_group_id"),
429 "match_type_id": match["match_type_id"],
430 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
431 "division_id": match.get("division_id"),
432 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
433 "match_status": match.get("match_status"),
434 "scoring_mode": match.get("scoring_mode", "manual"),
435 "created_by": match.get("created_by"),
436 "updated_by": match.get("updated_by"),
437 "source": match.get("source", "manual"),
438 "match_id": match.get("match_id"),
439 # A person locked the score; the ingest holds the feed's
440 # score and status for it (SB-1787).
441 "score_locked": bool(match.get("score_locked")),
442 # Tournament filing. Left out, an unchanged tournament
443 # rescrape reads as changed and is re-written every run
444 # (SB-1747) — the same trap as the shootout above.
445 "tournament_id": match.get("tournament_id"),
446 "tournament_group": match.get("tournament_group"),
447 "tournament_round": match.get("tournament_round"),
448 "tournament_round_order": match.get("tournament_round_order"),
449 "created_at": match["created_at"],
450 "updated_at": match["updated_at"],
451 }
452 # Only when the column exists: the ingest reads an absent key
453 # as "not migrated here" and leaves location alone (SB-1874).
454 if "location" in match: 454 ↛ 456line 454 didn't jump to line 456 because the condition on line 454 was always true
455 flat_match["location"] = match["location"]
456 return flat_match
457 return None
459 except Exception:
460 logger.exception("Error getting match by teams and date")
461 return None
463 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
464 def update_match_external_id(self, match_id: int, external_match_id: str) -> bool:
465 """Update only the external match_id field on an existing match.
467 This is used when a manually-entered match is matched with a scraped match,
468 allowing future scrapes to use the external_match_id for deduplication.
470 Args:
471 match_id: Database ID of the match to update
472 external_match_id: External match ID from match-scraper (e.g., "98966")
474 Returns:
475 True if update successful, False otherwise
476 """
477 try:
478 response = (
479 self.client.table("matches")
480 .update(
481 {
482 "match_id": external_match_id,
483 "source": "match-scraper", # Update source to indicate scraper now manages this
484 }
485 )
486 .eq("id", match_id)
487 .execute()
488 )
490 if response.data: 490 ↛ 497line 490 didn't jump to line 497 because the condition on line 490 was always true
491 logger.info(
492 "Updated match with external match_id",
493 match_id=match_id,
494 external_match_id=external_match_id,
495 )
496 return True
497 return False
499 except Exception:
500 logger.exception("Error updating match external_id")
501 return False
503 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
504 def create_match(
505 self,
506 home_team_id: int,
507 away_team_id: int,
508 match_date: str,
509 season_id: int,
510 home_score: int | None = None,
511 away_score: int | None = None,
512 match_status: str = "scheduled",
513 source: str = "manual",
514 match_id: str | None = None,
515 age_group_id: int = 1,
516 division_id: int | None = None,
517 match_type_id: int | None = None,
518 scheduled_kickoff: str | None = None,
519 home_penalty_score: int | None = None,
520 away_penalty_score: int | None = None,
521 tournament_id: int | None = None,
522 tournament_group: str | None = None,
523 tournament_round: str | None = None,
524 tournament_round_order: int | None = None,
525 location: str | None = None,
526 ) -> int | None:
527 """Create a new match with pre-resolved IDs.
529 Callers are responsible for resolving names to IDs before calling this
530 method. The Celery task and API layer both do this already.
532 Args:
533 home_team_id: Database ID of home team
534 away_team_id: Database ID of away team
535 match_date: ISO format date string
536 season_id: Database ID of season
537 home_score: Home team score (optional)
538 away_score: Away team score (optional)
539 match_status: Match status (scheduled, live, completed, etc.)
540 source: Data source (default: "manual", use "match-scraper" for external)
541 match_id: External match ID for deduplication (optional)
542 age_group_id: Database ID of age group (default: 1)
543 division_id: Database ID of division (optional)
544 match_type_id: Database ID of competition. Defaults to League when
545 the caller does not know — but a caller reading a feed does
546 know, and passing None used to be the only option: this method
547 hardcoded League, which is how 68 Flex fixtures were created as
548 League matches (SB-846/SB-847).
549 home_penalty_score: Home shootout score, when a level match went to
550 penalties. MLS NEXT Flex fixtures cannot end level (SB-1020).
551 away_penalty_score: Away shootout score, same conditions.
552 tournament_id: The tournament this match belongs to. A tournament
553 match is filed on the tournament and has no division (SB-1747).
554 tournament_group: The stored group value, already composed by
555 dao.tournament_groups.compose_group — never a raw feed label.
556 tournament_round: Round key (e.g. "group_stage").
557 tournament_round_order: Position within the round.
558 location: Venue and pitch as the feed sends it (SB-1874). Dropped,
559 with a warning, on a database the column has not reached yet.
561 Returns:
562 Created match ID, or None on failure
563 """
564 try:
565 # Validate division for match-scraper sourced matches. A tournament
566 # match is the exception: it is filed on the tournament instead.
567 if source == "match-scraper" and division_id is None and tournament_id is None: 567 ↛ 568line 567 didn't jump to line 568 because the condition on line 567 was never true
568 logger.error("Division is required for match-scraper sourced matches but was not provided")
569 raise ValueError("Division is required for match-scraper sourced matches")
571 # League when unstated. Every caller that reads a competition from
572 # a feed should pass one; the default is for manual creation paths
573 # that have no competition to read.
574 match_type_id = match_type_id or 1
576 data = {
577 "match_date": match_date,
578 "home_team_id": home_team_id,
579 "away_team_id": away_team_id,
580 "home_score": home_score,
581 "away_score": away_score,
582 "season_id": season_id,
583 "age_group_id": age_group_id,
584 "match_type_id": match_type_id,
585 "division_id": division_id,
586 "match_status": match_status,
587 "source": source,
588 }
590 if match_id: 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true
591 data["match_id"] = match_id
592 if scheduled_kickoff: 592 ↛ 593line 592 didn't jump to line 593 because the condition on line 592 was never true
593 data["scheduled_kickoff"] = scheduled_kickoff
594 # Both or neither, and only on a level score — the two CHECK
595 # constraints from 20260329000000_add_penalty_shootout_scores.sql.
596 # Sending one alone, or either on a decided match, fails the insert
597 # and loses the whole fixture rather than just the shootout.
598 if home_penalty_score is not None and away_penalty_score is not None: 598 ↛ 599line 598 didn't jump to line 599 because the condition on line 598 was never true
599 data["home_penalty_score"] = home_penalty_score
600 data["away_penalty_score"] = away_penalty_score
601 if tournament_id is not None: 601 ↛ 602line 601 didn't jump to line 602 because the condition on line 601 was never true
602 data["tournament_id"] = tournament_id
603 if tournament_group is not None:
604 data["tournament_group"] = tournament_group
605 if tournament_round is not None:
606 data["tournament_round"] = tournament_round
607 if tournament_round_order is not None:
608 data["tournament_round_order"] = tournament_round_order
609 if location:
610 data["location"] = location
612 try:
613 response = self.client.table("matches").insert(data).execute()
614 except APIError as e:
615 if "location" not in data or not _location_not_migrated(e):
616 raise
617 logger.warning("matches.location is not migrated here; creating the match without it")
618 data.pop("location")
619 response = self.client.table("matches").insert(data).execute()
621 if response.data and len(response.data) > 0: 621 ↛ 623line 621 didn't jump to line 623 because the condition on line 621 was always true
622 return response.data[0]["id"]
623 return None
625 except Exception:
626 logger.exception("Error creating match")
627 return None
629 def tournament_exists(self, tournament_id: int) -> bool:
630 """Whether a tournaments row with this id exists.
632 Asked by ingest before filing a match on a tournament (SB-1747): the
633 foreign key would reject an unknown id anyway, but as a failed insert
634 that is retried three times and then lost in a worker log.
636 Raises on a database error — "could not look" must not be recorded as
637 "no such tournament".
638 """
639 response = self.client.table("tournaments").select("id").eq("id", tournament_id).limit(1).execute()
640 return bool(response.data)
642 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
643 def update_ingested_tournament_match(self, match_id: int, updates: dict) -> bool:
644 """Write an ingest update to a match that is on a tournament.
646 The ingest task writes league updates straight to the table. A
647 tournament match goes through here so that, in a process sharing the
648 API's cache, the tournament reads are cleared with the write (SB-1747).
650 Returns whether a row was written. Raises on a database error; the
651 cache is only cleared when the write did not raise.
653 The clear only happens in a process that shares the API's cache
654 (CACHE_ENABLED=true and a reachable REDIS_URL). The ingest worker
655 has neither and cannot clear the API's cache, so there this is a
656 plain write. The tournament page is then stale for about a minute at
657 most: the tournament reads expire on a short TTL
658 (TOURNAMENT_SCORE_CACHE_TTL in tournament_dao, SB-1756).
659 """
660 response = self.client.table("matches").update(updates).eq("id", match_id).execute()
661 return bool(response.data)
663 # === Match Methods ===
665 def get_all_matches(
666 self,
667 season_id: int | None = None,
668 age_group_id: int | None = None,
669 division_id: int | None = None,
670 team_id: int | None = None,
671 match_type: str | None = None,
672 start_date: str | None = None,
673 end_date: str | None = None,
674 include_test: bool = False,
675 *,
676 raise_on_error: bool = False,
677 ) -> list[dict]:
678 """Get all matches with optional filters.
680 Args:
681 season_id: Filter by season ID
682 age_group_id: Filter by age group ID
683 division_id: Filter by division ID
684 team_id: Filter by team ID (home or away)
685 match_type: Filter by match type name
686 start_date: Filter by start date (YYYY-MM-DD)
687 end_date: Filter by end date (YYYY-MM-DD)
688 include_test: SB-591 test partition. Real/anonymous viewers pass
689 False (test matches hidden); admins + test users pass True.
690 raise_on_error: Re-raise query failures instead of returning [].
691 The default keeps the endpoints' behaviour; MT AI tools pass True
692 so a failed read is not mistaken for "no matches" (SB-1142).
693 """
694 try:
695 query = self.client.table(MATCHES_READ_RELATION).select("""
696 *,
697 home_team:teams!matches_home_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
698 away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
699 season:seasons(id, name, start_date),
700 age_group:age_groups(id, name),
701 match_type:match_types(id, name),
702 division:divisions(id, name, league_id, leagues!divisions_league_id_fkey(id, name))
703 """)
705 # Apply filters
706 if not include_test:
707 query = query.eq("is_test", False)
708 if season_id:
709 query = query.eq("season_id", season_id)
710 # A team's matches at an age group follow the age group that team
711 # fielded, which differs from the match's when it played up (SB-1444).
712 if age_group_id and not team_id:
713 query = query.eq("age_group_id", age_group_id)
714 if division_id:
715 query = query.eq("division_id", division_id)
717 # Date range filters
718 if start_date:
719 query = query.gte("match_date", start_date)
720 if end_date:
721 query = query.lte("match_date", end_date)
723 # For team_id, we need to match either home_team_id OR away_team_id
724 if team_id and age_group_id:
725 query = query.or_(team_age_group_filter(team_id, age_group_id))
726 elif team_id:
727 query = query.or_(f"home_team_id.eq.{team_id},away_team_id.eq.{team_id}")
729 response = query.order("match_date", desc=True).execute()
731 # Filter by match_type name if specified (post-query filtering)
732 filtered_matches = response.data
733 if match_type:
734 filtered_matches = [
735 match for match in response.data if match.get("match_type", {}).get("name") == match_type
736 ]
738 # Flatten the response for easier use
739 return [_flatten_match(match) for match in filtered_matches]
741 except Exception:
742 logger.exception("Error querying matches")
743 if raise_on_error:
744 raise
745 return []
747 def get_season_results(
748 self,
749 season_id: int,
750 age_group_id: int,
751 league_ids: list[int] | tuple[int, ...],
752 match_type_ids: list[int] | tuple[int, ...],
753 statuses: tuple[str, ...] = ("completed", "forfeit"),
754 include_test: bool = False,
755 ) -> list[dict]:
756 """A season's results at one age group across whole leagues (SB-1781).
758 `get_all_matches` reads one response, and PostgREST caps a response at
759 max_rows (1000): a league-wide season is more than that, so this filters
760 in the database (league through the division embed, match type, status)
761 and pages with `.range()`. Rows are in `get_all_matches`' flat shape.
763 A match is read when it or either side is at the age group: a side that
764 played up into another age group's match keeps its own age (SB-1444), and
765 the caller decides per side (`effective_side_age_groups`).
767 Paging stops on an empty page, not a short one: a server whose max_rows is
768 below the page size returns short pages that are not the last.
770 Raises on a database error: "could not read" must not look like "no results".
771 """
772 rows: list[dict] = []
773 while True:
774 query = (
775 self.client.table(MATCHES_READ_RELATION)
776 .select("""
777 *,
778 home_team:teams!matches_home_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
779 away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
780 season:seasons(id, name, start_date),
781 age_group:age_groups(id, name),
782 match_type:match_types(id, name),
783 division:divisions!inner(id, name, league_id, leagues!divisions_league_id_fkey(id, name))
784 """)
785 .eq("season_id", season_id)
786 .or_(_age_group_or_side(age_group_id))
787 .in_("division.league_id", list(league_ids))
788 .in_("match_type_id", list(match_type_ids))
789 .in_("match_status", list(statuses))
790 )
791 if not include_test:
792 query = query.eq("is_test", False)
793 page = (
794 query.order("match_date").order("id").range(len(rows), len(rows) + _SEASON_PAGE - 1).execute()
795 ).data or []
796 if not page:
797 return [_flatten_match(match) for match in rows]
798 rows.extend(page)
800 def _season_id_by_name(self, season_name: str) -> int | None:
801 """Resolve a season name to its id, or None when unknown."""
802 response = self.client.table("seasons").select("id").eq("name", season_name).limit(1).execute()
803 return response.data[0]["id"] if response.data else None
805 def get_match_summary(
806 self,
807 season_name: str,
808 score_from: str | None = None,
809 score_to: str | None = None,
810 include_test: bool = False,
811 ) -> list[dict]:
812 """Get match summary statistics grouped by age group, league, and division.
814 Used by the match-scraper-agent to understand what MT already has
815 and make smart decisions about what to scrape.
817 Aggregated in the database (SB-1057). This used to read every
818 non-cancelled match in the season — 5,272 rows for 2026-2027, in six
819 paginated round trips — and count them in Python, which put the whole
820 season on the wire to produce 119 rows of counts and tripped Supabase's
821 gateway timeout on every cold call. The agent runs hours apart, so it was
822 always the cold caller: it lost four consecutive production runs to it on
823 2026-09-11/12.
825 A match counts toward needs_score once SCORE_GRACE has passed since its
826 kick-off rather than once the calendar day has ended (SB-1058). The grace
827 is passed to the function rather than defined there, so this module stays
828 the one place it is written down.
830 Args:
831 season_name: Season name, e.g. '2025-2026'.
832 score_from: If set, only count needs_score for matches >= this date.
833 score_to: If set, only count needs_score for matches <= this date.
834 include_test: SB-591 test partition. Defaults False so the scraper
835 agent's "what is missing" counts are not skewed by hand-created
836 test fixtures, which are never scraped.
837 """
838 from datetime import date
840 season_id = self._season_id_by_name(season_name)
841 if season_id is None:
842 return []
844 now = datetime.now(UTC)
845 response = self.client.rpc(
846 "agent_match_summary",
847 {
848 "p_season_id": season_id,
849 "p_now": now.isoformat(),
850 "p_today": date.today().isoformat(),
851 "p_score_from": score_from,
852 "p_score_to": score_to,
853 "p_score_grace": f"{SCORE_GRACE.total_seconds()} seconds",
854 "p_kickoff_horizon_days": KICKOFF_HORIZON_DAYS,
855 "p_include_test": include_test,
856 },
857 ).execute()
859 # Shape kept byte-identical to the Python implementation this replaced:
860 # the planner in match-scraper reads these keys, and the two ran
861 # side by side against the live season to prove they agree.
862 return [
863 {
864 "age_group": row["age_group"],
865 "league": row["league"],
866 "division": row["division"],
867 "total": row["total"],
868 "by_status": row["by_status"] or {},
869 "needs_score": row["needs_score"],
870 "needs_kickoff": row["needs_kickoff"],
871 "date_range": {
872 "earliest": row["earliest"],
873 "latest": row["latest"],
874 },
875 "last_played_date": row["last_played_date"],
876 }
877 for row in (response.data or [])
878 ]
880 def get_bootstrap_divisions(self, season_name: str, include_test: bool = False) -> list[dict]:
881 """Divisions that exist but hold no matches for this season (SB-839).
883 The agent's targets are derived from matches MT already has, which makes
884 a division with none of them invisible:
886 no matches -> not advertised -> never scraped -> no matches
888 That is not a hypothetical. On 2026-08-26, with the season's reference
889 data fully in place, `get_match_summary("2026-2027")` returned exactly
890 one target — `Unknown | Unknown`, a friendly with no division — so the
891 agent would have scraped nothing at all for the new season.
893 These are returned separately from `targets` rather than mixed in with
894 a zero count, because they answer a different question. A target says
895 "here is what MT has and what it is missing"; this says "MT has nothing
896 here, go and look". The consumer needs the distinction: the first is
897 incremental sync, the second is a first load.
899 Age groups are deliberately absent. MT cannot know which age groups a
900 brand-new division serves — nothing has ever been scraped for it — and
901 guessing would send the scraper after combinations that do not exist
902 (U13 has no Flex; U15 has no Pathway). The source feed carries that
903 structure, so the scraper resolves it.
905 Computed in the database by agent_bootstrap_divisions (SB-1080). This
906 used to fetch the division_id of every match in the season — 5,331 rows
907 in six round trips for 2026-2027, growing with every fixture — to find
908 about twenty divisions. The rules live in that function now: retired
909 leagues are never offered, test leagues only with include_test, and
910 rows come back ordered by league then division.
911 """
912 season_id = self._season_id_by_name(season_name)
913 if season_id is None:
914 return []
916 try:
917 response = self.client.rpc(
918 "agent_bootstrap_divisions",
919 {"p_season_id": season_id, "p_include_test": include_test},
920 ).execute()
921 except Exception:
922 # This runs inside the agent's status endpoint. Losing bootstrap
923 # hints degrades discovery; raising would take down the whole plan.
924 logger.exception("Error computing bootstrap divisions", season_name=season_name)
925 return []
927 return [
928 {"division_id": row["division_id"], "division": row["division"], "league": row["league"]}
929 for row in (response.data or [])
930 ]
932 def get_matches_by_team(
933 self,
934 team_id: int,
935 season_id: int | None = None,
936 age_group_id: int | None = None,
937 include_test: bool = False,
938 ) -> list[dict]:
939 """Get all matches for a specific team.
941 include_test gates the SB-591 test partition.
942 """
943 try:
944 query = self.client.table(MATCHES_READ_RELATION).select("""
945 *,
946 home_team:teams!matches_home_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
947 away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, name, logo_url)),
948 season:seasons(id, name, start_date),
949 age_group:age_groups(id, name),
950 match_type:match_types(id, name),
951 division:divisions(id, name)
952 """)
954 if not include_test:
955 query = query.eq("is_test", False)
957 # At an age group, follow the age group this team fielded — not the
958 # match's — so a side that played up still finds the match (SB-1444).
959 if age_group_id:
960 query = query.or_(team_age_group_filter(team_id, age_group_id))
961 else:
962 query = query.or_(f"home_team_id.eq.{team_id},away_team_id.eq.{team_id}")
964 if season_id:
965 query = query.eq("season_id", season_id)
967 response = query.order("match_date", desc=True).execute()
969 # Flatten response (same as get_all_matches)
970 matches = []
971 for match in response.data:
972 flat_match = {
973 "id": match["id"],
974 "match_date": match["match_date"],
975 "scheduled_kickoff": match.get("scheduled_kickoff"),
976 "home_team_id": match["home_team_id"],
977 "away_team_id": match["away_team_id"],
978 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
979 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
980 "home_team_club": match["home_team"].get("club") if match.get("home_team") else None,
981 "away_team_club": match["away_team"].get("club") if match.get("away_team") else None,
982 "home_score": match["home_score"],
983 "away_score": match["away_score"],
984 # A Flex draw is decided on penalties, and the pair is stored;
985 # leaving it out of the flatten is why the page showed a draw
986 # and why the ingest re-wrote it every run (SB-1026).
987 "home_penalty_score": match.get("home_penalty_score"),
988 "away_penalty_score": match.get("away_penalty_score"),
989 "season_id": match["season_id"],
990 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
991 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
992 "age_group_id": match["age_group_id"],
993 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
994 "home_age_group_id": match.get("home_age_group_id"),
995 "away_age_group_id": match.get("away_age_group_id"),
996 "match_type_id": match["match_type_id"],
997 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
998 "division_id": match.get("division_id"),
999 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
1000 "division": match.get("division"), # Include full division object with leagues
1001 "match_status": match.get("match_status"),
1002 "scoring_mode": match.get("scoring_mode", "manual"),
1003 "created_by": match.get("created_by"),
1004 "updated_by": match.get("updated_by"),
1005 "source": match.get("source", "manual"),
1006 "match_id": match.get("match_id"), # External match identifier
1007 "created_at": match.get("created_at"),
1008 "updated_at": match.get("updated_at"),
1009 }
1010 matches.append(flat_match)
1012 return matches
1014 except Exception:
1015 logger.exception("Error querying matches by team")
1016 return []
1018 def get_match_preview(
1019 self,
1020 home_team_id: int,
1021 away_team_id: int,
1022 season_id: int | None = None,
1023 age_group_id: int | None = None,
1024 recent_count: int = 5,
1025 include_test: bool = False,
1026 match_type_id: int | None = None,
1027 home_age_group_id: int | None = None,
1028 away_age_group_id: int | None = None,
1029 ) -> dict:
1030 """Get match preview data: recent form, common opponents, and head-to-head history.
1032 Args:
1033 home_team_id: ID of the home team in the upcoming match
1034 away_team_id: ID of the away team in the upcoming match
1035 season_id: Season for recent form and common opponents (None = all seasons)
1036 age_group_id: Optional filter to restrict to a specific age group
1037 recent_count: How many recent matches to return per team
1038 include_test: SB-591 test partition gate
1039 match_type_id: The previewed match's competition; a qualifying one
1040 narrows recent form to qualifying competitions (SB-1346)
1041 home_age_group_id / away_age_group_id: one team's own season age,
1042 when it is not the match's: a pro academy's U15 side plays its
1043 league at U16 (SB-1908). Recent form and common opponents read
1044 each team at its own age; head-to-head keeps the match's cohort.
1046 Returns:
1047 Dict with home_team_recent, away_team_recent, common_opponents, head_to_head
1048 """
1049 select_str = """
1050 *,
1051 home_team:teams!matches_home_team_id_fkey(id, name),
1052 away_team:teams!matches_away_team_id_fkey(id, name),
1053 season:seasons(id, name, start_date),
1054 age_group:age_groups(id, name),
1055 match_type:match_types(id, name),
1056 division:divisions(id, name)
1057 """
1059 def flatten(match: dict) -> dict:
1060 return {
1061 "id": match["id"],
1062 "match_date": match["match_date"],
1063 "scheduled_kickoff": match.get("scheduled_kickoff"),
1064 "home_team_id": match["home_team_id"],
1065 "away_team_id": match["away_team_id"],
1066 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
1067 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
1068 "home_score": match["home_score"],
1069 "away_score": match["away_score"],
1070 # A Flex draw is decided on penalties, and the pair is stored;
1071 # leaving it out of the flatten is why the page showed a draw
1072 # and why the ingest re-wrote it every run (SB-1026).
1073 "home_penalty_score": match.get("home_penalty_score"),
1074 "away_penalty_score": match.get("away_penalty_score"),
1075 "season_id": match["season_id"],
1076 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
1077 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
1078 "age_group_id": match["age_group_id"],
1079 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
1080 "match_type_id": match["match_type_id"],
1081 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
1082 "division_id": match.get("division_id"),
1083 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
1084 "match_status": match.get("match_status"),
1085 "scoring_mode": match.get("scoring_mode", "manual"),
1086 "source": match.get("source", "manual"),
1087 "match_id": match.get("match_id"),
1088 "created_at": match.get("created_at"),
1089 "updated_at": match.get("updated_at"),
1090 }
1092 team_ages = {
1093 home_team_id: home_age_group_id or age_group_id,
1094 away_team_id: away_age_group_id or age_group_id,
1095 }
1097 def build_base_query(team_id: int):
1098 q = (
1099 self.client.table(MATCHES_READ_RELATION)
1100 .select(select_str)
1101 .or_(f"home_team_id.eq.{team_id},away_team_id.eq.{team_id}")
1102 .in_("match_status", ["completed", "forfeit"])
1103 )
1104 if not include_test: 1104 ↛ 1106line 1104 didn't jump to line 1106 because the condition on line 1104 was always true
1105 q = q.eq("is_test", False)
1106 if season_id: 1106 ↛ 1107line 1106 didn't jump to line 1107 because the condition on line 1106 was never true
1107 q = q.eq("season_id", season_id)
1108 if team_ages.get(team_id):
1109 q = q.eq("age_group_id", team_ages[team_id])
1110 return q
1112 def birth_year(age_group_name: str | None, season_name: str | None) -> int | None:
1113 """Derive a squad's birth year from its age group + season.
1115 Teams are stored per-club (one team_id shared across every age
1116 group), so an age group label like "U14" only identifies a squad
1117 when paired with the season it was played in. A U14 squad in
1118 2025-2026 was born in 2026 - 14 = 2012, and that same group of kids
1119 was U13 in 2024-2025 (2025 - 13 = 2012). Birth year therefore
1120 follows the cohort as it ages up year to year.
1121 """
1122 try:
1123 age_num = int(age_group_name.lstrip("Uu"))
1124 end_year = int(season_name.split("-")[-1])
1125 except (AttributeError, ValueError, TypeError, IndexError):
1126 return None
1127 return end_year - age_num
1129 try:
1130 types_resp = self.client.table("match_types").select("id, counts_for_qualification").execute()
1131 match_types = types_resp.data or []
1133 def scoped(q, type_ids: list[int] | None):
1134 return q if type_ids is None else q.in_("match_type_id", type_ids)
1136 # --- Recent form for each team ---
1137 # Every competition, unless the previewed match is a qualifying one.
1138 form_type_ids = form_match_type_ids(match_types, match_type_id)
1139 home_resp = (
1140 scoped(build_base_query(home_team_id), form_type_ids)
1141 .order("match_date", desc=True)
1142 .limit(recent_count)
1143 .execute()
1144 )
1145 away_resp = (
1146 scoped(build_base_query(away_team_id), form_type_ids)
1147 .order("match_date", desc=True)
1148 .limit(recent_count)
1149 .execute()
1150 )
1151 home_recent = [flatten(m) for m in (home_resp.data or [])]
1152 away_recent = [flatten(m) for m in (away_resp.data or [])]
1154 # --- Common opponents (season-scoped, League/Flex only) ---
1155 # Fetch all season matches for both teams to find shared opponents.
1156 # Only qualifying competitions compare like with like: a tournament
1157 # or friendly result is not evidence about a league match, and a
1158 # tournament draw must not turn up as a "shared" opponent (SB-1347).
1159 common_type_ids = qualifying_match_type_ids(match_types)
1160 home_all_resp = (
1161 scoped(build_base_query(home_team_id), common_type_ids).order("match_date", desc=True).execute()
1162 )
1163 away_all_resp = (
1164 scoped(build_base_query(away_team_id), common_type_ids).order("match_date", desc=True).execute()
1165 )
1166 home_all = [flatten(m) for m in (home_all_resp.data or [])]
1167 away_all = [flatten(m) for m in (away_all_resp.data or [])]
1169 def extract_opponents(matches: list[dict], team_id: int) -> dict[int, str]:
1170 """Return {opponent_id: opponent_name} excluding the two preview teams."""
1171 opps: dict[int, str] = {}
1172 for m in matches: 1172 ↛ 1173line 1172 didn't jump to line 1173 because the loop on line 1172 never started
1173 if m["home_team_id"] == team_id:
1174 opp_id, opp_name = m["away_team_id"], m["away_team_name"]
1175 else:
1176 opp_id, opp_name = m["home_team_id"], m["home_team_name"]
1177 # Exclude head-to-head matches between the two preview teams
1178 if opp_id not in (home_team_id, away_team_id):
1179 opps[opp_id] = opp_name
1180 return opps
1182 home_opps = extract_opponents(home_all, home_team_id)
1183 away_opps = extract_opponents(away_all, away_team_id)
1184 common_ids = sorted(set(home_opps) & set(away_opps), key=lambda i: home_opps[i])
1186 common_opponents = []
1187 for opp_id in common_ids: 1187 ↛ 1188line 1187 didn't jump to line 1188 because the loop on line 1187 never started
1188 home_vs = [m for m in home_all if opp_id in (m["home_team_id"], m["away_team_id"])]
1189 away_vs = [m for m in away_all if opp_id in (m["home_team_id"], m["away_team_id"])]
1190 common_opponents.append(
1191 {
1192 "opponent_id": opp_id,
1193 "opponent_name": home_opps[opp_id],
1194 "home_team_matches": home_vs,
1195 "away_team_matches": away_vs,
1196 }
1197 )
1199 # --- Head-to-head history (same birth-year cohort, all seasons) ---
1200 # Teams are stored per-club, so this club pair can meet on the same
1201 # day across several age groups (U13/U14/U15/U16 are different kids).
1202 # We scope H2H to the previewed match's birth-year cohort so it
1203 # follows the SAME squad as it ages up year to year (U14 this season
1204 # ⇄ U13 last season), across every match type (league, tournament,
1205 # friendly) — tournament opponents need not share a league. If the
1206 # previewed age group / season can't be resolved, fall back to the
1207 # unfiltered list rather than returning nothing.
1208 target_birth_year = None
1209 if age_group_id and season_id: 1209 ↛ 1210line 1209 didn't jump to line 1210 because the condition on line 1209 was never true
1210 ag_lookup = self.client.table("age_groups").select("name").eq("id", age_group_id).execute()
1211 season_lookup = self.client.table("seasons").select("name").eq("id", season_id).execute()
1212 ag_name = ag_lookup.data[0]["name"] if ag_lookup.data else None
1213 season_name = season_lookup.data[0]["name"] if season_lookup.data else None
1214 target_birth_year = _birth_year_from_labels(ag_name, season_name)
1216 h2h_query = (
1217 self.client.table(MATCHES_READ_RELATION)
1218 .select(select_str)
1219 .or_(f"home_team_id.eq.{home_team_id},away_team_id.eq.{home_team_id}")
1220 .in_("match_status", ["completed", "forfeit"])
1221 )
1222 if not include_test: 1222 ↛ 1224line 1222 didn't jump to line 1224 because the condition on line 1222 was always true
1223 h2h_query = h2h_query.eq("is_test", False)
1224 h2h_resp = h2h_query.order("match_date", desc=True).execute()
1225 head_to_head = [
1226 flatten(m) for m in (h2h_resp.data or []) if away_team_id in (m["home_team_id"], m["away_team_id"])
1227 ]
1228 if target_birth_year is not None: 1228 ↛ 1229line 1228 didn't jump to line 1229 because the condition on line 1228 was never true
1229 head_to_head = [
1230 m
1231 for m in head_to_head
1232 if _birth_year_from_labels(m["age_group_name"], m["season_name"]) == target_birth_year
1233 ]
1235 return {
1236 "home_team_id": home_team_id,
1237 "away_team_id": away_team_id,
1238 "home_team_recent": home_recent,
1239 "away_team_recent": away_recent,
1240 "common_opponents": common_opponents,
1241 "head_to_head": head_to_head,
1242 }
1244 except Exception:
1245 logger.exception("Error building match preview")
1246 return {
1247 "home_team_id": home_team_id,
1248 "away_team_id": away_team_id,
1249 "home_team_recent": [],
1250 "away_team_recent": [],
1251 "common_opponents": [],
1252 "head_to_head": [],
1253 }
1255 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
1256 def add_match(
1257 self,
1258 home_team_id: int,
1259 away_team_id: int,
1260 match_date: str,
1261 home_score: int,
1262 away_score: int,
1263 season_id: int,
1264 age_group_id: int,
1265 match_type_id: int,
1266 division_id: int | None = None,
1267 status: str | None = "scheduled",
1268 created_by: str | None = None,
1269 source: str = "manual",
1270 external_match_id: str | None = None,
1271 scheduled_kickoff: str | None = None,
1272 home_age_group_id: int | None = None,
1273 away_age_group_id: int | None = None,
1274 ) -> bool:
1275 """Add a new match with audit trail and optional external match_id.
1277 home_age_group_id / away_age_group_id are for a side that played up or
1278 down (SB-1444); omitted or equal to age_group_id, they store as NULL.
1279 """
1280 try:
1281 data = {
1282 "match_date": match_date,
1283 "home_team_id": home_team_id,
1284 "away_team_id": away_team_id,
1285 "home_score": home_score,
1286 "away_score": away_score,
1287 "season_id": season_id,
1288 "age_group_id": age_group_id,
1289 "match_type_id": match_type_id,
1290 "source": source,
1291 }
1293 # Add optional fields
1294 if division_id: 1294 ↛ 1295line 1294 didn't jump to line 1295 because the condition on line 1294 was never true
1295 data["division_id"] = division_id
1296 if status: 1296 ↛ 1298line 1296 didn't jump to line 1298 because the condition on line 1296 was always true
1297 data["match_status"] = status # Map status to match_status column
1298 if created_by: 1298 ↛ 1299line 1298 didn't jump to line 1299 because the condition on line 1298 was never true
1299 data["created_by"] = created_by
1300 if external_match_id: 1300 ↛ 1301line 1300 didn't jump to line 1301 because the condition on line 1300 was never true
1301 data["match_id"] = external_match_id
1302 if scheduled_kickoff: 1302 ↛ 1303line 1302 didn't jump to line 1303 because the condition on line 1302 was never true
1303 data["scheduled_kickoff"] = scheduled_kickoff
1304 for column, value in (("home_age_group_id", home_age_group_id), ("away_age_group_id", away_age_group_id)):
1305 if side_age_group(value, age_group_id) is not None: 1305 ↛ 1306line 1305 didn't jump to line 1306 because the condition on line 1305 was never true
1306 data[column] = value
1308 response = self.client.table("matches").insert(data).execute()
1310 return bool(response.data)
1312 except APIError as e:
1313 error_dict = e.args[0] if e.args else {}
1314 if error_dict.get("code") == "23505":
1315 # Duplicate key violation
1316 logger.warning(
1317 "Duplicate match detected",
1318 home_team_id=home_team_id,
1319 away_team_id=away_team_id,
1320 match_date=match_date,
1321 details=error_dict.get("details"),
1322 )
1323 raise DuplicateRecordError(
1324 message="A match with these teams on this date already exists",
1325 details=error_dict.get("details"),
1326 ) from e
1327 logger.exception("Error adding match")
1328 return False
1329 except Exception:
1330 logger.exception("Error adding match")
1331 return False
1333 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
1334 def add_match_with_external_id(
1335 self,
1336 home_team_id: int,
1337 away_team_id: int,
1338 match_date: str,
1339 home_score: int,
1340 away_score: int,
1341 season_id: int,
1342 age_group_id: int,
1343 match_type_id: int,
1344 external_match_id: str,
1345 division_id: int | None = None,
1346 created_by: str | None = None,
1347 source: str = "match-scraper",
1348 ) -> bool:
1349 """Add a new match with external match_id and audit trail.
1351 This is a convenience wrapper around add_match() for backwards compatibility.
1352 Consider using add_match() directly with external_match_id parameter.
1353 """
1354 return self.add_match(
1355 home_team_id=home_team_id,
1356 away_team_id=away_team_id,
1357 match_date=match_date,
1358 home_score=home_score,
1359 away_score=away_score,
1360 season_id=season_id,
1361 age_group_id=age_group_id,
1362 match_type_id=match_type_id,
1363 division_id=division_id,
1364 created_by=created_by,
1365 source=source,
1366 external_match_id=external_match_id,
1367 )
1369 @invalidates_cache(MATCHES_CACHE_PATTERN, PLAYOFF_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
1370 def update_match(
1371 self,
1372 match_id: int,
1373 home_team_id: int,
1374 away_team_id: int,
1375 match_date: str,
1376 home_score: int,
1377 away_score: int,
1378 season_id: int,
1379 age_group_id: int,
1380 match_type_id: int,
1381 division_id: int | None = None,
1382 status: str | None = None,
1383 updated_by: str | None = None,
1384 external_match_id: str | None = None,
1385 scheduled_kickoff: str | None = None,
1386 half_duration: int | None = None,
1387 home_penalty_score: int | None | _Unset = UNSET,
1388 away_penalty_score: int | None | _Unset = UNSET,
1389 home_age_group_id: int | None | _Unset = UNSET,
1390 away_age_group_id: int | None | _Unset = UNSET,
1391 ) -> dict | None:
1392 """Update an existing match with audit trail and optional external match_id.
1394 Returns the updated match data to avoid read-after-write consistency issues.
1395 """
1396 try:
1397 data = {
1398 "match_date": match_date,
1399 "home_team_id": home_team_id,
1400 "away_team_id": away_team_id,
1401 "home_score": home_score,
1402 "away_score": away_score,
1403 "season_id": season_id,
1404 "age_group_id": age_group_id,
1405 "match_type_id": match_type_id,
1406 "division_id": division_id,
1407 }
1409 # Add optional fields
1410 if status: 1410 ↛ 1411line 1410 didn't jump to line 1411 because the condition on line 1410 was never true
1411 data["match_status"] = status
1412 if updated_by: 1412 ↛ 1413line 1412 didn't jump to line 1413 because the condition on line 1412 was never true
1413 data["updated_by"] = updated_by
1414 if external_match_id is not None: # Allow explicit None to clear match_id 1414 ↛ 1415line 1414 didn't jump to line 1415 because the condition on line 1414 was never true
1415 data["match_id"] = external_match_id
1416 if scheduled_kickoff is not None: # Allow explicit None to clear scheduled_kickoff 1416 ↛ 1417line 1416 didn't jump to line 1417 because the condition on line 1416 was never true
1417 data["scheduled_kickoff"] = scheduled_kickoff
1418 # Minutes per half (SB-678). start_first_half is idempotent, so this
1419 # is the only way to correct a duration chosen wrongly at kickoff.
1420 if half_duration is not None: 1420 ↛ 1421line 1420 didn't jump to line 1421 because the condition on line 1420 was never true
1421 data["half_duration"] = half_duration
1422 # Shootout result, guarded like every other optional field above:
1423 # a caller that says nothing about penalties must not wipe one that
1424 # is already recorded.
1425 # UNSET means the caller said nothing, so an existing shootout
1426 # survives an unrelated write; an explicit None clears one that
1427 # should never have been recorded (SB-913).
1428 if home_penalty_score is not UNSET:
1429 data["home_penalty_score"] = home_penalty_score
1430 if away_penalty_score is not UNSET:
1431 data["away_penalty_score"] = away_penalty_score
1432 # Per-side age group (SB-1444): UNSET leaves a playing-up side as
1433 # it is; a value equal to the match's age group, or None, clears it.
1434 if home_age_group_id is not UNSET: 1434 ↛ 1435line 1434 didn't jump to line 1435 because the condition on line 1434 was never true
1435 data["home_age_group_id"] = side_age_group(home_age_group_id, age_group_id)
1436 if away_age_group_id is not UNSET: 1436 ↛ 1437line 1436 didn't jump to line 1437 because the condition on line 1436 was never true
1437 data["away_age_group_id"] = side_age_group(away_age_group_id, age_group_id)
1439 # Execute update
1440 response = self.client.table("matches").update(data).eq("id", match_id).execute()
1442 # Check if update actually affected any rows
1443 if not response.data or len(response.data) == 0: 1443 ↛ 1444line 1443 didn't jump to line 1444 because the condition on line 1443 was never true
1444 logger.warning("Update match failed - no rows affected", match_id=match_id)
1445 # Return None to signal failure
1446 return None
1448 # Clear cache BEFORE re-fetch to avoid returning stale cached data.
1449 # The @invalidates_cache decorator clears AFTER the function returns,
1450 # but get_match_by_id uses @dao_cache and would hit stale cache.
1451 clear_cache(MATCHES_CACHE_PATTERN)
1452 clear_cache(PLAYOFF_CACHE_PATTERN)
1453 clear_cache(TOURNAMENTS_CACHE_PATTERN)
1455 # Get the updated match to return with full relations.
1456 # include_test=True: read-back of an authorised write (SB-649 class)
1457 # — without it a PATCH against the TSC test world returns None and
1458 # the endpoint reports failure for an update that succeeded.
1459 return self.get_match_by_id(match_id, include_test=True)
1461 except Exception:
1462 logger.exception("Error updating match")
1463 return None
1465 @dao_cache("matches:by_id:{match_id}:{include_test}")
1466 def get_match_by_id(
1467 self, match_id: int, include_test: bool = False, *, raise_on_error: bool = False
1468 ) -> dict | None:
1469 """Get a single match by ID with all related data.
1471 raise_on_error re-raises a failed read instead of returning None, so a
1472 caller can tell "no such match" from "could not check" (SB-1780).
1474 include_test gates the SB-591 test partition. The cache key varies by
1475 include_test so a test match fetched by an admin is never served from
1476 cache to a real viewer (and a real viewer's miss is never cached as the
1477 admin's answer).
1478 """
1479 try:
1480 query = (
1481 self.client.table(MATCHES_READ_RELATION)
1482 .select("""
1483 *,
1484 home_team:teams!matches_home_team_id_fkey(
1485 id, name,
1486 club:clubs(id, name, logo_url, primary_color, secondary_color),
1487 division:divisions(id, leagues(sport_type)),
1488 league:leagues(id, name)
1489 ),
1490 away_team:teams!matches_away_team_id_fkey(
1491 id, name,
1492 club:clubs(id, name, logo_url, primary_color, secondary_color),
1493 league:leagues(id, name)
1494 ),
1495 season:seasons(id, name, start_date),
1496 age_group:age_groups(id, name),
1497 match_type:match_types(id, name),
1498 division:divisions(id, name, leagues(id, name, sport_type)),
1499 tournament:tournaments(id, name, logo_url, location)
1500 """)
1501 .eq("id", match_id)
1502 )
1503 if not include_test:
1504 query = query.eq("is_test", False)
1505 response = query.execute()
1507 if response.data and len(response.data) > 0:
1508 match = response.data[0]
1509 # Extract sport_type from division -> leagues (match division)
1510 division = match.get("division") or {}
1511 league = division.get("leagues") or {}
1512 sport_type = league.get("sport_type")
1514 # Fallback: get sport_type from home team's division -> league
1515 if not sport_type: 1515 ↛ 1521line 1515 didn't jump to line 1521 because the condition on line 1515 was always true
1516 home_team = match.get("home_team") or {}
1517 team_div = home_team.get("division") or {}
1518 team_league = team_div.get("leagues") or {}
1519 sport_type = team_league.get("sport_type", "soccer")
1521 tournament = match.get("tournament") or None
1523 # Per-team primary league (needed for tournament matches
1524 # where the match itself has no division/league but we
1525 # still want to know which league the teams come from).
1526 home_team_league = (match.get("home_team") or {}).get("league") or {}
1527 away_team_league = (match.get("away_team") or {}).get("league") or {}
1529 # Flatten the response to match the format from get_all_matches
1530 flat_match = {
1531 "id": match["id"],
1532 "match_date": match["match_date"],
1533 "scheduled_kickoff": match.get("scheduled_kickoff"),
1534 "home_team_id": match["home_team_id"],
1535 "away_team_id": match["away_team_id"],
1536 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
1537 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
1538 "home_team_club": match["home_team"].get("club") if match.get("home_team") else None,
1539 "away_team_club": match["away_team"].get("club") if match.get("away_team") else None,
1540 "home_team_league_name": home_team_league.get("name"),
1541 "away_team_league_name": away_team_league.get("name"),
1542 "home_score": match["home_score"],
1543 "away_score": match["away_score"],
1544 # A Flex draw is decided on penalties, and the pair is stored;
1545 # leaving it out of the flatten is why the page showed a draw
1546 # and why the ingest re-wrote it every run (SB-1026).
1547 "home_penalty_score": match.get("home_penalty_score"),
1548 "away_penalty_score": match.get("away_penalty_score"),
1549 "season_id": match["season_id"],
1550 "season_name": match["season"]["name"] if match.get("season") else "Unknown",
1551 "season_start_date": match["season"].get("start_date") if match.get("season") else None,
1552 "age_group_id": match["age_group_id"],
1553 "age_group_name": match["age_group"]["name"] if match.get("age_group") else "Unknown",
1554 "home_age_group_id": match.get("home_age_group_id"),
1555 "away_age_group_id": match.get("away_age_group_id"),
1556 "match_type_id": match["match_type_id"],
1557 "match_type_name": match["match_type"]["name"] if match.get("match_type") else "Unknown",
1558 "division_id": match.get("division_id"),
1559 "division_name": match["division"]["name"] if match.get("division") else "Unknown",
1560 "division": match.get("division"), # Include full division object with leagues
1561 "tournament_id": match.get("tournament_id"),
1562 "tournament_name": tournament["name"] if tournament else None,
1563 "tournament_logo_url": tournament.get("logo_url") if tournament else None,
1564 # The venue ("Mesa, Arizona"): the Fest card shows kickoff in venue time (SB-1883)
1565 "tournament_location": tournament.get("location") if tournament else None,
1566 "tournament_group": match.get("tournament_group"),
1567 "tournament_round": match.get("tournament_round"),
1568 "location": match.get("location"), # venue and pitch, from the feed (SB-1874)
1569 "sport_type": sport_type,
1570 "match_status": match.get("match_status"),
1571 "scoring_mode": match.get("scoring_mode", "manual"),
1572 "created_by": match.get("created_by"),
1573 "updated_by": match.get("updated_by"),
1574 "source": match.get("source", "manual"),
1575 "match_id": match.get("match_id"), # External match identifier
1576 "created_at": match["created_at"],
1577 "updated_at": match["updated_at"],
1578 # Live match clock fields
1579 "kickoff_time": match.get("kickoff_time"),
1580 "halftime_start": match.get("halftime_start"),
1581 "second_half_start": match.get("second_half_start"),
1582 "match_end_time": match.get("match_end_time"),
1583 "half_duration": match.get("half_duration", 45),
1584 # The dispatcher loads with include_test=True and narrows the
1585 # audience on this flag; dropping it made every rehearsal
1586 # look real (SB-1534).
1587 "is_test": bool(match.get("is_test", False)),
1588 }
1589 return flat_match
1590 else:
1591 return None
1593 except Exception:
1594 logger.exception("Error retrieving match by ID")
1595 if raise_on_error:
1596 raise
1597 return None
1599 @invalidates_cache(MATCHES_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
1600 def delete_match(self, match_id: int) -> bool:
1601 """Delete a match."""
1602 try:
1603 self.client.table("matches").delete().eq("id", match_id).execute()
1605 return True # Supabase delete returns empty data even on success
1607 except Exception:
1608 logger.exception("Error deleting match")
1609 return False
1611 def qualifying_match_type_names(self) -> set[str]:
1612 """The competitions flagged as counting towards cup qualification.
1614 Read from match_types.counts_for_qualification rather than listed in
1615 code, so a new qualifying competition is one flag in one row and every
1616 surface agrees (SB-849).
1617 """
1618 try:
1619 response = self.client.table("match_types").select("name").eq("counts_for_qualification", True).execute()
1620 return {row["name"] for row in (response.data or []) if row.get("name")}
1621 except Exception:
1622 logger.exception("Error reading qualifying match types")
1623 return set()
1625 def _match_type_names(self, match_type: str | None) -> set[str] | None:
1626 """Which competition names a `match_type` argument selects. None = all."""
1627 if match_type is None or match_type == STANDINGS_ALL:
1628 return None
1629 if match_type == STANDINGS_QUALIFYING:
1630 return self.qualifying_match_type_names()
1631 return {match_type}
1633 @dao_cache("matches:standings:{season_id}:{age_group_id}:{division_id}:{match_type}:{include_test}")
1634 def get_standings(
1635 self,
1636 season_id: int | None = None,
1637 age_group_id: int | None = None,
1638 division_id: int | None = None,
1639 match_type: str = "League",
1640 include_test: bool = False,
1641 *,
1642 raise_on_error: bool = False,
1643 ) -> dict:
1644 """
1645 Standings plus the coverage needed to read them honestly.
1647 Args:
1648 season_id: Filter by season
1649 age_group_id: Filter by age group
1650 division_id: Filter by division
1651 match_type: A competition name, "qualifying" (every competition
1652 flagged counts_for_qualification) or "all" (every competition).
1653 include_test: SB-591 test partition. A test match must not move a
1654 real team's points, so this is part of the cache key — the two
1655 audiences never share a computed table.
1656 raise_on_error: Re-raise failures instead of returning an empty
1657 table. The default keeps /api/table's behaviour; the MT AI
1658 get_standings tool passes True so a failed read is not
1659 mistaken for "no matches played" (SB-1496).
1661 Returns:
1662 {"standings": [...], "coverage": {...}}
1664 A single competition is a standing: every match counted was played
1665 between two teams in the table. A combined view is not. Flex brackets
1666 cut across Homegrown divisions, so folding Flex into a Homegrown table
1667 counts results against opponents the table does not list. That is a
1668 record, and `coverage` carries what the UI needs to say so — per
1669 CLAUDE.md, a cross-team statistic ships with its coverage or it does
1670 not ship.
1671 """
1672 try:
1673 names = self._match_type_names(match_type)
1674 combined = names is None or len(names) > 1
1676 logger.info(
1677 "generating league table from database",
1678 season_id=season_id,
1679 age_group_id=age_group_id,
1680 division_id=division_id,
1681 match_type=match_type,
1682 )
1684 # A combined view must not filter by division in the query: a
1685 # team's Flex matches carry the Flex bracket's division_id, so the
1686 # database filter would drop exactly the matches being combined.
1687 # The division work happens below, over team ids.
1688 fetch_division_id = None if combined else division_id
1689 matches = self._fetch_matches_for_standings(
1690 season_id, age_group_id, fetch_division_id, include_test=include_test
1691 )
1692 fixtures = filter_by_match_types(matches, names)
1693 matches = filter_completed_matches(fixtures)
1695 # `fixtures` is everything scheduled for the selection, played or
1696 # not, so an empty table can say "16 fixtures, none played yet"
1697 # rather than show a bare header (SB-1043).
1698 if not combined:
1699 # Everyone who played gets a row unless the table has guests:
1700 # they lose the row, their opponents keep the result (SB-1598).
1701 only_team_ids = None
1702 if division_id: 1702 ↛ 1708line 1702 didn't jump to line 1708 because the condition on line 1702 was always true
1703 fixtures = filter_matches_in_division(fixtures, division_id)
1704 matches = filter_matches_in_division(matches, division_id)
1705 guests = self._guest_team_ids(season_id, age_group_id, division_id)
1706 if guests:
1707 only_team_ids = teams_in_division(fixtures, division_id) - guests
1708 return {
1709 "standings": calculate_standings_with_extras(matches, only_team_ids),
1710 "coverage": self._coverage(match_type, names, matches, None, len(fixtures)),
1711 }
1713 if not division_id:
1714 # No division asked for, so there is no outside-the-table.
1715 return {
1716 "standings": calculate_standings_with_extras(matches),
1717 "coverage": self._coverage(match_type, names, matches, None, len(fixtures)),
1718 }
1720 # The table is the division's teams; the matches counted are those
1721 # teams' matches in any of the selected competitions. The roster
1722 # comes from every fixture filed to the division, so a team with
1723 # only scheduled matches is still in the table it is registered
1724 # to — it has no row yet, but its fixtures count.
1725 roster = teams_in_division(fixtures, division_id) - self._guest_team_ids(
1726 season_id, age_group_id, division_id
1727 )
1728 counted = filter_matches_involving(matches, roster)
1729 scheduled = filter_matches_involving(fixtures, roster)
1731 return {
1732 "standings": calculate_standings_with_extras(counted, roster),
1733 "coverage": self._coverage(match_type, names, counted, roster, len(scheduled)),
1734 }
1736 except Exception:
1737 logger.exception("Error generating league table")
1738 if raise_on_error:
1739 raise
1740 return {"standings": [], "coverage": self._coverage(match_type, None, [], None)}
1742 @staticmethod
1743 def _coverage(
1744 match_type: str | None,
1745 names: set[str] | None,
1746 matches: list[dict],
1747 roster: set[int] | None,
1748 fixtures: int = 0,
1749 ) -> dict:
1750 """What the caller needs in order to caption the table truthfully."""
1751 against_outsiders, outsiders = (0, 0) if roster is None else count_outside_table_opponents(matches, roster)
1752 # How many played matches each selected competition contributes, zero
1753 # included: a combined view that is silently all League because no
1754 # Flex has been played yet looks like a bug until it says so.
1755 by_competition: dict[str, int] = dict.fromkeys(names or [], 0)
1756 for match in matches:
1757 name = (match.get("match_type") or {}).get("name")
1758 if name: 1758 ↛ 1756line 1758 didn't jump to line 1756 because the condition on line 1758 was always true
1759 by_competition[name] = by_competition.get(name, 0) + 1
1760 return {
1761 "match_type": match_type,
1762 "competitions": sorted(names) if names is not None else None,
1763 "matches_counted": len(matches),
1764 "fixtures": fixtures,
1765 "counted_by_competition": dict(sorted(by_competition.items())),
1766 "matches_vs_outside_table": against_outsiders,
1767 "teams_outside_table": outsiders,
1768 # Which of the counted competitions score a shootout (winner 2,
1769 # loser 1). The reader needs this to see why 1W 2D is worth 7,
1770 # and a combined table can hold both models at once (SB-1027).
1771 "shootout_points": shootout_competitions(matches),
1772 }
1774 @dao_cache("matches:team_active:{season_id}:{team_id}:{include_test}")
1775 def team_has_matches_in_season(self, team_id: int, season_id: int, include_test: bool = False) -> bool:
1776 """Whether a team has at least one match, home or away, in a season.
1778 What "active" means for get_my_team (SB-1322): derived from scraped
1779 fixtures, so a team that stops playing drops out and one that returns
1780 comes back with no flag to maintain. An existence check (`limit 1`), not a
1781 season's match list — PostgREST caps a response at 1000 rows, and a
1782 truncated list would read as "no matches".
1784 Raises on a failed query: returning False there would read as "inactive".
1785 """
1786 query = (
1787 self.client.table(MATCHES_READ_RELATION)
1788 .select("id")
1789 .eq("season_id", season_id)
1790 .or_(f"home_team_id.eq.{team_id},away_team_id.eq.{team_id}")
1791 )
1792 if not include_test:
1793 query = query.eq("is_test", False)
1794 return bool(query.limit(1).execute().data)
1796 @dao_cache("matches:leagues_present:{season_id}:{include_test}")
1797 def get_leagues_present(self, season_id: int | None = None, include_test: bool = False) -> list[dict]:
1798 """How many matches each league has in a season.
1800 Returns `[{"league_id": int, "matches": int}, ...]` — a list, not a map
1801 keyed by league id, because this is cached: JSON has no integer keys, so
1802 a dict[int, int] comes back from Redis with string keys and every
1803 `counts[league_id]` lookup silently misses. The symptom would be every
1804 league reading as zero matches after the first cache fill, which is
1805 exactly the wrong answer for a filter that hides leagues with none.
1807 A league with no matches in the season being viewed has nothing to show,
1808 and offering it in a filter is the loading-skeleton failure CLAUDE.md
1809 warns about — a control promising data that is not coming.
1811 Matches carry a division, not a league, so this resolves through
1812 divisions. Deliberately NOT through `teams.league_id`: Flex has zero
1813 teams by that column, because its participants are Homegrown teams, and
1814 keying on it would hide the newest competition in the product.
1815 """
1816 try:
1817 query = self.client.table(MATCHES_READ_RELATION).select("division_id")
1818 if not include_test:
1819 query = query.eq("is_test", False)
1820 if season_id: 1820 ↛ 1822line 1820 didn't jump to line 1822 because the condition on line 1820 was always true
1821 query = query.eq("season_id", season_id)
1822 matches = query.execute().data or []
1824 divisions = self.client.table("divisions").select("id, league_id").execute().data or []
1825 league_of = {d["id"]: d.get("league_id") for d in divisions}
1827 counts: dict[int, int] = {}
1828 for match in matches:
1829 league_id = league_of.get(match.get("division_id"))
1830 if league_id is not None:
1831 counts[league_id] = counts.get(league_id, 0) + 1
1832 return [{"league_id": league_id, "matches": n} for league_id, n in sorted(counts.items())]
1833 except Exception:
1834 logger.exception("Error counting matches per league")
1835 return []
1837 @dao_cache("matches:divisions_present:{season_id}:{age_group_id}:{include_test}")
1838 def get_divisions_present(
1839 self,
1840 season_id: int | None = None,
1841 age_group_id: int | None = None,
1842 include_test: bool = False,
1843 ) -> list[dict]:
1844 """How many fixtures each division holds for a season and age group.
1846 Returns `[{"division_id": int, "matches": int, "played": int}, ...]` —
1847 a list, not a map, for the same reason as get_leagues_present: this is
1848 cached, and a dict[int, int] comes back from Redis with string keys.
1850 A division with no fixtures at this age group has nothing to show. In
1851 2026-2027 U15 that is 11 of 12 Homegrown divisions — Pathway does not
1852 exist at U15, and Florida U15-U19 has sent nothing (SB-1021) — so a
1853 dropdown offering all 12 is eleven blank tables (SB-1035).
1855 `matches` and `played` are both returned because "no results yet" and
1856 "not played here" are different answers, and only the second means
1857 the division should be hidden.
1858 """
1859 try:
1860 query = self.client.table(MATCHES_READ_RELATION).select("division_id, match_status")
1861 if not include_test: 1861 ↛ 1863line 1861 didn't jump to line 1863 because the condition on line 1861 was always true
1862 query = query.eq("is_test", False)
1863 if season_id: 1863 ↛ 1865line 1863 didn't jump to line 1865 because the condition on line 1863 was always true
1864 query = query.eq("season_id", season_id)
1865 if age_group_id: 1865 ↛ 1867line 1865 didn't jump to line 1867 because the condition on line 1865 was always true
1866 query = query.eq("age_group_id", age_group_id)
1867 matches = query.execute().data or []
1869 counts: dict[int, dict[str, int]] = {}
1870 for match in matches:
1871 division_id = match.get("division_id")
1872 if division_id is None:
1873 continue
1874 row = counts.setdefault(division_id, {"matches": 0, "played": 0})
1875 row["matches"] += 1
1876 if match.get("match_status") in ("completed", "forfeit"):
1877 row["played"] += 1
1878 return [{"division_id": division_id, **row} for division_id, row in sorted(counts.items())]
1879 except Exception:
1880 logger.exception("Error counting matches per division")
1881 return []
1883 def league_family_divisions(self, league_id: int) -> tuple[set[int], set[int]]:
1884 """(division ids of this league and its child leagues, division ids of this league alone).
1886 A child league is one of its parent's competitions (Flex under
1887 Homegrown, SB-1039), so "what does Homegrown play" spans both. The
1888 second set is what identifies the league's *own* competition.
1889 """
1890 leagues = self.client.table("leagues").select("id, parent_league_id").execute().data or []
1891 family = {league_id} | {lg["id"] for lg in leagues if lg.get("parent_league_id") == league_id}
1892 divisions = self.client.table("divisions").select("id, league_id").execute().data or []
1893 in_family = {d["id"] for d in divisions if d.get("league_id") in family}
1894 own = {d["id"] for d in divisions if d.get("league_id") == league_id}
1895 return in_family, own
1897 @dao_cache("matches:competitions:{season_id}:{age_group_id}:{division_id}:{league_id}:{include_test}")
1898 def get_competitions_present(
1899 self,
1900 season_id: int | None = None,
1901 age_group_id: int | None = None,
1902 division_id: int | None = None,
1903 include_test: bool = False,
1904 league_id: int | None = None,
1905 ) -> list[dict]:
1906 """Which competitions this age group (and division, or league) actually plays.
1908 With `league_id` and no division, the answer spans the league and its
1909 child leagues — Homegrown's competitions are League and Flex, because
1910 Flex is a league whose parent is Homegrown (SB-1039). `in_division`
1911 then counts matches filed to the league's own conferences, so it still
1912 identifies the competition the league opens on.
1914 U13 and U14 play no Flex; U13/U14/U15 have no Pro Player Pathway
1915 divisions. A client needs to know that from the data, because the
1916 alternative is hardcoded age-group ids in the frontend that will rot
1917 the first time MLS Next moves the boundary (SB-834/SB-835).
1919 With a division, the answer is scoped to that division's teams rather
1920 than to matches carrying its division_id — a Homegrown division's teams
1921 play Flex under Flex bracket ids, and a Flex tab that never appeared
1922 for them would be the bug this exists to prevent.
1924 Returns one row per competition present, in display_order, with:
1926 - `matches` / `played` — all, and completed. They differ before a
1927 season starts, and "no results yet" is not the same answer as "this
1928 competition is not played here".
1929 - `in_division` — how many of those matches actually carry this
1930 division_id. Non-zero identifies the division's *own* competition
1931 (League for Northeast, Flex for Turnpike), which is what a standings
1932 screen should open on. Deriving that from the league's name instead
1933 would be the hardcoding this endpoint exists to remove.
1934 """
1935 try:
1936 matches = self._fetch_matches_for_standings(season_id, age_group_id, None, include_test=include_test)
1938 own_division_ids: set[int] | None = None
1939 if division_id:
1940 roster = teams_in_division(matches, division_id)
1941 matches = filter_matches_involving(matches, roster)
1942 elif league_id: 1942 ↛ 1946line 1942 didn't jump to line 1946 because the condition on line 1942 was always true
1943 in_family, own_division_ids = self.league_family_divisions(league_id)
1944 matches = [m for m in matches if m.get("division_id") in in_family]
1946 played_ids = {m["id"] for m in filter_completed_matches(matches) if m.get("id") is not None}
1948 totals: dict[int, dict] = {}
1949 for match in matches:
1950 match_type = match.get("match_type") or {}
1951 type_id = match_type.get("id")
1952 if type_id is None: 1952 ↛ 1953line 1952 didn't jump to line 1953 because the condition on line 1952 was never true
1953 continue
1954 row = totals.setdefault(
1955 type_id,
1956 {"id": type_id, "name": match_type.get("name"), "matches": 0, "played": 0, "in_division": 0},
1957 )
1958 row["matches"] += 1
1959 if match.get("id") in played_ids:
1960 row["played"] += 1
1961 # "Own" is the division asked for, or — for a league query —
1962 # any conference the league holds directly rather than
1963 # through a child league.
1964 filed_to = match.get("division_id")
1965 if division_id:
1966 own = filed_to == division_id
1967 else:
1968 own = own_division_ids is not None and filed_to in own_division_ids
1969 if own:
1970 row["in_division"] += 1
1972 if not totals:
1973 return []
1975 # The whole row rather than a column list: has_standings (SB-1037)
1976 # is read from it, and a backend deployed ahead of that migration
1977 # must still answer rather than 400 on the column name.
1978 reference = self.client.table("match_types").select("*").execute()
1979 by_id = {row["id"]: row for row in (reference.data or [])}
1981 present = []
1982 for type_id, row in totals.items():
1983 meta = by_id.get(type_id, {})
1984 present.append(
1985 {
1986 **row,
1987 "name": meta.get("name") or row["name"],
1988 "counts_for_qualification": bool(meta.get("counts_for_qualification")),
1989 "display_order": meta.get("display_order"),
1990 # Passed through, not coerced: None means the column
1991 # does not exist yet, and a client treats that as
1992 # "offer it" rather than hiding every competition.
1993 "has_standings": meta.get("has_standings"),
1994 }
1995 )
1997 # NULL display_order sorts last, as it does in the reference query.
1998 present.sort(key=lambda r: (r["display_order"] is None, r["display_order"] or 0, r["name"] or ""))
1999 return present
2001 except Exception:
2002 logger.exception("Error listing competitions present")
2003 return []
2005 def get_league_table(
2006 self,
2007 season_id: int | None = None,
2008 age_group_id: int | None = None,
2009 division_id: int | None = None,
2010 match_type: str = "League",
2011 include_test: bool = False,
2012 ) -> list[dict]:
2013 """Standings only. See get_standings for the coverage that goes with them."""
2014 return self.get_standings(
2015 season_id=season_id,
2016 age_group_id=age_group_id,
2017 division_id=division_id,
2018 match_type=match_type,
2019 include_test=include_test,
2020 )["standings"]
2022 def _fetch_matches_for_standings(
2023 self,
2024 season_id: int | None = None,
2025 age_group_id: int | None = None,
2026 division_id: int | None = None,
2027 include_test: bool = False,
2028 ) -> list[dict]:
2029 """
2030 Fetch matches from database for standings calculation.
2032 This is a thin data access method that only handles the query.
2033 All business logic is in pure functions.
2035 Args:
2036 season_id: Filter by season
2037 age_group_id: Filter by age group
2038 division_id: Filter by division
2039 include_test: SB-591 test partition gate
2041 Returns:
2042 List of match dictionaries from database
2043 """
2044 logger.info(
2045 "fetching matches for standings calculation from database",
2046 season_id=season_id,
2047 age_group_id=age_group_id,
2048 division_id=division_id,
2049 )
2050 query = self.client.table(MATCHES_READ_RELATION).select("""
2051 *,
2052 home_team:teams!matches_home_team_id_fkey(id, name, division_id, club:clubs(id, name, logo_url)),
2053 away_team:teams!matches_away_team_id_fkey(id, name, division_id, club:clubs(id, name, logo_url)),
2054 match_type:match_types(*)
2055 """)
2056 # match_types(*) rather than a column list on purpose: the standings
2057 # code reads shootout_points (SB-1027) and treats a missing key as
2058 # off, so a backend deployed before the migration lands still serves
2059 # tables instead of a 400 on the column name.
2061 # Apply database-level filters
2062 if not include_test:
2063 query = query.eq("is_test", False)
2064 if season_id:
2065 query = query.eq("season_id", season_id)
2066 if age_group_id:
2067 query = query.eq("age_group_id", age_group_id)
2068 if division_id:
2069 query = query.eq("division_id", division_id)
2071 response = query.execute()
2072 return response.data
2074 # === Division Guests (SB-1598) ===
2076 def _guest_team_ids(self, season_id: int | None, age_group_id: int | None, division_id: int | None) -> set[int]:
2077 """Teams that get no row in this table.
2079 A guest is per table, so a query that is not for one table has none.
2080 A failed read returns none too: a backend deployed ahead of the
2081 migration, or a blip here, must still serve standings.
2082 """
2083 if not (season_id and age_group_id and division_id):
2084 return set()
2085 try:
2086 response = (
2087 self.client.table("division_guests")
2088 .select("team_id")
2089 .eq("season_id", season_id)
2090 .eq("age_group_id", age_group_id)
2091 .eq("division_id", division_id)
2092 .execute()
2093 )
2094 except Exception:
2095 logger.warning("could not read division guests", exc_info=True)
2096 return set()
2097 return {row["team_id"] for row in response.data or []}
2099 def list_division_guests(
2100 self,
2101 season_id: int | None = None,
2102 age_group_id: int | None = None,
2103 division_id: int | None = None,
2104 ) -> list[dict]:
2105 """Guests with the names needed to read them, narrowed by what is given."""
2106 query = self.client.table("division_guests").select(
2107 "*, team:teams(id, name), division:divisions(id, name, leagues!divisions_league_id_fkey(name)),"
2108 " age_group:age_groups(id, name), season:seasons(id, name)"
2109 )
2110 if season_id:
2111 query = query.eq("season_id", season_id)
2112 if age_group_id:
2113 query = query.eq("age_group_id", age_group_id)
2114 if division_id:
2115 query = query.eq("division_id", division_id)
2116 return query.order("id").execute().data or []
2118 @invalidates_cache(MATCHES_CACHE_PATTERN)
2119 def add_division_guest(
2120 self,
2121 team_id: int,
2122 division_id: int,
2123 age_group_id: int,
2124 season_id: int,
2125 reason: str,
2126 created_by: str | None = None,
2127 ) -> dict:
2128 """Hide a team from one table. Adding it twice updates the reason."""
2129 response = (
2130 self.client.table("division_guests")
2131 .upsert(
2132 {
2133 "team_id": team_id,
2134 "division_id": division_id,
2135 "age_group_id": age_group_id,
2136 "season_id": season_id,
2137 "reason": reason,
2138 "created_by": created_by,
2139 },
2140 on_conflict="team_id,division_id,age_group_id,season_id",
2141 )
2142 .execute()
2143 )
2144 return response.data[0]
2146 @invalidates_cache(MATCHES_CACHE_PATTERN)
2147 def remove_division_guest(self, guest_id: int) -> bool:
2148 """Give a team its row back. False when there was no such guest."""
2149 response = self.client.table("division_guests").delete().eq("id", guest_id).execute()
2150 return bool(response.data)
2152 # === Live Match Methods ===
2154 def get_live_matches(self, include_test: bool = False, live_scored_only: bool = True) -> list[dict]:
2155 """Get matches that are under way.
2157 Returns minimal data for the LIVE tab polling.
2159 `live_scored_only` (the default) narrows that to matches someone is
2160 actually live-scoring. A match marked in progress so its score can be
2161 typed in is under way too, but putting it on the LIVE tab promises a
2162 clock and an event feed nobody is driving (SB-910).
2164 include_test gates the SB-591 test partition. This is the endpoint an
2165 Android dry run drives, so a rehearsal must not appear on the public
2166 LIVE tab.
2167 """
2168 try:
2169 query = (
2170 self.client.table(MATCHES_READ_RELATION)
2171 .select("""
2172 id,
2173 match_status,
2174 scoring_mode,
2175 match_date,
2176 home_score,
2177 away_score,
2178 kickoff_time,
2179 home_team:teams!matches_home_team_id_fkey(id, name),
2180 away_team:teams!matches_away_team_id_fkey(id, name)
2181 """)
2182 .eq("match_status", "live")
2183 )
2184 if live_scored_only:
2185 query = query.eq("scoring_mode", "live")
2186 if not include_test: 2186 ↛ 2188line 2186 didn't jump to line 2188 because the condition on line 2186 was always true
2187 query = query.eq("is_test", False)
2188 response = query.execute()
2190 # Flatten the response
2191 result = []
2192 for match in response.data or []:
2193 result.append(
2194 {
2195 "match_id": match["id"],
2196 "match_status": match["match_status"],
2197 "scoring_mode": match.get("scoring_mode", "manual"),
2198 "match_date": match["match_date"],
2199 "home_score": match["home_score"],
2200 "away_score": match["away_score"],
2201 # A Flex draw is decided on penalties, and the pair is stored;
2202 # leaving it out of the flatten is why the page showed a draw
2203 # and why the ingest re-wrote it every run (SB-1026).
2204 "home_penalty_score": match.get("home_penalty_score"),
2205 "away_penalty_score": match.get("away_penalty_score"),
2206 "kickoff_time": match.get("kickoff_time"),
2207 "home_team_name": match["home_team"]["name"] if match.get("home_team") else "Unknown",
2208 "away_team_name": match["away_team"]["name"] if match.get("away_team") else "Unknown",
2209 }
2210 )
2211 return result
2213 except Exception:
2214 logger.exception("Error getting live matches")
2215 return []
2217 def get_live_match_state(self, match_id: int, include_test: bool = False) -> dict | None:
2218 """Get full live match state including clock timestamps.
2220 Returns match data with clock fields for the live match view.
2222 include_test gates the SB-591 test partition.
2223 """
2224 try:
2225 query = (
2226 self.client.table(MATCHES_READ_RELATION)
2227 .select("""
2228 *,
2229 home_team:teams!matches_home_team_id_fkey(
2230 id, name,
2231 club:clubs(id, logo_url),
2232 division:divisions(id, leagues(sport_type))
2233 ),
2234 away_team:teams!matches_away_team_id_fkey(id, name, club:clubs(id, logo_url)),
2235 age_group:age_groups(id, name),
2236 match_type:match_types(id, name),
2237 division:divisions(id, name, leagues(id, name, sport_type))
2238 """)
2239 .eq("id", match_id)
2240 )
2241 if not include_test:
2242 query = query.eq("is_test", False)
2243 response = query.single().execute()
2245 if not response.data:
2246 return None
2248 match = response.data
2249 # Extract club logo URLs from nested team -> club relationships
2250 home_team = match.get("home_team") or {}
2251 away_team = match.get("away_team") or {}
2252 home_club = home_team.get("club") or {}
2253 away_club = away_team.get("club") or {}
2255 # Extract sport_type from division -> leagues
2256 division = match.get("division") or {}
2257 league = division.get("leagues") or {}
2258 sport_type = league.get("sport_type")
2260 # Fallback: get sport_type from home team's division -> league
2261 if not sport_type:
2262 team_div = home_team.get("division") or {}
2263 team_league = team_div.get("leagues") or {}
2264 sport_type = team_league.get("sport_type", "soccer")
2266 return {
2267 "match_id": match["id"],
2268 "match_status": match.get("match_status"),
2269 "scoring_mode": match.get("scoring_mode", "manual"),
2270 "match_date": match["match_date"],
2271 "scheduled_kickoff": match.get("scheduled_kickoff"),
2272 "home_score": match["home_score"],
2273 "away_score": match["away_score"],
2274 # A Flex draw is decided on penalties, and the pair is stored;
2275 # leaving it out of the flatten is why the page showed a draw
2276 # and why the ingest re-wrote it every run (SB-1026).
2277 "home_penalty_score": match.get("home_penalty_score"),
2278 "away_penalty_score": match.get("away_penalty_score"),
2279 "kickoff_time": match.get("kickoff_time"),
2280 "halftime_start": match.get("halftime_start"),
2281 "second_half_start": match.get("second_half_start"),
2282 "match_end_time": match.get("match_end_time"),
2283 "half_duration": match.get("half_duration", 45),
2284 "season_id": match.get("season_id"),
2285 "home_team_id": match["home_team_id"],
2286 "home_team_name": home_team.get("name", "Unknown"),
2287 "home_team_logo": home_club.get("logo_url"),
2288 "away_team_id": match["away_team_id"],
2289 "away_team_name": away_team.get("name", "Unknown"),
2290 "away_team_logo": away_club.get("logo_url"),
2291 "age_group_name": match["age_group"]["name"] if match.get("age_group") else None,
2292 "match_type_name": match["match_type"]["name"] if match.get("match_type") else None,
2293 "division_name": match["division"]["name"] if match.get("division") else None,
2294 "sport_type": sport_type,
2295 }
2297 except Exception:
2298 logger.exception("Error getting live match state", match_id=match_id)
2299 return None
2301 @invalidates_cache(MATCHES_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
2302 def update_match_clock(
2303 self,
2304 match_id: int,
2305 action: str,
2306 updated_by: str | None = None,
2307 half_duration: int | None = None,
2308 occurred_at: str | None = None,
2309 ) -> dict | None:
2310 """Update match clock based on action.
2312 Args:
2313 match_id: The match to update
2314 action: Clock action - 'start_first_half', 'start_halftime',
2315 'cancel_halftime', 'start_second_half', 'cancel_second_half',
2316 'end_match'
2317 updated_by: UUID of user performing the action
2318 half_duration: Duration of each half in minutes (only for start_first_half)
2319 occurred_at: ISO timestamp to record instead of now (offline clients
2320 syncing a clock action after the fact)
2322 Returns:
2323 Updated match state or None on error
2324 """
2325 from datetime import datetime
2327 try:
2328 now = occurred_at or datetime.now(UTC).isoformat()
2329 data: dict = {"updated_by": updated_by} if updated_by else {}
2331 if action == "start_first_half":
2332 # Start the match - set kickoff time and status to live
2333 data["kickoff_time"] = now
2334 data["match_status"] = "live"
2335 # Starting the clock is what makes this a live-scored match, as
2336 # opposed to one someone merely marked in progress (SB-910).
2337 # Declared, not inferred from kickoff_time: a manager can start
2338 # a clock and then abandon live scoring, and the LIVE tab needs
2339 # to know the difference.
2340 data["scoring_mode"] = "live"
2341 # Set half duration if provided (default is 45)
2342 if half_duration: 2342 ↛ 2343line 2342 didn't jump to line 2343 because the condition on line 2342 was never true
2343 data["half_duration"] = half_duration
2344 elif action == "start_halftime": 2344 ↛ 2347line 2344 didn't jump to line 2347 because the condition on line 2344 was always true
2345 # Mark halftime started
2346 data["halftime_start"] = now
2347 elif action == "cancel_halftime":
2348 # Roll back to the first half — from half time or, since
2349 # SB-1449, from a second half started by mistake. Clearing
2350 # both lets the derived clock resume as (now - kickoff_time),
2351 # the real game time since kickoff, including the time spent
2352 # mistakenly on the later clock.
2353 current = self.client.table("matches").select("halftime_start").eq("id", match_id).single().execute()
2354 if not current.data:
2355 logger.warning("cancel_halftime rejected - match not found", match_id=match_id)
2356 return None
2357 if not current.data.get("halftime_start"):
2358 logger.warning(
2359 "cancel_halftime rejected - halftime not started",
2360 match_id=match_id,
2361 )
2362 return None
2363 data["halftime_start"] = None
2364 data["second_half_start"] = None
2365 elif action == "cancel_second_half":
2366 # Back to half time (SB-1449): the second half was started too
2367 # early. The half-time countdown resumes from halftime_start.
2368 data["second_half_start"] = None
2369 elif action == "start_second_half":
2370 # Start second half
2371 data["second_half_start"] = now
2372 elif action == "end_match":
2373 # End the match
2374 data["match_end_time"] = now
2375 data["match_status"] = "completed"
2376 else:
2377 logger.warning("Invalid clock action", action=action)
2378 return None
2380 response = self.client.table("matches").update(data).eq("id", match_id).execute()
2382 if not response.data: 2382 ↛ 2383line 2382 didn't jump to line 2383 because the condition on line 2382 was never true
2383 logger.warning("Clock update failed - no rows affected", match_id=match_id)
2384 return None
2386 logger.info(
2387 "match_clock_updated",
2388 match_id=match_id,
2389 action=action,
2390 )
2392 # Return updated state.
2393 #
2394 # include_test=True is required (SB-649): this reads back a row the
2395 # caller was already authorised to write, so re-applying the test
2396 # partition here would return None for a test match and make the
2397 # handler report a 500 for an update that actually succeeded.
2398 # Visibility is enforced on the read endpoints, not on a write's
2399 # own read-back.
2400 return self.get_live_match_state(match_id, include_test=True)
2402 except Exception:
2403 logger.exception("Error updating match clock", match_id=match_id, action=action)
2404 return None
2406 @invalidates_cache(MATCHES_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
2407 def reopen_match(
2408 self,
2409 match_id: int,
2410 updated_by: str | None = None,
2411 ) -> dict | None:
2412 """Reopen a completed match — clear match_end_time, set status back to live.
2414 Score and existing events are preserved. Used to recover from accidental
2415 end_match clicks.
2416 """
2417 try:
2418 current = (
2419 self.client.table("matches")
2420 .select("match_status,match_end_time,second_half_start")
2421 .eq("id", match_id)
2422 .single()
2423 .execute()
2424 )
2426 if not current.data:
2427 logger.warning("Reopen failed - match not found", match_id=match_id)
2428 return None
2430 if current.data.get("match_status") != "completed":
2431 logger.warning(
2432 "Reopen rejected - match not completed",
2433 match_id=match_id,
2434 current_status=current.data.get("match_status"),
2435 )
2436 return None
2438 data: dict = {
2439 "match_end_time": None,
2440 "match_status": "live",
2441 }
2442 if updated_by: 2442 ↛ 2445line 2442 didn't jump to line 2445 because the condition on line 2442 was always true
2443 data["updated_by"] = updated_by
2445 response = self.client.table("matches").update(data).eq("id", match_id).execute()
2447 if not response.data: 2447 ↛ 2448line 2447 didn't jump to line 2448 because the condition on line 2447 was never true
2448 logger.warning("Reopen failed - no rows affected", match_id=match_id)
2449 return None
2451 logger.info("match_reopened", match_id=match_id, updated_by=updated_by)
2452 # include_test=True — read-back of an authorised write (SB-649).
2453 return self.get_live_match_state(match_id, include_test=True)
2455 except Exception:
2456 logger.exception("Error reopening match", match_id=match_id)
2457 return None
2459 @invalidates_cache(MATCHES_CACHE_PATTERN, TOURNAMENTS_CACHE_PATTERN)
2460 def update_match_score(
2461 self,
2462 match_id: int,
2463 home_score: int,
2464 away_score: int,
2465 updated_by: str | None = None,
2466 ) -> dict | None:
2467 """Update match score (used when posting a goal).
2469 Args:
2470 match_id: The match to update
2471 home_score: New home team score
2472 away_score: New away team score
2473 updated_by: UUID of user performing the action
2475 Returns:
2476 Updated match state or None on error
2477 """
2478 try:
2479 data = {
2480 "home_score": home_score,
2481 "away_score": away_score,
2482 }
2483 if updated_by:
2484 data["updated_by"] = updated_by
2486 response = self.client.table("matches").update(data).eq("id", match_id).execute()
2488 if not response.data:
2489 logger.warning("Score update failed - no rows affected", match_id=match_id)
2490 return None
2492 logger.info(
2493 "match_score_updated",
2494 match_id=match_id,
2495 home_score=home_score,
2496 away_score=away_score,
2497 )
2499 # include_test=True — read-back of an authorised write (SB-649).
2500 return self.get_live_match_state(match_id, include_test=True)
2502 except Exception:
2503 logger.exception("Error updating match score", match_id=match_id)
2504 return None
2506 def get_agent_matches(
2507 self,
2508 team: str,
2509 age_group: str,
2510 league: str,
2511 division: str,
2512 season: str,
2513 start_date: str | None = None,
2514 end_date: str | None = None,
2515 include_test: bool = False,
2516 ) -> list[dict]:
2517 """Get individual match records for the audit agent's comparison step.
2519 Returns matches involving the specified team (home or away) in the
2520 given age-group/league/division/season. Used by GET /api/agent/matches.
2522 Args:
2523 team: MT canonical team name, e.g. "IFA".
2524 age_group: e.g. "U14".
2525 league: e.g. "Homegrown".
2526 division: e.g. "Northeast".
2527 season: e.g. "2025-2026".
2528 start_date: If set, only return matches on or after this date (YYYY-MM-DD).
2529 end_date: If set, only return matches on or before this date (YYYY-MM-DD).
2530 include_test: SB-591 test partition. Defaults False so the audit
2531 agent never reports a test fixture as a real-data discrepancy.
2533 Returns:
2534 List of match dicts with fields the audit comparator expects.
2535 """
2536 # Resolve IDs for the reference dimensions
2537 season_resp = self.client.table("seasons").select("id").eq("name", season).limit(1).execute()
2538 if not season_resp.data:
2539 logger.warning("get_agent_matches.season_not_found", season=season)
2540 return []
2541 season_id = season_resp.data[0]["id"]
2543 ag_resp = self.client.table("age_groups").select("id").eq("name", age_group).limit(1).execute()
2544 if not ag_resp.data:
2545 logger.warning("get_agent_matches.age_group_not_found", age_group=age_group)
2546 return []
2547 age_group_id = ag_resp.data[0]["id"]
2549 # Resolve division_id via league join
2550 div_resp = (
2551 self.client.table("divisions")
2552 .select("id, leagues!divisions_league_id_fkey(name)")
2553 .eq("name", division)
2554 .execute()
2555 )
2556 division_id = None
2557 for row in div_resp.data or []:
2558 if row.get("leagues") and row["leagues"].get("name") == league:
2559 division_id = row["id"]
2560 break
2561 if division_id is None:
2562 logger.warning("get_agent_matches.division_not_found", division=division, league=league)
2563 return []
2565 # Resolve team IDs matching the given name
2566 team_resp = self.client.table("teams").select("id").eq("name", team).execute()
2567 team_ids = [r["id"] for r in (team_resp.data or [])]
2568 if not team_ids:
2569 logger.warning("get_agent_matches.team_not_found", team=team)
2570 return []
2572 # Build OR filter for home/away team membership
2573 or_filter = ",".join(
2574 [f"home_team_id.eq.{tid}" for tid in team_ids] + [f"away_team_id.eq.{tid}" for tid in team_ids]
2575 )
2577 try:
2578 query = (
2579 self.client.table(MATCHES_READ_RELATION)
2580 .select(
2581 "match_id, match_date, scheduled_kickoff, home_score, away_score, match_status, "
2582 "home_team:teams!matches_home_team_id_fkey(name), "
2583 "away_team:teams!matches_away_team_id_fkey(name)"
2584 )
2585 .eq("season_id", season_id)
2586 .eq("age_group_id", age_group_id)
2587 .eq("division_id", division_id)
2588 .neq("match_status", "cancelled")
2589 )
2590 if not include_test:
2591 query = query.eq("is_test", False)
2592 if start_date:
2593 query = query.gte("match_date", start_date)
2594 if end_date:
2595 query = query.lte("match_date", end_date)
2596 response = query.or_(or_filter).order("match_date", desc=False).execute()
2597 except Exception:
2598 logger.exception("get_agent_matches.query_error", team=team)
2599 return []
2601 results = []
2602 for m in response.data or []:
2603 # Format match_time as "HH:MM" from scheduled_kickoff (UTC)
2604 match_time = None
2605 if m.get("scheduled_kickoff"):
2606 try:
2607 from datetime import datetime
2609 kt = datetime.fromisoformat(m["scheduled_kickoff"].replace("Z", "+00:00"))
2610 if kt.hour or kt.minute:
2611 match_time = kt.strftime("%H:%M")
2612 except (ValueError, AttributeError):
2613 pass
2615 results.append(
2616 {
2617 "external_match_id": m.get("match_id"),
2618 "home_team": m["home_team"]["name"] if m.get("home_team") else None,
2619 "away_team": m["away_team"]["name"] if m.get("away_team") else None,
2620 "match_date": m["match_date"],
2621 "match_time": match_time,
2622 "home_score": m.get("home_score"),
2623 "away_score": m.get("away_score"),
2624 "match_status": m.get("match_status"),
2625 "age_group": age_group,
2626 "league": league,
2627 "division": division,
2628 "season": season,
2629 }
2630 )
2632 logger.info(
2633 "get_agent_matches.done",
2634 team=team,
2635 age_group=age_group,
2636 count=len(results),
2637 )
2638 return results
2640 def get_agent_season_matches(
2641 self,
2642 season_id: int,
2643 start_date: str | None = None,
2644 end_date: str | None = None,
2645 league_ids: list[int] | None = None,
2646 page: int = 0,
2647 page_size: int = AGENT_SEASON_PAGE,
2648 include_test: bool = False,
2649 ) -> list[dict]:
2650 """One page of a season's matches for the reconcile (SB-1787).
2652 match-scraper's reconcile compares past MT matches with the official
2653 feed and resends what differs. It needs every match in the window, not
2654 one team's, so this pages: page `n` is rows `n * page_size` onwards in
2655 (match_date, id) order. The caller asks for pages 0, 1, 2… and stops at
2656 the first **empty** page — not a short one — and reads every page
2657 before sending a change, because a re-dated match moves between pages.
2659 A page is filled with `.range()` until it holds `page_size` rows or the
2660 database has no more, so a server whose max_rows is below the page size
2661 still returns full pages and the offsets of later pages stay right.
2663 `league_ids` keeps matches whose division is in one of those leagues;
2664 that leaves out tournament and other division-less matches, which have
2665 no league. Every status is returned, cancelled included: whether a
2666 difference is worth resending is the reconcile's call.
2668 `entered_by_person` is whether `source` is outside FEED_SOURCES — the
2669 row was entered by a person, the same test the ingest worker uses.
2670 updated_by is not the signal (the legacy sync endpoint stamps it for the
2671 scraper, and any edit sets it for good) and is not returned. A person
2672 who edits a *scraped* row's score is not visible here until a score
2673 provenance column exists.
2675 Raises on a database error: "could not read" must not look like "no
2676 matches", or the reconcile would conclude MT is missing the season.
2677 """
2678 page_size = max(1, min(int(page_size), AGENT_SEASON_PAGE_MAX))
2679 start = max(0, int(page)) * page_size
2681 columns = _AGENT_SEASON_COLUMNS + (
2682 ", division:divisions!inner(league_id)" if league_ids else ", division:divisions(league_id)"
2683 )
2685 rows: list[dict] = []
2686 while len(rows) < page_size:
2687 query = self.client.table(MATCHES_READ_RELATION).select(columns).eq("season_id", season_id)
2688 if league_ids:
2689 query = query.in_("division.league_id", list(league_ids))
2690 if not include_test: 2690 ↛ 2692line 2690 didn't jump to line 2692 because the condition on line 2690 was always true
2691 query = query.eq("is_test", False)
2692 if start_date:
2693 query = query.gte("match_date", start_date)
2694 if end_date:
2695 query = query.lte("match_date", end_date)
2696 offset = start + len(rows)
2697 chunk = (query.order("match_date").order("id").range(offset, start + page_size - 1).execute()).data or []
2698 if not chunk:
2699 break
2700 rows.extend(chunk)
2702 return [
2703 {
2704 "id": m["id"],
2705 "match_id": m.get("match_id"),
2706 "match_date": m.get("match_date"),
2707 "match_status": m.get("match_status"),
2708 "home_team_id": m.get("home_team_id"),
2709 "home_team_name": (m.get("home_team") or {}).get("name"),
2710 "away_team_id": m.get("away_team_id"),
2711 "away_team_name": (m.get("away_team") or {}).get("name"),
2712 "home_score": m.get("home_score"),
2713 "away_score": m.get("away_score"),
2714 "home_penalty_score": m.get("home_penalty_score"),
2715 "away_penalty_score": m.get("away_penalty_score"),
2716 "division_id": m.get("division_id"),
2717 "league_id": (m.get("division") or {}).get("league_id"),
2718 "match_type": (m.get("match_type") or {}).get("name"),
2719 "source": m.get("source"),
2720 "entered_by_person": (m.get("source") or "match-scraper") not in FEED_SOURCES,
2721 "score_locked": bool(m.get("score_locked")),
2722 }
2723 for m in rows[:page_size]
2724 ]
2726 def cancel_match(
2727 self,
2728 home_team: str,
2729 away_team: str,
2730 match_date: str,
2731 age_group: str,
2732 league: str,
2733 division: str,
2734 season: str,
2735 ) -> bool:
2736 """Mark a match as cancelled by natural key.
2738 Only cancels matches with no score (home_score IS NULL) to avoid
2739 accidentally cancelling completed matches.
2741 Returns True if a match was found and cancelled, False if not found.
2742 """
2743 # Resolve dimension IDs (same pattern as get_agent_matches)
2744 season_resp = self.client.table("seasons").select("id").eq("name", season).limit(1).execute()
2745 if not season_resp.data:
2746 logger.warning("cancel_match.season_not_found", season=season)
2747 return False
2748 season_id = season_resp.data[0]["id"]
2750 ag_resp = self.client.table("age_groups").select("id").eq("name", age_group).limit(1).execute()
2751 if not ag_resp.data:
2752 logger.warning("cancel_match.age_group_not_found", age_group=age_group)
2753 return False
2754 age_group_id = ag_resp.data[0]["id"]
2756 div_resp = (
2757 self.client.table("divisions")
2758 .select("id, leagues!divisions_league_id_fkey(name)")
2759 .eq("name", division)
2760 .execute()
2761 )
2762 division_id = None
2763 for row in div_resp.data or []:
2764 if row.get("leagues") and row["leagues"].get("name") == league:
2765 division_id = row["id"]
2766 break
2767 if division_id is None:
2768 logger.warning("cancel_match.division_not_found", division=division, league=league)
2769 return False
2771 home_resp = self.client.table("teams").select("id").eq("name", home_team).execute()
2772 home_ids = [r["id"] for r in (home_resp.data or [])]
2773 away_resp = self.client.table("teams").select("id").eq("name", away_team).execute()
2774 away_ids = [r["id"] for r in (away_resp.data or [])]
2775 if not home_ids or not away_ids:
2776 logger.warning("cancel_match.team_not_found", home_team=home_team, away_team=away_team)
2777 return False
2779 or_parts = [f"and(home_team_id.eq.{hid},away_team_id.eq.{aid})" for hid in home_ids for aid in away_ids]
2780 resp = (
2781 self.client.table("matches")
2782 .select("id, home_score")
2783 .eq("season_id", season_id)
2784 .eq("age_group_id", age_group_id)
2785 .eq("division_id", division_id)
2786 .eq("match_date", match_date)
2787 .is_("home_score", "null") # safety: never cancel scored matches
2788 .or_(",".join(or_parts))
2789 .limit(1)
2790 .execute()
2791 )
2793 if not resp.data:
2794 logger.warning(
2795 "cancel_match.not_found",
2796 home_team=home_team,
2797 away_team=away_team,
2798 match_date=match_date,
2799 )
2800 return False
2802 internal_id = resp.data[0]["id"]
2803 self.client.table("matches").update({"match_status": "cancelled"}).eq("id", internal_id).execute()
2804 logger.info(
2805 "cancel_match.done",
2806 internal_id=internal_id,
2807 home_team=home_team,
2808 away_team=away_team,
2809 match_date=match_date,
2810 )
2811 return True
2813 # Admin CRUD methods for reference data have been moved to:
2814 # - SeasonDAO (seasons, age_groups)
2815 # - LeagueDAO (leagues, divisions)
2816 # - MatchTypeDAO (match_types)
2817 # Team methods moved to TeamDAO - see dao/team_dao.py
2818 # Club methods moved to ClubDAO - see dao/club_dao.py
2819 # User profile and player methods moved to PlayerDAO - see dao/player_dao.py