Coverage for dao/club_dao.py: 52.02%
157 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
1"""
2Club Data Access Object.
4Handles all database operations related to clubs including:
5- Club CRUD operations
6- Club-team associations
7- Club queries and filters
8"""
10from collections import Counter
11from urllib.parse import urlparse
13import structlog
15from dao.base_dao import BaseDAO, clear_cache, dao_cache, invalidates_cache
17logger = structlog.get_logger()
19# Cache pattern for invalidation
20CLUBS_CACHE_PATTERN = "mt:dao:clubs:*"
22_PAGE = 1000
24LOGO_MISSING = "missing"
25LOGO_EXTERNAL = "external"
26LOGO_HOSTED = "hosted"
29def club_logo_prefix(supabase_url: str | None) -> str | None:
30 """The public URL every crest we host starts with, or None if unknown.
32 Derived from SUPABASE_URL rather than hardcoded, so local, prod and any
33 future project each recognise their own bucket (SB-1815).
34 """
35 base = (supabase_url or "").strip().rstrip("/")
36 if not base:
37 return None
38 return f"{base}/storage/v1/object/public/club-logos/"
41def versioned_url(public_url: str, version: int) -> str:
42 """`public_url` with `?v=<version>`, replacing any query it had (SB-1898).
44 A re-uploaded crest overwrites the same storage path, so an unchanged URL
45 keeps serving the old image from Cloudflare and browser caches. A new
46 version per upload makes the replacement visible at once. Storage's
47 `get_public_url` ends in a bare `?`, which this drops.
48 """
49 base = public_url.split("?", 1)[0]
50 return f"{base}?v={version}"
53def classify_logo(logo_url: str | None, prefix: str) -> str:
54 """missing, external (hot-linked from someone else's site), or hosted.
56 Scheme and host compare case-insensitively; the path does not, because
57 storage paths are case-sensitive.
58 """
59 url = (logo_url or "").strip()
60 if not url:
61 return LOGO_MISSING
62 parsed, expected = urlparse(url), urlparse(prefix)
63 same_origin = (parsed.scheme.lower(), parsed.netloc.lower()) == (
64 expected.scheme.lower(),
65 expected.netloc.lower(),
66 )
67 return LOGO_HOSTED if same_origin and parsed.path.startswith(expected.path) else LOGO_EXTERNAL
70def build_logo_gaps(
71 teams: list[dict],
72 clubs: list[dict],
73 match_counts: dict[int, int],
74 prefix: str,
75 scoped: bool = True,
76) -> dict:
77 """The three crest gaps, from rows already read (SB-1815).
79 With `scoped`, only teams with at least one match count, and only clubs
80 with at least one such team: a gap nobody sees is not the one to fix
81 first. Test clubs (is_test) and their teams are left out too — their
82 fixtures are real rows, so the match count alone does not exclude them.
83 Unscoped, every team and club is reported.
84 """
85 test_clubs = {c["id"] for c in clubs if c.get("is_test")}
86 in_scope = [
87 t for t in teams if not scoped or (match_counts.get(t["id"], 0) > 0 and t.get("club_id") not in test_clubs)
88 ]
90 teams_without_club = sorted(
91 (
92 {"id": t["id"], "name": t.get("name"), "match_count": match_counts.get(t["id"], 0)}
93 for t in in_scope
94 if t.get("club_id") is None
95 ),
96 key=lambda row: (-row["match_count"], row["name"] or ""),
97 )
99 club_ids = {t["club_id"] for t in in_scope if t.get("club_id") is not None}
100 clubs_without_logo: list[dict] = []
101 clubs_external_logo: list[dict] = []
102 for club in sorted(clubs, key=lambda c: c.get("name") or ""):
103 if scoped and club["id"] not in club_ids:
104 continue
105 status = classify_logo(club.get("logo_url"), prefix)
106 if status == LOGO_MISSING:
107 clubs_without_logo.append({"id": club["id"], "name": club.get("name")})
108 elif status == LOGO_EXTERNAL:
109 url = club["logo_url"].strip()
110 clubs_external_logo.append(
111 {"id": club["id"], "name": club.get("name"), "logo_url": url, "host": urlparse(url).hostname or ""}
112 )
114 return {
115 "teams_without_club": teams_without_club,
116 "clubs_without_logo": clubs_without_logo,
117 "clubs_external_logo": clubs_external_logo,
118 }
121class ClubDAO(BaseDAO):
122 """Data access object for club operations."""
124 # === Club Query Methods ===
126 @dao_cache("clubs:all:{include_team_counts}")
127 def get_all_clubs(self, include_team_counts: bool = True) -> list[dict]:
128 """Get all clubs with their associated teams count.
130 Args:
131 include_team_counts: If True, include team_count field for each club
133 Returns:
134 List of clubs from the clubs table.
135 """
136 response = self.client.table("clubs").select("*").order("name").execute()
137 clubs = response.data
139 if include_team_counts:
140 # Enrich with team counts (single query instead of N+1)
141 teams_response = self.client.table("teams").select("club_id").not_.is_("club_id", "null").execute()
142 team_counts = Counter(team["club_id"] for team in teams_response.data if team.get("club_id"))
143 for club in clubs:
144 club["team_count"] = team_counts.get(club["id"], 0)
146 return clubs
148 @dao_cache("clubs:for_team:{team_id}")
149 def get_club_for_team(self, team_id: int) -> dict | None:
150 """Get the club for a team.
152 Args:
153 team_id: The team ID
155 Returns:
156 Club dict if team belongs to a club, None otherwise
157 """
158 # Get the team to find its club_id
159 team_response = self.client.table("teams").select("club_id").eq("id", team_id).execute()
160 if not team_response.data or len(team_response.data) == 0:
161 return None
163 club_id = team_response.data[0].get("club_id")
164 if not club_id:
165 return None
167 # Get the club details
168 club_response = self.client.table("clubs").select("*").eq("id", club_id).execute()
169 if club_response.data and len(club_response.data) > 0:
170 return club_response.data[0]
171 return None
173 def get_club_by_name(self, name: str) -> dict | None:
174 """Get a club by name (exact match, case-sensitive).
176 Matches the clubs_name_unique DB constraint, which is `UNIQUE (name)`
177 case-sensitively. Used by the create-club endpoint to recover the
178 existing row when the DB raises that unique violation. Returns the
179 full club row if found, None otherwise.
180 """
181 response = self.client.table("clubs").select("*").eq("name", name).limit(1).execute()
182 if response.data and len(response.data) > 0:
183 return response.data[0]
184 return None
186 # === Club CRUD Methods ===
188 @invalidates_cache(CLUBS_CACHE_PATTERN)
189 def create_club(
190 self,
191 name: str,
192 city: str,
193 website: str | None = None,
194 description: str | None = None,
195 logo_url: str | None = None,
196 primary_color: str | None = None,
197 secondary_color: str | None = None,
198 pro_academy: bool = False,
199 ) -> dict:
200 """Create a new club.
202 Args:
203 name: Club name
204 city: Club city/location
205 website: Optional website URL
206 description: Optional description
207 logo_url: Optional URL to club logo in Supabase Storage
208 primary_color: Optional primary brand color (hex code)
209 secondary_color: Optional secondary brand color (hex code)
210 pro_academy: True for an MLS/professional club academy. Teams in
211 such a club field no U15 side — that cohort plays up into U16
212 — so a ragged age list is expected rather than a scrape gap.
214 Returns:
215 Created club dict
217 Raises:
218 ValueError: If club creation fails
219 """
220 club_data = {"name": name, "city": city}
221 if website: 221 ↛ 222line 221 didn't jump to line 222 because the condition on line 221 was never true
222 club_data["website"] = website
223 if description:
224 club_data["description"] = description
225 if logo_url: 225 ↛ 226line 225 didn't jump to line 226 because the condition on line 225 was never true
226 club_data["logo_url"] = logo_url
227 if primary_color: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 club_data["primary_color"] = primary_color
229 if secondary_color: 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true
230 club_data["secondary_color"] = secondary_color
231 # Written unconditionally, unlike the optional strings above: False is
232 # a real answer here, not an absent one.
233 club_data["pro_academy"] = pro_academy
235 result = self.client.table("clubs").insert(club_data).execute()
237 if not result.data or len(result.data) == 0: 237 ↛ 238line 237 didn't jump to line 238 because the condition on line 237 was never true
238 raise ValueError("Failed to create club")
240 return result.data[0]
242 @invalidates_cache(CLUBS_CACHE_PATTERN)
243 def update_club(
244 self,
245 club_id: int,
246 name: str | None = None,
247 city: str | None = None,
248 website: str | None = None,
249 description: str | None = None,
250 logo_url: str | None = None,
251 primary_color: str | None = None,
252 secondary_color: str | None = None,
253 pro_academy: bool | None = None,
254 ) -> dict | None:
255 """Update an existing club.
257 Args:
258 club_id: ID of club to update
259 name: Optional new name
260 city: Optional new city/location
261 website: Optional new website URL
262 description: Optional new description
263 logo_url: Optional URL to club logo in Supabase Storage
264 primary_color: Optional primary brand color (hex code)
265 secondary_color: Optional secondary brand color (hex code)
267 Returns:
268 Updated club dict or None if not found
269 """
270 update_data = {}
271 if name is not None:
272 update_data["name"] = name
273 if city is not None: 273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true
274 update_data["city"] = city
275 if website is not None: 275 ↛ 276line 275 didn't jump to line 276 because the condition on line 275 was never true
276 update_data["website"] = website
277 if description is not None: 277 ↛ 278line 277 didn't jump to line 278 because the condition on line 277 was never true
278 update_data["description"] = description
279 if logo_url is not None: 279 ↛ 280line 279 didn't jump to line 280 because the condition on line 279 was never true
280 update_data["logo_url"] = logo_url
281 if primary_color is not None: 281 ↛ 282line 281 didn't jump to line 282 because the condition on line 281 was never true
282 update_data["primary_color"] = primary_color
283 if secondary_color is not None: 283 ↛ 284line 283 didn't jump to line 284 because the condition on line 283 was never true
284 update_data["secondary_color"] = secondary_color
285 if pro_academy is not None:
286 update_data["pro_academy"] = pro_academy
288 if not update_data: 288 ↛ 289line 288 didn't jump to line 289 because the condition on line 288 was never true
289 return None
291 result = self.client.table("clubs").update(update_data).eq("id", club_id).execute()
293 if not result.data or len(result.data) == 0: 293 ↛ 294line 293 didn't jump to line 294 because the condition on line 293 was never true
294 return None
296 return result.data[0]
298 @invalidates_cache(CLUBS_CACHE_PATTERN)
299 def delete_club(self, club_id: int) -> bool:
300 """Delete a club.
302 Args:
303 club_id: The club ID to delete
305 Returns:
306 True if deleted successfully
308 Raises:
309 Exception: If deletion fails
311 Note:
312 This will fail if there are teams still associated with this club
313 due to ON DELETE RESTRICT constraint.
314 Invitations referencing this club are deleted first.
315 """
316 # Delete invitations referencing this club first (FK constraint)
317 self.client.table("invitations").delete().eq("club_id", club_id).execute()
318 # Now delete the club
319 self.client.table("clubs").delete().eq("id", club_id).execute()
320 return True
322 def merge_club(self, from_id: int, into_id: int, dry_run: bool = True) -> dict:
323 """Fold a duplicate club into its canonical club (SB-1822).
325 One transaction in the database (merge_club RPC): every reference is
326 repointed, the target's empty crest/colours are filled from the source,
327 and the source is deleted. A dry run reports the same counts and
328 changes nothing. A real run raises while the dry run lists blockers.
329 """
330 response = self.client.rpc("merge_club", {"p_from": from_id, "p_into": into_id, "p_dry_run": dry_run}).execute()
331 if not dry_run:
332 # Teams carry their club's crest and colours into every cached
333 # read, so nothing cached about either club is trustworthy now.
334 clear_cache("mt:dao:*")
335 return response.data or {}
337 # === Crest coverage (SB-1815) ===
339 def _paged(self, query_fn) -> list[dict]:
340 """Every row of a query, a page at a time (PostgREST caps a response)."""
341 rows: list[dict] = []
342 while True:
343 page = query_fn().order("id").range(len(rows), len(rows) + _PAGE - 1).execute().data or []
344 rows.extend(page)
345 if len(page) < _PAGE:
346 return rows
348 def logo_gaps(self, season_id: int | None) -> dict:
349 """Teams with no club, clubs with no crest, clubs whose crest is hot-linked.
351 `season_id` scopes the report to teams that played in that season and
352 their clubs; None reports every team and club.
353 """
354 prefix = club_logo_prefix(getattr(self.connection_holder, "url", None))
355 if prefix is None:
356 raise ValueError("SUPABASE_URL is not configured; cannot tell hosted crests from hot-linked ones")
358 teams = self._paged(lambda: self.client.table("teams").select("id, name, club_id"))
359 clubs = self._paged(lambda: self.client.table("clubs").select("id, name, logo_url, is_test"))
361 def matches_query():
362 query = self.client.table("matches").select("id, home_team_id, away_team_id")
363 return query.eq("season_id", season_id) if season_id is not None else query
365 match_counts: Counter = Counter()
366 for match in self._paged(matches_query):
367 match_counts[match["home_team_id"]] += 1
368 match_counts[match["away_team_id"]] += 1
370 report = build_logo_gaps(teams, clubs, match_counts, prefix, scoped=season_id is not None)
371 return {"season_id": season_id, **report}
373 # === Team-Club Association Methods ===
375 def update_team_club(self, team_id: int, club_id: int | None) -> dict:
376 """Update the club for a team.
378 Args:
379 team_id: The team ID to update
380 club_id: The club ID to assign (or None to remove club association)
382 Returns:
383 Updated team dict
385 Raises:
386 ValueError: If team update fails
387 """
388 result = self.client.table("teams").update({"club_id": club_id}).eq("id", team_id).execute()
389 if not result.data or len(result.data) == 0:
390 raise ValueError(f"Failed to update club for team {team_id}")
391 return result.data[0]
393 def get_all_parent_club_entities(self) -> list[dict]:
394 """Get all parent club entities (teams with no club_id).
396 This includes clubs that don't have children yet.
397 Used for dropdowns where users need to select a parent club.
398 """
399 try:
400 # Get all teams that could be parent clubs (no club_id)
401 response = self.client.table("teams").select("*").is_("club_id", "null").execute()
402 return response.data
403 except Exception:
404 logger.exception("Error querying parent club entities")
405 return []