Coverage for dao/qop_rankings_dao.py: 85.79%

147 statements  

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

1""" 

2Quality of Play (QoP) Rankings data access layer for MissingTable. 

3 

4Data model (see migration 20260418000000_qop_snapshots_redesign.sql): 

5 

6 qop_snapshots one row per scrape that observed new data. 

7 Keyed by (detected_at, division_id, age_group_id). 

8 detected_at is the date the scraper first saw this 

9 particular ranking set — not a wall-clock week. 

10 

11 qop_rankings one row per team per snapshot. FK → qop_snapshots 

12 with ON DELETE CASCADE. 

13 

14Write path (`record_snapshot`) compares the incoming rankings against the 

15latest stored snapshot for the same (division, age_group). If unchanged it 

16returns `{"status": "unchanged"}` without inserting anything — that's how we 

17distinguish "mlssoccer hasn't published new numbers yet" from "new publish". 

18""" 

19 

20from __future__ import annotations 

21 

22from decimal import Decimal 

23from typing import Any 

24 

25import structlog 

26 

27logger = structlog.get_logger() 

28 

29 

30# Fields used to decide "did this snapshot change?". `team_id` and `scraped_at` 

31# are deliberately excluded: team_id is derived by us via a name lookup (not 

32# part of the scraped payload) and scraped_at always differs per run. 

33_SIGNATURE_FIELDS = ( 

34 "rank", 

35 "team_name", 

36 "matches_played", 

37 "att_score", 

38 "def_score", 

39 "qop_score", 

40) 

41 

42 

43def _to_float(value: Any) -> float | None: 

44 """Normalize Decimal/float/int/None to float for comparison.""" 

45 if value is None: 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true

46 return None 

47 if isinstance(value, Decimal): 

48 return float(value) 

49 return float(value) 

50 

51 

52def _ranking_signature(entry: dict) -> tuple: 

53 """Build a comparable tuple for a single ranking row. 

54 

55 Scores are rounded to 1 decimal to match the NUMERIC(5,1) DB precision — 

56 without rounding, a Decimal('87.6') read from the DB would compare 

57 unequal to a float 87.6 sent in a fresh payload. 

58 """ 

59 return ( 

60 int(entry["rank"]), 

61 str(entry["team_name"]), 

62 ( 

63 int(entry["matches_played"]) 

64 if entry.get("matches_played") is not None 

65 else None 

66 ), 

67 ( 

68 round(_to_float(entry.get("att_score")), 1) 

69 if entry.get("att_score") is not None 

70 else None 

71 ), 

72 ( 

73 round(_to_float(entry.get("def_score")), 1) 

74 if entry.get("def_score") is not None 

75 else None 

76 ), 

77 round(_to_float(entry["qop_score"]), 1), 

78 ) 

79 

80 

81def _rankings_equal(a: list[dict], b: list[dict]) -> bool: 

82 """Two ranking lists are equal iff their ordered signature lists match.""" 

83 if len(a) != len(b): 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true

84 return False 

85 a_sorted = sorted(a, key=lambda r: int(r["rank"])) 

86 b_sorted = sorted(b, key=lambda r: int(r["rank"])) 

87 return [_ranking_signature(x) for x in a_sorted] == [ 

88 _ranking_signature(x) for x in b_sorted 

89 ] 

90 

91 

92class QoPRankingsDAO: 

93 """Data Access Object for Quality of Play rankings.""" 

94 

95 # ── Lookups ────────────────────────────────────────────────────────────── 

96 

97 @staticmethod 

98 def _resolve_division_id(client, division: str) -> int | None: 

99 """Resolve a division name to its database ID (case-insensitive).""" 

100 try: 

101 response = client.table("divisions").select("id, name").execute() 

102 for row in response.data: 

103 if row["name"].lower() == division.lower(): 

104 return row["id"] 

105 logger.warning("qop_rankings_division_not_found", division=division) 

106 return None 

107 except Exception: 

108 logger.exception("qop_rankings_division_lookup_error", division=division) 

109 return None 

110 

111 @staticmethod 

112 def _resolve_age_group_id(client, age_group: str) -> int | None: 

113 """Resolve an age group name to its database ID (case-insensitive).""" 

114 try: 

115 response = client.table("age_groups").select("id, name").execute() 

116 for row in response.data: 

117 if row["name"].lower() == age_group.lower(): 

118 return row["id"] 

119 logger.warning("qop_rankings_age_group_not_found", age_group=age_group) 

120 return None 

121 except Exception: 

122 logger.exception("qop_rankings_age_group_lookup_error", age_group=age_group) 

123 return None 

124 

125 @staticmethod 

126 def _resolve_team_id(client, team_name: str) -> int | None: 

127 """Resolve a team name to its database ID (case-insensitive).""" 

128 try: 

129 response = ( 

130 client.table("teams") 

131 .select("id, name") 

132 .ilike("name", team_name) 

133 .limit(1) 

134 .execute() 

135 ) 

136 if response.data: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true

137 return response.data[0]["id"] 

138 return None 

139 except Exception: 

140 logger.warning("qop_rankings_team_lookup_error", team_name=team_name) 

141 return None 

142 

143 # ── Snapshot fetch ─────────────────────────────────────────────────────── 

144 

145 @staticmethod 

146 def _fetch_latest_snapshot( 

147 client, division_id: int, age_group_id: int 

148 ) -> dict | None: 

149 """Return the most recent snapshot + its rankings, or None if absent.""" 

150 snap_resp = ( 

151 client.table("qop_snapshots") 

152 .select("id, detected_at") 

153 .eq("division_id", division_id) 

154 .eq("age_group_id", age_group_id) 

155 .order("detected_at", desc=True) 

156 .limit(1) 

157 .execute() 

158 ) 

159 if not snap_resp.data: 

160 return None 

161 

162 snap = snap_resp.data[0] 

163 rankings_resp = ( 

164 client.table("qop_rankings") 

165 .select( 

166 "rank, team_name, team_id, matches_played, att_score, def_score, qop_score" 

167 ) 

168 .eq("snapshot_id", snap["id"]) 

169 .order("rank") 

170 .execute() 

171 ) 

172 return { 

173 "id": snap["id"], 

174 "detected_at": snap["detected_at"], 

175 "rankings": rankings_resp.data or [], 

176 } 

177 

178 # ── Write ──────────────────────────────────────────────────────────────── 

179 

180 @staticmethod 

181 def record_snapshot(client, snapshot: dict) -> dict: 

182 """ 

183 Record a QoP snapshot — insert a new row iff the rankings differ from 

184 the most recent stored snapshot for the same (division, age_group). 

185 

186 Args: 

187 client: Supabase client instance 

188 snapshot: { 

189 "detected_at": "2026-04-18", # ISO date 

190 "division": "Northeast", 

191 "age_group": "U14", 

192 "source": "cronjob", # optional 

193 "rankings": [{rank, team_name, matches_played, 

194 att_score, def_score, qop_score}, ...] 

195 } 

196 

197 Returns: 

198 { 

199 "status": "inserted" | "unchanged", 

200 "detected_at": "2026-04-18", 

201 "snapshot_id": int | None, # None when status=unchanged 

202 "rankings_count": int, 

203 } 

204 

205 Raises: 

206 ValueError: division or age_group cannot be resolved. 

207 """ 

208 detected_at = snapshot["detected_at"] 

209 division_name = snapshot["division"] 

210 age_group_name = snapshot["age_group"] 

211 source = snapshot.get("source") or "cronjob" 

212 rankings = snapshot.get("rankings", []) 

213 

214 division_id = QoPRankingsDAO._resolve_division_id(client, division_name) 

215 if division_id is None: 

216 raise ValueError(f"Division not found: {division_name!r}") 

217 

218 age_group_id = QoPRankingsDAO._resolve_age_group_id(client, age_group_name) 

219 if age_group_id is None: 

220 raise ValueError(f"Age group not found: {age_group_name!r}") 

221 

222 if not rankings: 

223 return { 

224 "status": "unchanged", 

225 "detected_at": detected_at, 

226 "snapshot_id": None, 

227 "rankings_count": 0, 

228 } 

229 

230 latest = QoPRankingsDAO._fetch_latest_snapshot( 

231 client, division_id, age_group_id 

232 ) 

233 if latest is not None and _rankings_equal(rankings, latest["rankings"]): 

234 logger.info( 

235 "qop_rankings_unchanged", 

236 division=division_name, 

237 age_group=age_group_name, 

238 latest_detected_at=latest["detected_at"], 

239 ) 

240 return { 

241 "status": "unchanged", 

242 "detected_at": latest["detected_at"], 

243 "snapshot_id": latest["id"], 

244 "rankings_count": len(rankings), 

245 } 

246 

247 # Create the snapshot row. UNIQUE (detected_at, division, age_group) 

248 # will reject a second snapshot on the same day with different data — 

249 # that's intentional: two distinct ranking sets on the same date 

250 # means something is wrong upstream and we want to see it. 

251 snap_row = { 

252 "detected_at": detected_at, 

253 "division_id": division_id, 

254 "age_group_id": age_group_id, 

255 "source": source, 

256 } 

257 if snapshot.get("scraped_at"): 257 ↛ 258line 257 didn't jump to line 258 because the condition on line 257 was never true

258 snap_row["scraped_at"] = snapshot["scraped_at"] 

259 

260 snap_resp = client.table("qop_snapshots").insert(snap_row).execute() 

261 if not snap_resp.data: 261 ↛ 262line 261 didn't jump to line 262 because the condition on line 261 was never true

262 raise RuntimeError("qop_snapshots insert returned no data") 

263 snapshot_id = snap_resp.data[0]["id"] 

264 

265 # Build ranking rows with team_id lookup. 

266 ranking_rows = [] 

267 for entry in rankings: 

268 team_id = QoPRankingsDAO._resolve_team_id(client, entry["team_name"]) 

269 ranking_rows.append( 

270 { 

271 "snapshot_id": snapshot_id, 

272 "rank": entry["rank"], 

273 "team_name": entry["team_name"], 

274 "team_id": team_id, 

275 "matches_played": entry.get("matches_played"), 

276 "att_score": entry.get("att_score"), 

277 "def_score": entry.get("def_score"), 

278 "qop_score": entry["qop_score"], 

279 } 

280 ) 

281 

282 client.table("qop_rankings").insert(ranking_rows).execute() 

283 

284 logger.info( 

285 "qop_rankings_inserted", 

286 detected_at=detected_at, 

287 division=division_name, 

288 age_group=age_group_name, 

289 snapshot_id=snapshot_id, 

290 count=len(ranking_rows), 

291 ) 

292 return { 

293 "status": "inserted", 

294 "detected_at": detected_at, 

295 "snapshot_id": snapshot_id, 

296 "rankings_count": len(ranking_rows), 

297 } 

298 

299 # ── Read ───────────────────────────────────────────────────────────────── 

300 

301 @staticmethod 

302 def get_latest_with_delta( 

303 client, division_id: int, age_group_id: int 

304 ) -> dict: 

305 """Back-compat wrapper around `get_with_delta` for callers that always 

306 want the newest snapshot (match preview, /api/table enrichment).""" 

307 return QoPRankingsDAO.get_with_delta(client, division_id, age_group_id) 

308 

309 @staticmethod 

310 def get_with_delta( 

311 client, 

312 division_id: int, 

313 age_group_id: int, 

314 snapshot_id: int | None = None, 

315 ) -> dict: 

316 """ 

317 Fetch one snapshot (the latest, or the one pinned by `snapshot_id`) 

318 plus the one immediately older, and compute per-team rank/score deltas. 

319 

320 Also returns `prev_snapshot_id` / `next_snapshot_id` so the caller can 

321 step backward/forward through history. Both are `None` at the ends — 

322 that's the signal the UI uses to hide the prev/next buttons. 

323 

324 Response shape is a superset of the legacy `get_latest_with_delta` 

325 response — `week_of` / `prior_week_of` are detection dates, not ISO 

326 weeks, and are preserved purely for frontend compat. 

327 """ 

328 empty = { 

329 "has_data": False, 

330 "week_of": None, 

331 "prior_week_of": None, 

332 "snapshot_id": None, 

333 "prev_snapshot_id": None, 

334 "next_snapshot_id": None, 

335 "rankings": [], 

336 } 

337 

338 try: 

339 snap_resp = ( 

340 client.table("qop_snapshots") 

341 .select("id, detected_at") 

342 .eq("division_id", division_id) 

343 .eq("age_group_id", age_group_id) 

344 .order("detected_at", desc=True) 

345 .execute() 

346 ) 

347 snapshots = snap_resp.data or [] 

348 if not snapshots: 

349 return empty 

350 

351 current_index = 0 

352 if snapshot_id is not None: 

353 current_index = next( 

354 (i for i, s in enumerate(snapshots) if s["id"] == snapshot_id), 

355 -1, 

356 ) 

357 if current_index == -1: 

358 return empty 

359 

360 current = snapshots[current_index] 

361 # DESC order: older snapshots have higher indices. 

362 prior = ( 

363 snapshots[current_index + 1] 

364 if current_index + 1 < len(snapshots) 

365 else None 

366 ) 

367 next_snapshot_id = ( 

368 snapshots[current_index - 1]["id"] if current_index > 0 else None 

369 ) 

370 prev_snapshot_id = prior["id"] if prior is not None else None 

371 

372 current_rows_resp = ( 

373 client.table("qop_rankings") 

374 .select( 

375 "rank, team_name, team_id, matches_played, att_score, def_score, qop_score" 

376 ) 

377 .eq("snapshot_id", current["id"]) 

378 .order("rank") 

379 .execute() 

380 ) 

381 current_rows = current_rows_resp.data or [] 

382 

383 prior_rank_by_team: dict[str, int] = {} 

384 prior_qop_by_team: dict[str, float] = {} 

385 prior_att_by_team: dict[str, float] = {} 

386 prior_def_by_team: dict[str, float] = {} 

387 if prior is not None: 

388 prior_rows_resp = ( 

389 client.table("qop_rankings") 

390 .select("rank, team_name, att_score, def_score, qop_score") 

391 .eq("snapshot_id", prior["id"]) 

392 .execute() 

393 ) 

394 for row in prior_rows_resp.data or []: 

395 prior_rank_by_team[row["team_name"]] = row["rank"] 

396 if row.get("qop_score") is not None: 396 ↛ 397line 396 didn't jump to line 397 because the condition on line 396 was never true

397 prior_qop_by_team[row["team_name"]] = row["qop_score"] 

398 if row.get("att_score") is not None: 398 ↛ 399line 398 didn't jump to line 399 because the condition on line 398 was never true

399 prior_att_by_team[row["team_name"]] = row["att_score"] 

400 if row.get("def_score") is not None: 400 ↛ 401line 400 didn't jump to line 401 because the condition on line 400 was never true

401 prior_def_by_team[row["team_name"]] = row["def_score"] 

402 

403 rankings = [] 

404 for row in current_rows: 

405 prior_rank = prior_rank_by_team.get(row["team_name"]) 

406 rank_change = ( 

407 (prior_rank - row["rank"]) if prior_rank is not None else None 

408 ) 

409 prior_qop = prior_qop_by_team.get(row["team_name"]) 

410 qop_change = ( 

411 round(row["qop_score"] - prior_qop, 1) 

412 if prior_qop is not None and row.get("qop_score") is not None 

413 else None 

414 ) 

415 prior_att = prior_att_by_team.get(row["team_name"]) 

416 att_change = ( 

417 round(row["att_score"] - prior_att, 1) 

418 if prior_att is not None and row.get("att_score") is not None 

419 else None 

420 ) 

421 prior_def = prior_def_by_team.get(row["team_name"]) 

422 def_change = ( 

423 round(row["def_score"] - prior_def, 1) 

424 if prior_def is not None and row.get("def_score") is not None 

425 else None 

426 ) 

427 rankings.append( 

428 { 

429 "rank": row["rank"], 

430 "team_name": row["team_name"], 

431 "team_id": row.get("team_id"), 

432 "matches_played": row.get("matches_played"), 

433 "att_score": row.get("att_score"), 

434 "def_score": row.get("def_score"), 

435 "qop_score": row["qop_score"], 

436 "rank_change": rank_change, 

437 "qop_change": qop_change, 

438 "att_change": att_change, 

439 "def_change": def_change, 

440 } 

441 ) 

442 

443 return { 

444 "has_data": True, 

445 "week_of": current["detected_at"], 

446 "prior_week_of": prior["detected_at"] if prior else None, 

447 "snapshot_id": current["id"], 

448 "prev_snapshot_id": prev_snapshot_id, 

449 "next_snapshot_id": next_snapshot_id, 

450 "rankings": rankings, 

451 } 

452 

453 except Exception: 

454 logger.exception( 

455 "qop_rankings_get_with_delta_error", 

456 division_id=division_id, 

457 age_group_id=age_group_id, 

458 snapshot_id=snapshot_id, 

459 ) 

460 return empty