Coverage for dao/season_dao.py: 47.37%
166 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""
2Season Data Access Object.
4Handles all database operations related to seasons and age groups including:
5- Season CRUD operations
6- Age group CRUD operations
7- Current/active season queries
8"""
10from datetime import date
12import structlog
14from dao.base_dao import MATCHES_READ_RELATION, BaseDAO, dao_cache, invalidates_cache
16logger = structlog.get_logger()
18# Cache patterns for invalidation
19SEASONS_CACHE_PATTERN = "mt:dao:seasons:*"
20AGE_GROUPS_CACHE_PATTERN = "mt:dao:age_groups:*"
21# Rosters and current-team lookups are resolved against the current season
22# (SB-441/SB-442), so they go stale the moment it changes. Their cache keys
23# carry no season component and live for 24h, which would otherwise leave every
24# roster wrong for a day right when it matters most.
25PLAYERS_CACHE_PATTERN = "mt:dao:players:*"
28class SeasonDAO(BaseDAO):
29 """Data access object for season and age group operations."""
31 # === Age Group Query Methods ===
33 @dao_cache("age_groups:all")
34 def get_all_age_groups(self) -> list[dict]:
35 """Get all age groups."""
36 try:
37 response = self.client.table("age_groups").select("*").order("name").execute()
38 return response.data
39 except Exception:
40 logger.exception("Error querying age groups")
41 return []
43 def get_age_group_by_name(self, name: str) -> dict | None:
44 """Get an age group by name (case-insensitive exact match).
46 Returns the age group record (id, name).
47 For match-scraper integration, this helps look up age groups by name.
48 No caching - used for scraper lookups.
49 """
50 try:
51 response = (
52 self.client.table("age_groups")
53 .select("id, name")
54 .ilike("name", name) # Case-insensitive match
55 .limit(1)
56 .execute()
57 )
59 if response.data and len(response.data) > 0:
60 return response.data[0]
61 return None
63 except Exception:
64 logger.exception("Error getting age group by name", age_group_name=name)
65 return None
67 # === Age Group CRUD Methods ===
69 @invalidates_cache(AGE_GROUPS_CACHE_PATTERN)
70 def create_age_group(self, name: str) -> dict:
71 """Create a new age group."""
72 try:
73 result = self.client.table("age_groups").insert({"name": name}).execute()
74 return result.data[0]
75 except Exception as e:
76 logger.exception("Error creating age group")
77 raise e
79 @invalidates_cache(AGE_GROUPS_CACHE_PATTERN)
80 def update_age_group(self, age_group_id: int, name: str) -> dict | None:
81 """Update an age group."""
82 try:
83 result = self.client.table("age_groups").update({"name": name}).eq("id", age_group_id).execute()
84 return result.data[0] if result.data else None
85 except Exception as e:
86 logger.exception("Error updating age group")
87 raise e
89 @invalidates_cache(AGE_GROUPS_CACHE_PATTERN)
90 def delete_age_group(self, age_group_id: int) -> bool:
91 """Delete an age group."""
92 try:
93 result = self.client.table("age_groups").delete().eq("id", age_group_id).execute()
94 return len(result.data) > 0
95 except Exception as e:
96 logger.exception("Error deleting age group")
97 raise e
99 # === Season Query Methods ===
101 @dao_cache("seasons:all")
102 def get_all_seasons(self) -> list[dict]:
103 """Get all seasons."""
104 try:
105 response = self.client.table("seasons").select("*").order("start_date", desc=True).execute()
106 return response.data
107 except Exception:
108 logger.exception("Error querying seasons")
109 return []
111 @dao_cache("seasons:current")
112 def get_current_season(self) -> dict | None:
113 """Get the current season.
115 Prefers the admin-set `is_current` flag (exactly one season). Falls
116 back to the date-spanning season for older data that predates the
117 flag, so the off-season gap no longer yields None when a season is
118 flagged.
119 """
120 try:
121 flagged = self.client.table("seasons").select("*").eq("is_current", True).limit(1).execute()
122 if flagged.data:
123 return flagged.data[0]
125 # Legacy fallback: the season spanning today.
126 today = date.today().isoformat()
127 response = (
128 self.client.table("seasons")
129 .select("*")
130 .lte("start_date", today)
131 .gte("end_date", today)
132 .limit(1)
133 .execute()
134 )
135 return response.data[0] if response.data else None
136 except Exception as e:
137 logger.info("No current season found", error=str(e))
138 return None
140 def get_season_by_name(self, name: str) -> dict | None:
141 """The season with this exact name (e.g. "2025-2026"), or None.
143 Reads the cached full list rather than querying: a season load asks
144 this once per match, and the set of seasons changes once a year.
145 """
146 if not name:
147 return None
148 wanted = name.strip().casefold()
149 for season in self.get_all_seasons():
150 if (season.get("name") or "").strip().casefold() == wanted:
151 return season
152 return None
154 def get_current_season_id(self) -> int | None:
155 """Convenience: id of the current season, or None."""
156 season = self.get_current_season()
157 return season["id"] if season else None
159 @invalidates_cache(SEASONS_CACHE_PATTERN, PLAYERS_CACHE_PATTERN)
160 def set_current_season(self, season_id: int) -> dict | None:
161 """Mark one season current, clearing the flag from all others.
163 Two ordered updates — clear every current row, then set the target —
164 so the partial unique index (seasons_single_current) never sees two
165 TRUE values.
166 """
167 try:
168 self.client.table("seasons").update({"is_current": False}).eq("is_current", True).execute()
169 self.client.table("seasons").update({"is_current": True}).eq("id", season_id).execute()
170 return self.get_season_by_id(season_id)
171 except Exception as e:
172 logger.exception("Error setting current season")
173 raise e
175 def get_season_by_id(self, season_id: int) -> dict | None:
176 """Fetch a single season by id."""
177 try:
178 resp = self.client.table("seasons").select("*").eq("id", season_id).limit(1).execute()
179 return resp.data[0] if resp.data else None
180 except Exception:
181 logger.exception("Error fetching season by id")
182 return None
184 # Cache key lives in the `matches:` namespace so it's invalidated by
185 # MATCHES_CACHE_PATTERN whenever any match is created/updated/deleted.
186 @dao_cache("matches:counts_by_season:{include_test}")
187 def get_match_counts_by_season(self, include_test: bool = False) -> list[dict]:
188 """Return [{season_id, match_count}] for every season.
190 Backs the Admin → Seasons page (SB-61). The previous client-side
191 approach fetched all matches from /api/matches and filtered by
192 season_id, which silently capped at Supabase's 1000-row default and
193 showed bogus counts (always 1000 for the current season, 0 for
194 everything older).
196 One row per season; missing seasons (no matches) still appear with
197 match_count=0 — the seasons list is the source of truth, the count
198 is just a join.
200 include_test gates the SB-591 test partition; it is part of the cache
201 key so the two audiences never share a count.
202 """
203 try:
204 # PostgREST embedded resource with count: one round-trip for
205 # every season and its match count. Falls back to N+1 if the
206 # embedded count isn't accepted.
207 #
208 # The embed targets the matches_with_test view rather than the
209 # matches table so the test partition can be filtered inside the
210 # embedded resource (verified: the embedded is_test filter is
211 # applied to the count, not just the outer row).
212 query = self.client.table("seasons").select(
213 f"id, {MATCHES_READ_RELATION}(count)"
214 )
215 if not include_test:
216 query = query.eq(f"{MATCHES_READ_RELATION}.is_test", False)
217 response = query.execute()
218 counts = []
219 for row in response.data or []:
220 # comes back as a list of {count: N} when the embedded count
221 # modifier is honored.
222 matches_field = row.get(MATCHES_READ_RELATION) or []
223 if isinstance(matches_field, list) and matches_field:
224 match_count = matches_field[0].get("count") or 0
225 else:
226 match_count = 0
227 counts.append({"season_id": row["id"], "match_count": match_count})
228 return counts
229 except Exception:
230 logger.exception("Error querying match counts by season; falling back to N+1")
231 # Fallback: count per season individually. Seasons are few (<10
232 # in practice), so the extra round-trips are fine.
233 try:
234 seasons = (
235 self.client.table("seasons").select("id").execute().data or []
236 )
237 counts = []
238 for season in seasons:
239 sid = season["id"]
240 fallback = (
241 self.client.table(MATCHES_READ_RELATION)
242 .select("id", count="exact")
243 .eq("season_id", sid)
244 )
245 if not include_test: 245 ↛ 247line 245 didn't jump to line 247 because the condition on line 245 was always true
246 fallback = fallback.eq("is_test", False)
247 resp = fallback.limit(0).execute()
248 counts.append(
249 {"season_id": sid, "match_count": resp.count or 0}
250 )
251 return counts
252 except Exception:
253 logger.exception("Error in N+1 fallback for season match counts")
254 return []
256 @dao_cache("seasons:active")
257 def get_active_seasons(self) -> list[dict]:
258 """Get active seasons (current and future) for scheduling new matches."""
259 try:
260 today = date.today().isoformat()
262 response = (
263 self.client.table("seasons")
264 .select("*")
265 .gte("end_date", today)
266 .order("start_date", desc=False)
267 .execute()
268 )
270 return response.data
271 except Exception:
272 logger.exception("Error querying active seasons")
273 return []
275 # === Season CRUD Methods ===
277 @invalidates_cache(SEASONS_CACHE_PATTERN)
278 def create_season(
279 self, name: str, start_date: str, end_date: str, is_current: bool = False
280 ) -> dict:
281 """Create a new season. When is_current, it becomes the sole current season."""
282 try:
283 result = (
284 self.client.table("seasons")
285 .insert({"name": name, "start_date": start_date, "end_date": end_date})
286 .execute()
287 )
288 created = result.data[0]
289 if is_current:
290 return self.set_current_season(created["id"]) or created
291 return created
292 except Exception as e:
293 logger.exception("Error creating season")
294 raise e
296 @invalidates_cache(SEASONS_CACHE_PATTERN)
297 def update_season(
298 self,
299 season_id: int,
300 name: str,
301 start_date: str,
302 end_date: str,
303 is_current: bool | None = None,
304 ) -> dict | None:
305 """Update a season. is_current=True makes it the sole current season;
306 is_current is otherwise left untouched (pass explicitly to change it)."""
307 try:
308 result = (
309 self.client.table("seasons")
310 .update({"name": name, "start_date": start_date, "end_date": end_date})
311 .eq("id", season_id)
312 .execute()
313 )
314 updated = result.data[0] if result.data else None
315 if is_current:
316 return self.set_current_season(season_id) or updated
317 return updated
318 except Exception as e:
319 logger.exception("Error updating season")
320 raise e
322 @invalidates_cache(SEASONS_CACHE_PATTERN)
323 def delete_season(self, season_id: int) -> bool:
324 """Delete a season."""
325 try:
326 result = self.client.table("seasons").delete().eq("id", season_id).execute()
327 return len(result.data) > 0
328 except Exception as e:
329 logger.exception("Error deleting season")
330 raise e