Coverage for dao/player_stats_dao.py: 39.28%
279 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Player Stats Data Access Object.
4Handles all database operations for player statistics:
5- Per-match stats (player_match_stats table)
6- Season aggregations
7- Goal increment/decrement for live game
8"""
10import structlog
12from dao.base_dao import MATCHES_READ_RELATION, BaseDAO, dao_cache, invalidates_cache
14logger = structlog.get_logger()
16# Cache patterns for invalidation
17STATS_CACHE_PATTERN = "mt:dao:stats:*"
20# Statuses that mean the match was actually contested. `scheduled`, `postponed`
21# and `cancelled` never happened, so nothing recorded against them is an
22# appearance (SB-671).
23#
24# `forfeit` is included for the same reason get_goals_leaderboard includes it —
25# a forfeited match can still have been played, and can carry real goals.
26#
27# `live` is included here and deliberately *not* in get_goals_leaderboard. A
28# squad's own board should move as its match is played, which is the whole point
29# of recording starters at kickoff; a league-wide leaderboard should not reorder
30# itself mid-match. Same column, different question.
31PLAYED_STATUSES = ("live", "completed", "forfeit")
34class PlayerStatsDAO(BaseDAO):
35 """Data access object for player statistics operations."""
37 # === Read Operations ===
39 def get_match_stats(self, player_id: int, match_id: int) -> dict | None:
40 """
41 Get stats for a player in a specific match.
43 Args:
44 player_id: Player ID
45 match_id: Match ID
47 Returns:
48 Stats dict or None if not found
49 """
50 try:
51 response = (
52 self.client.table("player_match_stats")
53 .select("*")
54 .eq("player_id", player_id)
55 .eq("match_id", match_id)
56 .execute()
57 )
59 if response.data and len(response.data) > 0:
60 return response.data[0]
61 return None
63 except Exception as e:
64 logger.error("stats_get_match_error", player_id=player_id, match_id=match_id, error=str(e))
65 return None
67 @invalidates_cache(STATS_CACHE_PATTERN)
68 def get_or_create_match_stats(self, player_id: int, match_id: int) -> dict | None:
69 """
70 Get or create stats record for a player in a match.
72 Used when recording stats - ensures a record exists.
74 Args:
75 player_id: Player ID
76 match_id: Match ID
78 Returns:
79 Stats dict (existing or newly created)
80 """
81 try:
82 # Try to get existing
83 existing = self.get_match_stats(player_id, match_id)
84 if existing: 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true
85 return existing
87 # Create new record with defaults
88 response = (
89 self.client.table("player_match_stats")
90 .insert(
91 {
92 "player_id": player_id,
93 "match_id": match_id,
94 "started": False,
95 "played": False,
96 "minutes_played": 0,
97 "goals": 0,
98 }
99 )
100 .execute()
101 )
103 if response.data and len(response.data) > 0:
104 logger.info("stats_record_created", player_id=player_id, match_id=match_id)
105 return response.data[0]
106 return None
108 except Exception as e:
109 logger.error("stats_get_or_create_error", player_id=player_id, match_id=match_id, error=str(e))
110 return None
112 @dao_cache("stats:player:{player_id}:season:{season_id}:test{include_test}:mt{match_type_id}")
113 def get_player_season_stats(
114 self,
115 player_id: int,
116 season_id: int,
117 include_test: bool = False,
118 match_type_id: int | list[int] | None = None,
119 ) -> dict | None:
120 """
121 Get aggregated stats for a player across a season.
123 Args:
124 player_id: Player ID
125 season_id: Season ID
126 include_test: SB-591 test partition. Minutes and goals from a test
127 match must not inflate a real player's season totals, so this is
128 part of the cache key.
129 match_type_id: Restrict to one competition — league, friendly,
130 tournament. None means all of them. It is part of the cache key
131 for the same reason include_test is: without it a league-only
132 request would be served an all-competitions total (SB-433). A
133 list totals several competitions, e.g. League + Flex (SB-1599).
135 Returns:
136 Aggregated stats dict with games_played, games_started,
137 total_minutes, total_goals
138 """
139 try:
140 # Get all match stats for this player where match is in the season
141 # Need to join with matches to filter by season
142 response = (
143 self.client.table("player_match_stats")
144 .select(f"""
145 *,
146 match:{MATCHES_READ_RELATION}!inner(id, season_id, is_test, match_type_id, match_status)
147 """)
148 .eq("player_id", player_id)
149 .eq("match.season_id", season_id)
150 .execute()
151 )
153 stats = response.data or []
154 if not include_test:
155 stats = [s for s in stats if not (s.get("match") or {}).get("is_test")]
156 if match_type_id is not None:
157 wanted = {match_type_id} if isinstance(match_type_id, int) else set(match_type_id)
158 stats = [s for s in stats if (s.get("match") or {}).get("match_type_id") in wanted]
160 # Only matches that actually happened. A lineup saved for a
161 # scheduled match, or a match started and then reverted to
162 # scheduled, leaves appearance rows behind that nothing cleans up —
163 # so the aggregation asks whether the match was played rather than
164 # trusting the rows to be tidy (SB-671). This also repairs existing
165 # data, which a cleanup hook could not.
166 stats = [s for s in stats if (s.get("match") or {}).get("match_status") in PLAYED_STATUSES]
168 # Aggregate - only count games where player actually participated
169 games_played = sum(1 for s in stats if s.get("played") or s.get("started"))
170 games_started = sum(1 for s in stats if s.get("started"))
171 total_minutes = sum(s.get("minutes_played", 0) for s in stats)
172 total_goals = sum(s.get("goals", 0) for s in stats)
173 # assists and cards have been columns on player_match_stats all along;
174 # they simply weren't summed here, so nothing downstream could show
175 # them (SB-433).
176 total_assists = sum(s.get("assists", 0) for s in stats)
177 total_yellow_cards = sum(s.get("yellow_cards", 0) for s in stats)
178 total_red_cards = sum(s.get("red_cards", 0) for s in stats)
180 return {
181 "player_id": player_id,
182 "season_id": season_id,
183 "games_played": games_played,
184 "games_started": games_started,
185 "total_minutes": total_minutes,
186 "total_goals": total_goals,
187 "total_assists": total_assists,
188 "total_yellow_cards": total_yellow_cards,
189 "total_red_cards": total_red_cards,
190 }
192 except Exception as e:
193 logger.error("stats_season_error", player_id=player_id, season_id=season_id, error=str(e))
194 return None
196 @dao_cache("stats:team:{team_id}:season:{season_id}:test{include_test}:mt{match_type_id}:age{age_group_id}")
197 def get_team_stats(
198 self,
199 team_id: int,
200 season_id: int,
201 include_test: bool = False,
202 match_type_id: int | list[int] | None = None,
203 age_group_id: int | None = None,
204 ) -> list[dict]:
205 """
206 Get aggregated stats for all players on a team for a season.
208 Args:
209 team_id: Team ID
210 season_id: Season ID
211 include_test: SB-591 test partition gate, threaded through to each
212 player's season aggregation.
213 match_type_id: Restrict to one competition, or a list of them to
214 total several (SB-1599); None means all. Part of the cache key,
215 or a league-only request gets served an all-competitions total
216 (SB-433).
217 age_group_id: Restrict the squad to players whose
218 `players.age_group_id` matches — the same rule as the roster
219 (SB-68), so a multi-age team's board lists the same players as
220 its Roster tab. None means every age group (SB-1258).
222 Returns:
223 List of player stats dicts sorted by goals (descending)
224 """
225 try:
226 # First get all players on this team/season
227 query = (
228 self.client.table("players")
229 .select("id, jersey_number, first_name, last_name")
230 .eq("team_id", team_id)
231 .eq("season_id", season_id)
232 .eq("is_active", True)
233 )
234 if age_group_id is not None:
235 query = query.eq("age_group_id", age_group_id)
237 players = query.execute().data or []
239 result = []
240 for player in players:
241 # Get season stats for each player
242 stats = self.get_player_season_stats(
243 player["id"], season_id, include_test=include_test, match_type_id=match_type_id
244 )
245 if stats: 245 ↛ 240line 245 didn't jump to line 240 because the condition on line 245 was always true
246 result.append(
247 {
248 "player_id": player["id"],
249 "jersey_number": player["jersey_number"],
250 "first_name": player.get("first_name"),
251 "last_name": player.get("last_name"),
252 "games_played": stats["games_played"],
253 "games_started": stats["games_started"],
254 "total_minutes": stats["total_minutes"],
255 "total_goals": stats["total_goals"],
256 "total_assists": stats["total_assists"],
257 "total_yellow_cards": stats["total_yellow_cards"],
258 "total_red_cards": stats["total_red_cards"],
259 }
260 )
262 # Sort by goals descending
263 result.sort(key=lambda x: x["total_goals"], reverse=True)
264 return result
266 except Exception as e:
267 logger.error("stats_team_error", team_id=team_id, season_id=season_id, error=str(e))
268 return []
270 @dao_cache(
271 "stats:leaderboard:goals:s{season_id}:l{league_id}:d{division_id}:a{age_group_id}:mt{match_type_id}:t{tournament_id}:lim{limit}:test{include_test}"
272 )
273 def get_goals_leaderboard(
274 self,
275 season_id: int,
276 league_id: int | None = None,
277 division_id: int | None = None,
278 age_group_id: int | None = None,
279 match_type_id: int | list[int] | None = None,
280 tournament_id: int | None = None,
281 limit: int = 50,
282 include_test: bool = False,
283 ) -> list[dict]:
284 """
285 Get top goal scorers filtered by league/division/age group/match type/tournament.
287 Args:
288 season_id: Season ID (required)
289 league_id: Optional league filter
290 division_id: Optional division filter
291 age_group_id: Optional age group filter
292 match_type_id: Optional match type filter (e.g. 4 for Playoff). A list
293 totals several types, e.g. League + Flex (SB-1594).
294 tournament_id: Optional specific tournament filter (matches.tournament_id)
295 limit: Maximum results (default 50)
297 Returns:
298 List of player dicts with goals stats, ranked by goals descending
299 """
300 try:
301 # Build the query using Supabase RPC or raw SQL
302 # Since Supabase Python SDK doesn't support complex aggregations well,
303 # we'll fetch the data and aggregate in Python
305 # Get all player match stats for matches in this season
306 query = (
307 self.client.table("player_match_stats")
308 .select("""
309 player_id,
310 goals,
311 started,
312 played,
313 match:matches_with_test!inner(
314 id,
315 season_id,
316 match_status,
317 match_type_id,
318 tournament_id,
319 division_id,
320 age_group_id,
321 is_test,
322 division:divisions(
323 id,
324 league_id
325 )
326 ),
327 player:players!inner(
328 id,
329 jersey_number,
330 first_name,
331 last_name,
332 team_id,
333 team:teams(
334 id,
335 name
336 )
337 )
338 """)
339 .eq("match.season_id", season_id)
340 )
342 # Apply optional filters
343 if division_id is not None: 343 ↛ 344line 343 didn't jump to line 344 because the condition on line 343 was never true
344 query = query.eq("match.division_id", division_id)
345 if age_group_id is not None: 345 ↛ 346line 345 didn't jump to line 346 because the condition on line 345 was never true
346 query = query.eq("match.age_group_id", age_group_id)
348 response = query.execute()
349 stats = response.data or []
351 # Filter in Python since PostgREST nested filters on !inner joins are unreliable
352 # Include completed and forfeit matches (forfeit matches can have real goals)
353 stats = [s for s in stats if s.get("match", {}).get("match_status") in ("completed", "forfeit")]
354 # SB-591 test partition: a goal scored in a test match must never
355 # reach a real viewer's leaderboard. Filtered here rather than in the
356 # query for the same reason as the status filter above.
357 if not include_test: 357 ↛ 359line 357 didn't jump to line 359 because the condition on line 357 was always true
358 stats = [s for s in stats if not s.get("match", {}).get("is_test")]
359 if match_type_id is not None:
360 wanted = {match_type_id} if isinstance(match_type_id, int) else set(match_type_id)
361 if wanted: 361 ↛ 363line 361 didn't jump to line 363 because the condition on line 361 was always true
362 stats = [s for s in stats if s.get("match", {}).get("match_type_id") in wanted]
363 if tournament_id is not None: 363 ↛ 364line 363 didn't jump to line 364 because the condition on line 363 was never true
364 stats = [s for s in stats if s.get("match", {}).get("tournament_id") == tournament_id]
365 if league_id is not None: 365 ↛ 369line 365 didn't jump to line 369 because the condition on line 365 was never true
366 # For matches with a division, check division.league_id directly.
367 # For playoff matches (division_id is null), check if the player's
368 # team plays in this league by looking at their divisional matches.
369 league_team_ids = self._get_league_team_ids(league_id, season_id, include_test=include_test)
370 stats = [
371 s
372 for s in stats
373 if (s.get("match", {}).get("division") or {}).get("league_id") == league_id
374 or (
375 s.get("match", {}).get("division") is None
376 and s.get("player", {}).get("team_id") in league_team_ids
377 )
378 ]
380 # Aggregate by player
381 player_goals: dict[int, dict] = {}
382 for stat in stats:
383 player = stat.get("player")
384 if not player: 384 ↛ 385line 384 didn't jump to line 385 because the condition on line 384 was never true
385 continue
387 player_id = player["id"]
388 goals = stat.get("goals", 0)
390 if player_id not in player_goals:
391 team = player.get("team", {}) or {}
392 player_goals[player_id] = {
393 "player_id": player_id,
394 "jersey_number": player.get("jersey_number"),
395 "first_name": player.get("first_name"),
396 "last_name": player.get("last_name"),
397 "team_id": player.get("team_id"),
398 "team_name": team.get("name"),
399 "goals": 0,
400 "games_played": 0,
401 }
403 player_goals[player_id]["goals"] += goals
404 if stat.get("played") or stat.get("started"): 404 ↛ 382line 404 didn't jump to line 382 because the condition on line 404 was always true
405 player_goals[player_id]["games_played"] += 1
407 # Filter out players with 0 goals and sort
408 result = [p for p in player_goals.values() if p["goals"] > 0]
409 result.sort(key=lambda x: (-x["goals"], x["games_played"]))
411 # Calculate goals per game and add rank
412 for i, player in enumerate(result[:limit], start=1):
413 player["rank"] = i
414 games = player["games_played"]
415 player["goals_per_game"] = round(player["goals"] / games, 2) if games > 0 else 0.0
417 return result[:limit]
419 except Exception:
420 logger.exception(
421 "stats_goals_leaderboard_error",
422 season_id=season_id,
423 league_id=league_id,
424 division_id=division_id,
425 age_group_id=age_group_id,
426 match_type_id=match_type_id,
427 tournament_id=tournament_id,
428 )
429 raise
431 def _get_league_team_ids(self, league_id: int, season_id: int, include_test: bool = False) -> set[int]:
432 """Get team IDs that participate in a league via their divisional matches.
434 Used to attribute playoff goals (which have no division) to the correct league.
436 include_test gates the SB-591 test partition. A test club entered into a
437 real division would otherwise pull its team into the real leaderboard's
438 universe via this lookup.
439 """
440 try:
441 # Get divisions belonging to this league
442 div_response = self.client.table("divisions").select("id").eq("league_id", league_id).execute()
443 division_ids = [d["id"] for d in (div_response.data or [])]
444 if not division_ids:
445 return set()
447 # Get teams that have matches in those divisions for this season
448 matches_query = (
449 self.client.table(MATCHES_READ_RELATION)
450 .select("home_team_id, away_team_id")
451 .eq("season_id", season_id)
452 .in_("division_id", division_ids)
453 )
454 if not include_test:
455 matches_query = matches_query.eq("is_test", False)
456 matches_response = matches_query.execute()
457 team_ids = set()
458 for m in matches_response.data or []:
459 team_ids.add(m["home_team_id"])
460 team_ids.add(m["away_team_id"])
461 return team_ids
463 except Exception:
464 logger.exception("stats_get_league_team_ids_error", league_id=league_id)
465 return set()
467 def get_team_match_stats(self, match_id: int, team_id: int) -> list[dict]:
468 """
469 Get player stats for a specific team in a match, joined with player info.
471 Args:
472 match_id: Match ID
473 team_id: Team ID
475 Returns:
476 List of player stats dicts with player details
477 """
478 try:
479 # Get all players on this team for the match's season
480 # First get the match to find the season
481 match_response = self.client.table("matches").select("season_id").eq("id", match_id).single().execute()
482 if not match_response.data:
483 return []
485 season_id = match_response.data["season_id"]
487 # Get all players on the team for this season
488 players_response = (
489 self.client.table("players")
490 .select("id, jersey_number, first_name, last_name")
491 .eq("team_id", team_id)
492 .eq("season_id", season_id)
493 .eq("is_active", True)
494 .order("jersey_number")
495 .execute()
496 )
498 players = players_response.data or []
500 # Get existing stats for these players in this match
501 player_ids = [p["id"] for p in players]
502 if not player_ids:
503 return []
505 stats_response = (
506 self.client.table("player_match_stats")
507 .select("*")
508 .eq("match_id", match_id)
509 .in_("player_id", player_ids)
510 .execute()
511 )
513 stats_by_player = {s["player_id"]: s for s in (stats_response.data or [])}
515 # Merge player info with stats
516 result = []
517 for player in players:
518 stats = stats_by_player.get(player["id"], {})
519 result.append(
520 {
521 "player_id": player["id"],
522 "jersey_number": player["jersey_number"],
523 "first_name": player.get("first_name"),
524 "last_name": player.get("last_name"),
525 "started": stats.get("started", False),
526 "played": stats.get("played", False),
527 "minutes_played": stats.get("minutes_played", 0),
528 "goals": stats.get("goals", 0),
529 "yellow_cards": stats.get("yellow_cards", 0),
530 "red_cards": stats.get("red_cards", 0),
531 }
532 )
534 return result
536 except Exception as e:
537 logger.error(
538 "stats_team_match_error",
539 match_id=match_id,
540 team_id=team_id,
541 error=str(e),
542 )
543 return []
545 @invalidates_cache(STATS_CACHE_PATTERN)
546 def batch_update_stats(self, match_id: int, player_stats: list[dict]) -> bool:
547 """
548 Batch upsert started/minutes_played for multiple players in a match.
550 Args:
551 match_id: Match ID
552 player_stats: List of dicts with player_id, started, minutes_played
554 Returns:
555 True if successful
556 """
557 try:
558 for entry in player_stats:
559 player_id = entry["player_id"]
560 # Ensure record exists
561 self.get_or_create_match_stats(player_id, match_id)
563 # Update started, played, minutes, and cards
564 played = entry.get("played", False) or entry["started"]
565 self.client.table("player_match_stats").update(
566 {
567 "started": entry["started"],
568 "played": played,
569 "minutes_played": entry["minutes_played"],
570 "yellow_cards": entry.get("yellow_cards", 0),
571 "red_cards": entry.get("red_cards", 0),
572 }
573 ).eq("player_id", player_id).eq("match_id", match_id).execute()
575 logger.info(
576 "stats_batch_updated",
577 match_id=match_id,
578 player_count=len(player_stats),
579 )
580 return True
582 except Exception as e:
583 logger.error(
584 "stats_batch_update_error",
585 match_id=match_id,
586 error=str(e),
587 )
588 return False
590 # === Update Operations ===
592 @invalidates_cache(STATS_CACHE_PATTERN)
593 def increment_goals(self, player_id: int, match_id: int) -> dict | None:
594 """
595 Increment goal count for a player in a match.
597 Creates stats record if it doesn't exist.
599 Args:
600 player_id: Player ID
601 match_id: Match ID
603 Returns:
604 Updated stats dict
605 """
606 try:
607 # Ensure record exists
608 stats = self.get_or_create_match_stats(player_id, match_id)
609 if not stats:
610 return None
612 current_goals = stats.get("goals", 0)
614 response = (
615 self.client.table("player_match_stats")
616 .update({"goals": current_goals + 1, "played": True})
617 .eq("player_id", player_id)
618 .eq("match_id", match_id)
619 .execute()
620 )
622 if response.data and len(response.data) > 0:
623 logger.info(
624 "stats_goal_incremented",
625 player_id=player_id,
626 match_id=match_id,
627 new_total=current_goals + 1,
628 )
629 return response.data[0]
630 return None
632 except Exception as e:
633 logger.error("stats_increment_goals_error", player_id=player_id, match_id=match_id, error=str(e))
634 return None
636 @invalidates_cache(STATS_CACHE_PATTERN)
637 def decrement_goals(self, player_id: int, match_id: int) -> dict | None:
638 """
639 Decrement goal count for a player in a match.
641 Won't go below 0.
643 Args:
644 player_id: Player ID
645 match_id: Match ID
647 Returns:
648 Updated stats dict
649 """
650 try:
651 stats = self.get_match_stats(player_id, match_id)
652 if not stats:
653 return None
655 current_goals = stats.get("goals", 0)
656 new_goals = max(0, current_goals - 1)
658 response = (
659 self.client.table("player_match_stats")
660 .update({"goals": new_goals})
661 .eq("player_id", player_id)
662 .eq("match_id", match_id)
663 .execute()
664 )
666 if response.data and len(response.data) > 0:
667 logger.info(
668 "stats_goal_decremented",
669 player_id=player_id,
670 match_id=match_id,
671 new_total=new_goals,
672 )
673 return response.data[0]
674 return None
676 except Exception as e:
677 logger.error("stats_decrement_goals_error", player_id=player_id, match_id=match_id, error=str(e))
678 return None
680 @invalidates_cache(STATS_CACHE_PATTERN)
681 def increment_assists(self, player_id: int, match_id: int) -> dict | None:
682 """
683 Increment assist count for a player in a match.
685 Creates stats record if it doesn't exist.
687 Args:
688 player_id: Player ID
689 match_id: Match ID
691 Returns:
692 Updated stats dict
693 """
694 try:
695 stats = self.get_or_create_match_stats(player_id, match_id)
696 if not stats:
697 return None
699 current_assists = stats.get("assists", 0)
701 response = (
702 self.client.table("player_match_stats")
703 .update({"assists": current_assists + 1, "played": True})
704 .eq("player_id", player_id)
705 .eq("match_id", match_id)
706 .execute()
707 )
709 if response.data and len(response.data) > 0:
710 logger.info(
711 "stats_assist_incremented",
712 player_id=player_id,
713 match_id=match_id,
714 new_total=current_assists + 1,
715 )
716 return response.data[0]
717 return None
719 except Exception as e:
720 logger.error("stats_increment_assists_error", player_id=player_id, match_id=match_id, error=str(e))
721 return None
723 @invalidates_cache(STATS_CACHE_PATTERN)
724 def decrement_assists(self, player_id: int, match_id: int) -> dict | None:
725 """
726 Decrement assist count for a player in a match.
728 Won't go below 0.
730 Args:
731 player_id: Player ID
732 match_id: Match ID
734 Returns:
735 Updated stats dict
736 """
737 try:
738 stats = self.get_match_stats(player_id, match_id)
739 if not stats:
740 return None
742 current_assists = stats.get("assists", 0)
743 new_assists = max(0, current_assists - 1)
745 response = (
746 self.client.table("player_match_stats")
747 .update({"assists": new_assists})
748 .eq("player_id", player_id)
749 .eq("match_id", match_id)
750 .execute()
751 )
753 if response.data and len(response.data) > 0:
754 logger.info(
755 "stats_assist_decremented",
756 player_id=player_id,
757 match_id=match_id,
758 new_total=new_assists,
759 )
760 return response.data[0]
761 return None
763 except Exception as e:
764 logger.error("stats_decrement_assists_error", player_id=player_id, match_id=match_id, error=str(e))
765 return None
767 @invalidates_cache(STATS_CACHE_PATTERN)
768 def set_started(self, player_id: int, match_id: int, started: bool) -> dict | None:
769 """
770 Set whether a player started a match.
772 Args:
773 player_id: Player ID
774 match_id: Match ID
775 started: True if player started
777 Returns:
778 Updated stats dict
779 """
780 try:
781 # Ensure record exists
782 self.get_or_create_match_stats(player_id, match_id)
784 update_data = {"started": started}
785 if started:
786 update_data["played"] = True
788 response = (
789 self.client.table("player_match_stats")
790 .update(update_data)
791 .eq("player_id", player_id)
792 .eq("match_id", match_id)
793 .execute()
794 )
796 if response.data and len(response.data) > 0:
797 logger.info("stats_started_updated", player_id=player_id, match_id=match_id, started=started)
798 return response.data[0]
799 return None
801 except Exception as e:
802 logger.error("stats_set_started_error", player_id=player_id, match_id=match_id, error=str(e))
803 return None
805 @invalidates_cache(STATS_CACHE_PATTERN)
806 def get_starter_ids(self, match_id: int) -> list[int]:
807 """Players recorded as starters for a match (set at kickoff, SB-671)."""
808 response = (
809 self.client.table("player_match_stats")
810 .select("player_id")
811 .eq("match_id", match_id)
812 .eq("started", True)
813 .execute()
814 )
815 return [row["player_id"] for row in (response.data or [])]
817 @invalidates_cache(STATS_CACHE_PATTERN)
818 def mark_played(self, player_id: int, match_id: int) -> None:
819 """Record that a player appeared — e.g. came on as a substitute (SB-1227)."""
820 self.get_or_create_match_stats(player_id, match_id)
821 self.client.table("player_match_stats").update({"played": True}).eq("player_id", player_id).eq(
822 "match_id", match_id
823 ).execute()
825 @invalidates_cache(STATS_CACHE_PATTERN)
826 def record_minutes(self, match_id: int, minutes_by_player: dict[int, int]) -> None:
827 """Write derived minutes for each player who appeared (SB-1227)."""
828 for player_id, minutes in minutes_by_player.items():
829 self.get_or_create_match_stats(player_id, match_id)
830 self.client.table("player_match_stats").update({"minutes_played": minutes, "played": True}).eq(
831 "player_id", player_id
832 ).eq("match_id", match_id).execute()
833 logger.info("stats_minutes_recorded", match_id=match_id, players=len(minutes_by_player))
835 def update_minutes(self, player_id: int, match_id: int, minutes: int) -> dict | None:
836 """
837 Update minutes played for a player in a match.
839 Args:
840 player_id: Player ID
841 match_id: Match ID
842 minutes: Minutes played
844 Returns:
845 Updated stats dict
846 """
847 try:
848 # Ensure record exists
849 self.get_or_create_match_stats(player_id, match_id)
851 response = (
852 self.client.table("player_match_stats")
853 .update({"minutes_played": minutes})
854 .eq("player_id", player_id)
855 .eq("match_id", match_id)
856 .execute()
857 )
859 if response.data and len(response.data) > 0:
860 logger.info("stats_minutes_updated", player_id=player_id, match_id=match_id, minutes=minutes)
861 return response.data[0]
862 return None
864 except Exception as e:
865 logger.error("stats_update_minutes_error", player_id=player_id, match_id=match_id, error=str(e))
866 return None
868 # === Batch Operations ===
870 @invalidates_cache(STATS_CACHE_PATTERN)
871 def record_match_appearance(
872 self, player_id: int, match_id: int, started: bool = False, minutes: int = 0
873 ) -> dict | None:
874 """
875 Record a player's appearance in a match.
877 Convenience method to set started and minutes at once.
879 Args:
880 player_id: Player ID
881 match_id: Match ID
882 started: Whether player started
883 minutes: Minutes played
885 Returns:
886 Updated stats dict
887 """
888 try:
889 # Ensure record exists
890 self.get_or_create_match_stats(player_id, match_id)
892 response = (
893 self.client.table("player_match_stats")
894 .update({"started": started, "played": True, "minutes_played": minutes})
895 .eq("player_id", player_id)
896 .eq("match_id", match_id)
897 .execute()
898 )
900 if response.data and len(response.data) > 0:
901 logger.info(
902 "stats_appearance_recorded",
903 player_id=player_id,
904 match_id=match_id,
905 started=started,
906 minutes=minutes,
907 )
908 return response.data[0]
909 return None
911 except Exception as e:
912 logger.error(
913 "stats_record_appearance_error",
914 player_id=player_id,
915 match_id=match_id,
916 error=str(e),
917 )
918 return None