Coverage for dao/motw_dao.py: 87.23%

113 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1"""Match of the Week — one editorial pick per week for each slot (SB-1010, SB-1638). 

2 

3A slot is (pool, age group): the main pool (Homegrown Northeast League + Flex 

4Empire/Turnpike/New England) runs U15-U19, the Pro Player Pathway U16-U19. SB-1010 

5began with one global pick a week; SB-1638 made it one per age group in each pool. 

6 

7The "only one" rule is a UNIQUE constraint on (week_start, pool, age_group_id), not 

8a convention this module remembers to honour — two admin tabs would be enough to 

9break the convention version. Re-picking a slot is an upsert on that key, and past 

10weeks stay as rows, so the archive comes free. 

11 

12Match payloads are not built here. `MatchDAO.get_match_by_id` already returns 

13the flattened shape the frontend knows, club colours included; duplicating that 

14select would be one more place to forget a field. 

15""" 

16 

17from __future__ import annotations 

18 

19from datetime import date, datetime, timedelta 

20from typing import Any 

21 

22import structlog 

23 

24from dao.base_dao import BaseDAO 

25 

26logger = structlog.get_logger() 

27 

28TABLE = "match_of_the_week" 

29SLOT_CONFLICT = "week_start,pool,age_group_id" 

30 

31MAIN_POOL = "main" 

32PATHWAY_POOL = "pathway" 

33POOLS = (MAIN_POOL, PATHWAY_POOL) 

34 

35# `reasons` omitted from a write (SB-1552). Distinct from None, which clears 

36# them: the hero's blurb editor re-posts the pick without reasons, and that 

37# must not wipe a "Why" list the agent or an admin wrote. 

38KEEP = object() 

39 

40 

41def week_start_for(match_date: str | date) -> str: 

42 """The Monday of the week a date falls in, as YYYY-MM-DD. 

43 

44 This is the bucket the uniqueness constraint is keyed on, so every caller 

45 must derive it the same way — hence one function rather than an inline 

46 timedelta in each of them. 

47 """ 

48 if isinstance(match_date, str): 

49 match_date = datetime.strptime(match_date[:10], "%Y-%m-%d").date() 

50 return (match_date - timedelta(days=match_date.weekday())).isoformat() 

51 

52 

53def pool_for_match(match: dict[str, Any]) -> str: 

54 """The pool a match's pick belongs to: the Pro Player Pathway, or the main pool. 

55 

56 Keyed on the division name, as the SB-1638 migration's backfill is, so a pick 

57 made before and after the migration lands in the same slot. 

58 """ 

59 division = str(match.get("division_name") or "") 

60 return PATHWAY_POOL if "pro player pathway" in division.lower() else MAIN_POOL 

61 

62 

63class MotwDAO(BaseDAO): 

64 """Read and write the match_of_the_week table.""" 

65 

66 def __init__(self, connection_holder): 

67 super().__init__(connection_holder) 

68 self._match_dao = None 

69 

70 @property 

71 def match_dao(self): 

72 """MatchDAO over the same connection, built on first use. 

73 

74 Imported inside the property because match_dao imports base_dao at 

75 module level; doing it at the top here closes the circle. 

76 """ 

77 if self._match_dao is None: 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true

78 from dao.match_dao import MatchDAO 

79 

80 self._match_dao = MatchDAO(self.connection_holder) 

81 return self._match_dao 

82 

83 def _query(self, week_start: str, pool: str | None, age_group_id: int | None): 

84 query = self.client.table(TABLE).select("*").eq("week_start", week_start) 

85 if pool is not None: 

86 query = query.eq("pool", pool) 

87 if age_group_id is not None: 

88 query = query.eq("age_group_id", age_group_id) 

89 return query 

90 

91 def get_for_week( 

92 self, 

93 week_start: str, 

94 *, 

95 pool: str | None = None, 

96 age_group_id: int | None = None, 

97 include_test: bool = False, 

98 ) -> dict[str, Any] | None: 

99 """The pick for one week's slot, with its match, or None when nobody picked. 

100 

101 With no slot named, the week's first pick (main pool first, then by age 

102 group): what an app released before SB-1638 shows as its one hero. 

103 

104 None is the ordinary answer, not a failure: most slots start with no 

105 pick, and every caller has to render that state anyway (CLAUDE.md). 

106 """ 

107 try: 

108 response = ( 

109 self._query(week_start, pool, age_group_id).order("pool").order("age_group_id").limit(1).execute() 

110 ) 

111 rows = response.data or [] 

112 return self._shape(rows[0], include_test) if rows else None 

113 except Exception: 

114 logger.exception("Could not read match of the week", week_start=week_start) 

115 return None 

116 

117 def list_for_week(self, week_start: str, *, include_test: bool = False) -> list[dict[str, Any]]: 

118 """Every slot's pick for a week, main pool first then by age group. [] when none.""" 

119 try: 

120 response = self._query(week_start, None, None).order("pool").order("age_group_id").execute() 

121 picks = [self._shape(row, include_test) for row in response.data or []] 

122 return [p for p in picks if p is not None] 

123 except Exception: 

124 logger.exception("Could not read the week's matches of the week", week_start=week_start) 

125 return [] 

126 

127 def _shape(self, row: dict[str, Any], include_test: bool) -> dict[str, Any] | None: 

128 week_start = row["week_start"] 

129 # Which pick in the slot's series this is. Counting picks rather than 

130 # calendar weeks is the only number that means anything here: the 

131 # season row starts 2026-08-01, the first stray fixture is two weeks 

132 # later, and the first real matchday is a month after that — so any 

133 # date-derived "week 6" is arithmetic nobody recognises. The first 

134 # Match of the Week in a slot is Week 1. 

135 ordinal = self.client.table(TABLE).select("id", count="exact").lte("week_start", week_start) 

136 if row.get("pool") is not None: 136 ↛ 138line 136 didn't jump to line 138 because the condition on line 136 was always true

137 ordinal = ordinal.eq("pool", row["pool"]) 

138 if row.get("age_group_id") is not None: 138 ↛ 140line 138 didn't jump to line 140 because the condition on line 138 was always true

139 ordinal = ordinal.eq("age_group_id", row["age_group_id"]) 

140 ordinal = ordinal.execute() 

141 match = self.match_dao.get_match_by_id(row["match_id"], include_test=include_test) 

142 if match is None: 

143 # The pick outlived its match's visibility — a test match seen by 

144 # an admin and then requested by a visitor, most likely. Report no 

145 # pick rather than a hero with an empty middle. 

146 logger.info("MOTW row has no visible match", week_start=week_start, match_id=row["match_id"]) 

147 return None 

148 

149 return { 

150 "week_start": week_start, 

151 "pool": row.get("pool") or MAIN_POOL, 

152 "age_group_id": row.get("age_group_id") or match.get("age_group_id"), 

153 "age_group": match.get("age_group_name"), 

154 "pick_number": ordinal.count or 1, 

155 "blurb": row.get("blurb"), 

156 # null = never provided, [] = provided and empty (SB-1552). 

157 "reasons": row.get("reasons"), 

158 "selected_by": row.get("selected_by"), 

159 "selected_by_service": row.get("selected_by_service"), 

160 "created_at": row.get("created_at"), 

161 "updated_at": row.get("updated_at"), 

162 "match": match, 

163 } 

164 

165 def set_for_match( 

166 self, 

167 match_id: int, 

168 *, 

169 blurb: str | None = None, 

170 reasons: list[dict[str, Any]] | None | object = KEEP, 

171 selected_by: str | None = None, 

172 selected_by_service: str | None = None, 

173 ) -> dict[str, Any] | None: 

174 """Pick a match, replacing whatever held its slot. 

175 

176 The slot comes from the match: its week (from its own date, not "now", 

177 so picking next week's fixture ahead of time fills next week's slot), 

178 its age group, and its pool. Picking a U16 match never touches the U15 

179 pick. 

180 

181 `selected_by` is the picking user's id; `selected_by_service` names the 

182 service account instead when one picked (SB-1553). Every write sets both, 

183 so an admin re-pick clears the agent's name and vice versa. 

184 

185 `reasons` left as KEEP preserves the slot's existing reasons when the 

186 same match is re-picked (a blurb edit), and clears them when a 

187 different match takes the slot — another match's reasons are wrong 

188 for this one. 

189 

190 Returns None when the match does not exist — the caller turns that into 

191 a 404, which is correct here: an unknown match id really is a bad 

192 request, unlike a slot with no pick. 

193 """ 

194 match = self.match_dao.get_match_by_id(match_id, include_test=True) 

195 if match is None: 

196 return None 

197 

198 week_start = week_start_for(match["match_date"]) 

199 pool = pool_for_match(match) 

200 age_group_id = match.get("age_group_id") 

201 payload = { 

202 "match_id": match_id, 

203 "week_start": week_start, 

204 "pool": pool, 

205 "age_group_id": age_group_id, 

206 "blurb": blurb, 

207 "selected_by": selected_by, 

208 "selected_by_service": selected_by_service, 

209 "updated_at": "now()", 

210 } 

211 if reasons is KEEP: 

212 if not self._is_current_pick(week_start, pool, age_group_id, match_id): 

213 payload["reasons"] = None 

214 else: 

215 payload["reasons"] = reasons 

216 

217 try: 

218 self.client.table(TABLE).upsert(payload, on_conflict=SLOT_CONFLICT).execute() 

219 except Exception: 

220 logger.exception("Could not set match of the week", match_id=match_id, week_start=week_start) 

221 return None 

222 

223 return self.get_for_week(week_start, pool=pool, age_group_id=age_group_id, include_test=True) 

224 

225 def _is_current_pick(self, week_start: str, pool: str, age_group_id: int | None, match_id: int) -> bool: 

226 """Whether `match_id` already holds the slot. 

227 

228 On a failed read, answer False: the write then clears reasons, which 

229 loses a list someone can rewrite, rather than attaching one match's 

230 reasons to another. 

231 """ 

232 try: 

233 query = self.client.table(TABLE).select("match_id").eq("week_start", week_start).eq("pool", pool) 

234 if age_group_id is not None: 234 ↛ 236line 234 didn't jump to line 236 because the condition on line 234 was always true

235 query = query.eq("age_group_id", age_group_id) 

236 rows = query.limit(1).execute().data or [] 

237 return bool(rows) and rows[0].get("match_id") == match_id 

238 except Exception: 

239 logger.exception("Could not read current match of the week", week_start=week_start) 

240 return False 

241 

242 def clear_week(self, week_start: str, *, pool: str | None = None, age_group_id: int | None = None) -> bool: 

243 """Unpick a slot, or every slot of the week when none is named. 

244 

245 True when a row went away, False when none was there. 

246 """ 

247 try: 

248 query = self.client.table(TABLE).delete().eq("week_start", week_start) 

249 if pool is not None: 

250 query = query.eq("pool", pool) 

251 if age_group_id is not None: 

252 query = query.eq("age_group_id", age_group_id) 

253 return bool(query.execute().data) 

254 except Exception: 

255 logger.exception("Could not clear match of the week", week_start=week_start) 

256 return False 

257 

258 def week_starts_with_picks(self, match_ids: list[int]) -> dict[int, str]: 

259 """Which of these matches are the pick for their week, as {match_id: week_start}. 

260 

261 Lets the Matches table badge its rows from one query instead of one per 

262 row. Empty input short-circuits: `in_()` with an empty list is an easy 

263 way to ask a database for everything by accident. 

264 """ 

265 if not match_ids: 

266 return {} 

267 try: 

268 response = self.client.table(TABLE).select("match_id, week_start").in_("match_id", match_ids).execute() 

269 return {row["match_id"]: row["week_start"] for row in (response.data or [])} 

270 except Exception: 

271 logger.exception("Could not read match of the week flags") 

272 return {}