Coverage for dao/motd_dao.py: 97.25%
87 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
1"""Tournament Match of the Day — one editorial pick per tournament, day and age group (SB-1559, SB-1750).
3The tournament sibling of MotwDAO. A multi-day event like MLS NEXT Fest has
4dozens of matches a day across six age groups, so the unit is (tournament,
5day, age group) rather than the calendar week. A single-age tournament has
6one slot a day, as it did before SB-1750.
8"Only one per slot" is the UNIQUE(tournament_id, match_date, age_group_id)
9constraint, not something this module remembers to check. Re-picking a slot
10is an upsert on that key; past days stay as rows.
12Reads never name the age_group_id column: a row without one takes its match's
13age group, and the age filter runs here rather than in the query. That keeps
14the public banner working on either side of the SB-1750 migration.
16Match payloads come from `MatchDAO.get_match_by_id`, as in MotwDAO, so the
17banner gets the same flattened shape (club colours, tournament name) the rest
18of the frontend already knows.
19"""
21from __future__ import annotations
23from typing import Any
25import structlog
27from dao.base_dao import BaseDAO
29logger = structlog.get_logger()
31TABLE = "tournament_match_of_the_day"
32SLOT_CONFLICT = "tournament_id,match_date,age_group_id"
35class MotdPickError(ValueError):
36 """The match cannot be the pick for that tournament day.
38 A ValueError so the endpoint turns it into a 400: the caller asked for
39 something that cannot be true (a match from another tournament, on
40 another day, in another age group, or with no age group at all), which is
41 a bad request rather than a missing resource.
42 """
45class MotdWriteError(RuntimeError):
46 """The pick was valid but could not be stored, or could not be cleared.
48 Kept apart from "no such match" (None) and from "nothing was picked" (0) so
49 the endpoint answers 5xx instead of a 404 that blames the match id or a 200
50 that says the pick is gone. The cause is logged here, not carried in the
51 message.
52 """
55def check_pick(
56 match: dict[str, Any],
57 tournament_id: int,
58 match_date: str | None = None,
59 age_group_id: int | None = None,
60) -> str:
61 """Validate that `match` can be featured for `tournament_id`; return its date.
63 Pure so the rule is testable without a database. `match_date` and
64 `age_group_id`, when the caller gives them, must agree with the match's
65 own — picking for a day or an age group and passing a match from a
66 different one is the mistake this catches.
67 """
68 if match.get("tournament_id") != tournament_id:
69 raise MotdPickError(f"Match {match.get('id')} is not in tournament {tournament_id}")
70 own_date = str(match.get("match_date") or "")[:10]
71 if not own_date:
72 raise MotdPickError(f"Match {match.get('id')} has no date")
73 if match_date and match_date[:10] != own_date:
74 raise MotdPickError(f"Match {match.get('id')} is on {own_date}, not {match_date[:10]}")
75 if match.get("age_group_id") is None:
76 # The age group is part of the slot key; production allows a match without one.
77 raise MotdPickError(f"Match {match.get('id')} has no age group, so it cannot be Match of the Day")
78 if age_group_id is not None and match.get("age_group_id") != age_group_id:
79 raise MotdPickError(f"Match {match.get('id')} is in age group {match.get('age_group_id')}, not {age_group_id}")
80 return own_date
83def _slot_order(pick: dict[str, Any]) -> tuple[str, int]:
84 return (str(pick["match_date"]), pick.get("age_group_id") or 0)
87class MotdDAO(BaseDAO):
88 """Read and write the tournament_match_of_the_day table."""
90 def __init__(self, connection_holder):
91 super().__init__(connection_holder)
92 self._match_dao = None
94 @property
95 def match_dao(self):
96 """MatchDAO over the same connection, built on first use (see MotwDAO)."""
97 if self._match_dao is None: 97 ↛ 98line 97 didn't jump to line 98 because the condition on line 97 was never true
98 from dao.match_dao import MatchDAO
100 self._match_dao = MatchDAO(self.connection_holder)
101 return self._match_dao
103 def _hydrate(self, row: dict[str, Any], *, include_test: bool) -> dict[str, Any] | None:
104 match = self.match_dao.get_match_by_id(row["match_id"], include_test=include_test)
105 if match is None:
106 # The pick outlived its match's visibility (a test match picked by
107 # an admin, read by a visitor). Report no pick rather than a banner
108 # with nothing in it.
109 logger.info("MOTD row has no visible match", tournament_id=row["tournament_id"], match_id=row["match_id"])
110 return None
111 return {
112 "tournament_id": row["tournament_id"],
113 "match_date": row["match_date"],
114 # A row written before SB-1750 has no age group of its own.
115 "age_group_id": row.get("age_group_id") or match.get("age_group_id"),
116 "age_group": match.get("age_group_name"),
117 "blurb": row.get("blurb"),
118 "reasons": row.get("reasons"),
119 "selected_by": row.get("selected_by"),
120 "created_at": row.get("created_at"),
121 "updated_at": row.get("updated_at"),
122 "match": match,
123 }
125 def list_for_day(self, tournament_id: int, match_date: str, *, include_test: bool = False) -> list[dict[str, Any]]:
126 """Every visible pick for one tournament day, by age group.
128 Empty is the ordinary answer — most days start without a pick.
129 """
130 try:
131 response = (
132 self.client.table(TABLE)
133 .select("*")
134 .eq("tournament_id", tournament_id)
135 .eq("match_date", match_date)
136 .execute()
137 )
138 picks = (self._hydrate(row, include_test=include_test) for row in (response.data or []))
139 return sorted((p for p in picks if p is not None), key=_slot_order)
140 except Exception:
141 logger.exception("Could not read match of the day", tournament_id=tournament_id, match_date=match_date)
142 return []
144 def get_for_day(
145 self,
146 tournament_id: int,
147 match_date: str,
148 *,
149 age_group_id: int | None = None,
150 include_test: bool = False,
151 ) -> dict[str, Any] | None:
152 """The pick for one slot, or None when nobody picked.
154 With no age group, the day's first pick by age group: the only one a
155 single-age tournament has. With one, that age group's pick and never
156 another's.
157 """
158 picks = self.list_for_day(tournament_id, match_date, include_test=include_test)
159 if age_group_id is not None:
160 picks = [p for p in picks if p["age_group_id"] == age_group_id]
161 return picks[0] if picks else None
163 def list_for_tournament(self, tournament_id: int, *, include_test: bool = False) -> list[dict[str, Any]]:
164 """Every visible pick in a tournament, oldest day first, then by age group.
166 Lets the tournament page choose "today" in the viewer's own timezone
167 instead of the server guessing which day it is in Mesa.
168 """
169 try:
170 response = (
171 self.client.table(TABLE).select("*").eq("tournament_id", tournament_id).order("match_date").execute()
172 )
173 except Exception:
174 logger.exception("Could not list matches of the day", tournament_id=tournament_id)
175 return []
176 picks = (self._hydrate(row, include_test=include_test) for row in (response.data or []))
177 return sorted((p for p in picks if p is not None), key=_slot_order)
179 def set_for_match(
180 self,
181 tournament_id: int,
182 match_id: int,
183 *,
184 match_date: str | None = None,
185 age_group_id: int | None = None,
186 blurb: str | None = None,
187 reasons: list[dict[str, Any]] | None = None,
188 selected_by: str | None = None,
189 ) -> dict[str, Any] | None:
190 """Pick a match for its tournament day and age group, replacing that slot's pick.
192 The slot comes from the match: picking a U16 match never touches the
193 U15 pick. `match_date` and `age_group_id` are guards only.
195 Returns None when the match does not exist (the endpoint's 404).
196 Raises MotdPickError when it exists but cannot be this slot's pick,
197 and MotdWriteError when the pick could not be stored.
198 """
199 match = self.match_dao.get_match_by_id(match_id, include_test=True)
200 if match is None:
201 return None
203 day = check_pick(match, tournament_id, match_date, age_group_id)
204 slot_age = match.get("age_group_id")
205 payload = {
206 "tournament_id": tournament_id,
207 "match_date": day,
208 "age_group_id": slot_age,
209 "match_id": match_id,
210 "blurb": blurb,
211 "reasons": reasons,
212 "selected_by": selected_by,
213 "updated_at": "now()",
214 }
215 try:
216 self.client.table(TABLE).upsert(payload, on_conflict=SLOT_CONFLICT).execute()
217 except Exception as e:
218 logger.exception("Could not set match of the day", tournament_id=tournament_id, match_id=match_id)
219 raise MotdWriteError("Could not store match of the day") from e
221 pick = self.get_for_day(tournament_id, day, age_group_id=slot_age, include_test=True)
222 if pick is None:
223 logger.error("Match of the day not readable after write", tournament_id=tournament_id, match_id=match_id)
224 raise MotdWriteError("Could not read back match of the day")
225 return pick
227 def clear_day(self, tournament_id: int, match_date: str, *, age_group_id: int | None = None) -> int:
228 """Unpick a slot, or every slot of the day when no age group is named.
230 The number of picks that went away; 0 when none was there. Raises
231 MotdWriteError when the delete itself failed, so a pick that is still
232 there is never reported as cleared.
233 """
234 try:
235 query = self.client.table(TABLE).delete().eq("tournament_id", tournament_id).eq("match_date", match_date)
236 if age_group_id is not None:
237 query = query.eq("age_group_id", age_group_id)
238 return len(query.execute().data or [])
239 except Exception as e:
240 logger.exception(
241 "Could not clear match of the day",
242 tournament_id=tournament_id,
243 match_date=match_date,
244 age_group_id=age_group_id,
245 )
246 raise MotdWriteError("Could not clear match of the day") from e