Coverage for dao/standings.py: 94.99%
231 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Pure functions for league standings calculation.
4This module contains pure functions with no external dependencies,
5making them trivially testable without mocking.
7These functions are used by MatchDAO.get_league_table() but can be
8unit tested independently.
9"""
11from collections import defaultdict
12from datetime import date
13from fractions import Fraction
14from operator import itemgetter
15from typing import Any
18def filter_completed_matches(matches: list[dict]) -> list[dict]:
19 """
20 Filter matches to only include completed ones.
22 Uses match_status field if available, otherwise falls back to
23 date-based logic for backwards compatibility.
25 Args:
26 matches: List of match dictionaries from database
28 Returns:
29 List of completed matches only
30 """
31 played_matches = []
32 for match in matches:
33 match_status = match.get("match_status")
34 if match_status: 34 ↛ 40line 34 didn't jump to line 40 because the condition on line 34 was always true
35 # Use match_status field if available
36 if match_status in ("completed", "forfeit"):
37 played_matches.append(match)
38 else:
39 # Fallback to date-based logic for backwards compatibility
40 match_date_str = match.get("match_date")
41 if match_date_str:
42 match_date = date.fromisoformat(match_date_str)
43 if match_date <= date.today():
44 played_matches.append(match)
45 return played_matches
48def filter_matches_in_division(matches: list[dict], division_id: int) -> list[dict]:
49 """
50 Filter matches to those filed to a division — `matches.division_id`.
52 This used to ask a different question: whether *both teams* carried that
53 `teams.division_id`. That reading was wrong twice over (SB-835).
55 A Flex bracket's participants are Homegrown teams — every one of them has
56 its Homegrown division_id — so the teams test kept 0 of 68 Flex matches and
57 every Flex standings table came back empty.
59 And `teams.division_id` is a single value per team row, while a club plays
60 different divisions at different age groups. In 2025-2026 that quietly
61 dropped 88 New England U14 League matches whose teams are recorded under
62 Northeast. It is also a *current* value being applied to *historical*
63 matches, so a team moving divisions rewrites old tables.
65 The match knows which division it was played in. Ask the match.
66 """
67 return [m for m in matches if m.get("division_id") == division_id]
70def filter_by_match_type(matches: list[dict], match_type: str) -> list[dict]:
71 """
72 Filter matches by match type name.
74 Args:
75 matches: List of match dictionaries
76 match_type: Match type name to filter by (e.g., "League")
78 Returns:
79 List of matches with the specified match type
80 """
81 return [m for m in matches if m.get("match_type", {}).get("name") == match_type]
84def filter_by_match_types(matches: list[dict], names: set[str] | None) -> list[dict]:
85 """
86 Keep matches in any of the named competitions. None keeps every one.
88 The singular version has no way to ask for "every competition", which is
89 why there was no combined table at all (SB-834). None is the pass-through
90 rather than a sentinel string, so a caller cannot spell it wrong.
91 """
92 if names is None:
93 return list(matches)
94 return [m for m in matches if (m.get("match_type") or {}).get("name") in names]
97def teams_in_division(matches: list[dict], division_id: int) -> set[int]:
98 """
99 The team ids that make up a division's table.
101 A team is in the table because it played matches filed to the division.
102 For a Homegrown division that means its League matches: its Flex matches
103 carry the Flex bracket's division_id and do not, on their own, put a team
104 in the Homegrown table.
105 """
106 team_ids: set[int] = set()
107 for match in filter_matches_in_division(matches, division_id):
108 for side in ("home_team", "away_team"):
109 team_id = (match.get(side) or {}).get("id")
110 if team_id is not None: 110 ↛ 108line 110 didn't jump to line 108 because the condition on line 110 was always true
111 team_ids.add(team_id)
112 return team_ids
115def filter_matches_involving(matches: list[dict], team_ids: set[int]) -> list[dict]:
116 """Matches with at least one of these teams in them."""
117 kept = []
118 for match in matches:
119 home_id = (match.get("home_team") or {}).get("id")
120 away_id = (match.get("away_team") or {}).get("id")
121 if home_id in team_ids or away_id in team_ids:
122 kept.append(match)
123 return kept
126def count_outside_table_opponents(matches: list[dict], team_ids: set[int]) -> tuple[int, int]:
127 """
128 How much of this table is played against teams that are not in it.
130 Returns (matches_against_outsiders, distinct_outsiders).
132 This is the combined view's denominator, and it is part of the feature
133 rather than a footnote. Flex brackets cut across Homegrown divisions, so a
134 team's combined points include results against opponents the table does not
135 list — that is a record, not a standing, and per CLAUDE.md a cross-team
136 statistic ships with its coverage or it does not ship.
137 """
138 outsiders: set[int] = set()
139 count = 0
140 for match in matches:
141 home_id = (match.get("home_team") or {}).get("id")
142 away_id = (match.get("away_team") or {}).get("id")
143 for team_id in (home_id, away_id):
144 if team_id is not None and team_id not in team_ids:
145 outsiders.add(team_id)
146 count += 1
147 break
148 return count, len(outsiders)
151def awards_shootout_points(match: dict) -> bool:
152 """
153 Does this match's competition score a penalty shootout?
155 Read from `match_types.shootout_points`, joined onto the match — never
156 from the competition's name, and never from whether a shootout happens to
157 be recorded. Tournament matches record shootouts too, and there they are
158 knockout progression, not table points (SB-1027).
159 """
160 return bool((match.get("match_type") or {}).get("shootout_points"))
163def shootout_result(match: dict) -> str | None:
164 """
165 Which side won the shootout: "home", "away", or None.
167 None covers every case in which no shootout decided anything: the match
168 was not level after regulation, its competition does not score
169 shootouts, or the shootout scores are absent or themselves level. A Flex
170 match level after regulation with no shootout recorded is scored as a
171 plain draw — absent data is not a shootout loss for either side.
172 """
173 if not awards_shootout_points(match):
174 return None
175 if match.get("home_score") != match.get("away_score"):
176 return None
177 home_pens = match.get("home_penalty_score")
178 away_pens = match.get("away_penalty_score")
179 if home_pens is None or away_pens is None or home_pens == away_pens:
180 return None
181 return "home" if home_pens > away_pens else "away"
184def shootout_competitions(matches: list[dict]) -> list[str]:
185 """The competitions among these matches whose shootouts are worth points."""
186 names: set[str] = set()
187 for m in matches:
188 name = (m.get("match_type") or {}).get("name")
189 if name and awards_shootout_points(m):
190 names.add(name)
191 return sorted(names)
194def calculate_standings(matches: list[dict], only_team_ids: set[int] | None = None) -> list[dict]:
195 """
196 Calculate league standings from a list of completed matches.
198 This is a pure function with no external dependencies.
199 It expects matches that have already been filtered to only include
200 completed matches with scores.
202 Args:
203 matches: List of match dictionaries, each containing:
204 - home_team: dict with "name" key
205 - away_team: dict with "name" key
206 - home_score: int or None
207 - away_score: int or None
208 - match_type: dict with "name" and "shootout_points" keys
209 - home_penalty_score / away_penalty_score: int or None
211 Returns:
212 List of team standings in MLS NEXT order: points per match first,
213 then the official tiebreaks (see rank_table). Ranking by total
214 points misleads when teams have played different numbers of games,
215 as they do across League and Flex (SB-1623).
217 Each standing contains:
218 - team: Team name
219 - played: Matches played
220 - wins: Regulation wins
221 - draws: Matches level after regulation, shootout or not
222 - losses: Regulation losses
223 - shootout_wins / shootout_losses: how many of the draws were
224 settled on penalties, and which way — the reader's way of seeing
225 why 1W 2D can be worth 7
226 - goals_for: Goals scored (regulation only; shootout kicks are not goals)
227 - goals_against: Goals conceded
228 - goal_difference: goals_for - goals_against
229 - points: Total points
230 - points_per_match, gd_per_match, gf_per_match, ga_per_match:
231 per match played, to 2 decimals (see per_match_stats)
233 Business Rules:
234 - Win = 3 points
235 - Loss = 0 points
236 - Draw = 1 point each — unless the competition scores shootouts
237 (`match_types.shootout_points`, MLS NEXT Flex), in which case the
238 shootout winner takes 2 and the loser 1. The rule belongs to the
239 competition, not the match, so a combined table can hold a League
240 draw at 1-1 and a Flex shootout at 2-1 side by side (SB-1027).
241 - Matches without scores are skipped
243 only_team_ids restricts which teams get a *row*, without discarding the
244 match. The combined qualifying table needs exactly that: a team's Flex
245 results count towards its points even when the opponent sits outside the
246 division, and that opponent must not appear as a row — it has not played
247 the rest of the table (SB-834). None means every team gets a row.
248 """
249 standings: dict[str, dict[str, Any]] = defaultdict(
250 lambda: {
251 "played": 0,
252 "wins": 0,
253 "draws": 0,
254 "losses": 0,
255 "shootout_wins": 0,
256 "shootout_losses": 0,
257 "goals_for": 0,
258 "goals_against": 0,
259 "goal_difference": 0,
260 "points": 0,
261 "logo_url": None,
262 "team_id": None,
263 "club_id": None,
264 }
265 )
267 def record(team: dict, goals_for: int, goals_against: int, shootout: str | None) -> None:
268 """Fold one team's side of one result into its row.
270 `shootout` is "won", "lost" or None for this side.
271 """
272 row = standings[team["name"]]
274 if row["team_id"] is None:
275 row["team_id"] = team.get("id")
277 club = team.get("club") or {}
278 if not row["logo_url"]: 278 ↛ 280line 278 didn't jump to line 280 because the condition on line 278 was always true
279 row["logo_url"] = club.get("logo_url")
280 if row["club_id"] is None:
281 row["club_id"] = club.get("id")
283 row["played"] += 1
284 row["goals_for"] += goals_for
285 row["goals_against"] += goals_against
287 if goals_for > goals_against:
288 row["wins"] += 1
289 row["points"] += 3
290 elif goals_for < goals_against:
291 row["losses"] += 1
292 elif shootout == "won":
293 row["draws"] += 1
294 row["shootout_wins"] += 1
295 row["points"] += 2
296 elif shootout == "lost":
297 row["draws"] += 1
298 row["shootout_losses"] += 1
299 row["points"] += 1
300 else:
301 row["draws"] += 1
302 row["points"] += 1
304 def in_table(team: dict) -> bool:
305 return only_team_ids is None or team.get("id") in only_team_ids
307 # Inputs to the tiebreaks: points each team took from each opponent, and
308 # each team's home and away (goals for, goals against) results.
309 h2h: dict[tuple[str, str], int] = defaultdict(int)
310 venue: dict[str, dict[str, list[tuple[int, int]]]] = defaultdict(lambda: {"home": [], "away": []})
312 for match in matches:
313 home = match["home_team"]
314 away = match["away_team"]
315 home_score = match.get("home_score")
316 away_score = match.get("away_score")
318 # Skip matches without scores
319 if home_score is None or away_score is None:
320 continue
322 winner = shootout_result(match)
323 home_shootout = away_shootout = None
324 if winner == "home":
325 home_shootout, away_shootout = "won", "lost"
326 elif winner == "away":
327 home_shootout, away_shootout = "lost", "won"
329 if in_table(home):
330 record(home, home_score, away_score, home_shootout)
331 if in_table(away):
332 record(away, away_score, home_score, away_shootout)
334 if in_table(home):
335 venue[home["name"]]["home"].append((home_score, away_score))
336 if in_table(away):
337 venue[away["name"]]["away"].append((away_score, home_score))
338 if in_table(home) and in_table(away):
339 h2h[(home["name"], away["name"])] += _points(home_score, away_score, home_shootout)
340 h2h[(away["name"], home["name"])] += _points(away_score, home_score, away_shootout)
342 # Convert to list and calculate goal difference
343 table = []
344 for team, stats in standings.items():
345 stats["goal_difference"] = stats["goals_for"] - stats["goals_against"]
346 stats["team"] = team
347 stats.update(per_match_stats(stats))
348 table.append(stats)
350 return rank_table(table, h2h, venue)
353def _points(goals_for: int, goals_against: int, shootout: str | None) -> int:
354 """One side's points from one result, by the same rules as record()."""
355 if goals_for > goals_against:
356 return 3
357 if goals_for < goals_against:
358 return 0
359 return 2 if shootout == "won" else 1
362def per_match_stats(row: dict) -> dict[str, float | None]:
363 """
364 Points, goal difference, goals for and goals against per match played.
366 Rounded to 2 decimals for display; ranking uses exact fractions, never
367 these. None when the team has not played: a missing rate is not a rate
368 of zero.
369 """
370 played = row["played"]
371 if not played:
372 return dict.fromkeys(PER_MATCH_FIELDS)
373 return {
374 "points_per_match": round(row["points"] / played, 2),
375 "gd_per_match": round(row["goal_difference"] / played, 2),
376 "gf_per_match": round(row["goals_for"] / played, 2),
377 "ga_per_match": round(row["goals_against"] / played, 2),
378 }
381PER_MATCH_FIELDS = ("points_per_match", "gd_per_match", "gf_per_match", "ga_per_match")
384def _rate(total: int, played: int) -> Fraction:
385 return Fraction(total, played) if played else Fraction(0)
388def _venue_rates(results: list[tuple[int, int]]) -> tuple[Fraction, Fraction]:
389 """Goal difference and goals for per match, over home or away results."""
390 n = len(results)
391 return (
392 _rate(sum(gf - ga for gf, ga in results), n),
393 _rate(sum(gf for gf, _ in results), n),
394 )
397def rank_table(
398 table: list[dict],
399 h2h: dict[tuple[str, str], int] | None = None,
400 venue: dict[str, dict[str, list[tuple[int, int]]]] | None = None,
401) -> list[dict]:
402 """
403 Order a table the way MLS NEXT ranks one (2026-27 rules, XIII.l).
405 1. Points per match.
406 2. Head-to-head points, only when exactly two clubs are level. In a
407 tie of three or more it is skipped and never comes back.
408 3. Wins per match (regulation wins: a Flex shootout win is a draw).
409 4. Goal difference per match.
410 5. Goals for per match.
411 6. Away goal difference per match, then away goals for per match.
412 7. Home goal difference per match, then home goals for per match.
414 The rules then use disciplinary points and a coin toss. MT records
415 neither, so a tie that survives all of the above falls back to team
416 name, which keeps the order stable. Teams with no games sort last.
418 h2h maps (team, opponent) to the points the team took from that
419 opponent; venue maps team to its home and away (gf, ga) results. Both
420 come from calculate_standings(); without them those steps are skipped.
421 """
422 h2h = h2h or {}
423 venue = venue or {}
425 def key(row: dict) -> tuple:
426 played = row["played"]
427 sides = venue.get(row["team"], {})
428 away_gd, away_gf = _venue_rates(sides.get("away", []))
429 home_gd, home_gf = _venue_rates(sides.get("home", []))
430 return (
431 played > 0,
432 _rate(row["wins"], played),
433 _rate(row["goal_difference"], played),
434 _rate(row["goals_for"], played),
435 away_gd,
436 away_gf,
437 home_gd,
438 home_gf,
439 )
441 groups: dict[tuple[bool, Fraction], list[dict]] = defaultdict(list)
442 for row in table:
443 groups[(row["played"] > 0, _rate(row["points"], row["played"]))].append(row)
445 ranked: list[dict] = []
446 for _, group in sorted(groups.items(), key=itemgetter(0), reverse=True):
447 group.sort(key=itemgetter("team")) # last resort: name, ascending
448 group.sort(key=key, reverse=True)
449 if len(group) == 2:
450 first, second = group
451 mine = h2h.get((first["team"], second["team"]), 0)
452 theirs = h2h.get((second["team"], first["team"]), 0)
453 if theirs > mine: 453 ↛ 454line 453 didn't jump to line 454 because the condition on line 453 was never true
454 group.reverse()
455 ranked.extend(group)
456 return ranked
459def get_team_form(matches: list[dict], last_n: int = 5) -> dict[str, list[str]]:
460 """
461 Calculate recent form (W/D/L) for each team from completed matches.
463 Args:
464 matches: List of completed match dicts with scores and match_date
465 last_n: Number of recent results to return (default 5)
467 Returns:
468 Dict mapping team name to list of results, most recent last.
469 e.g. {"Northeast IFA": ["W", "L", "D", "W", "W"]}
470 """
471 # Build per-team results ordered by match_date
472 team_results: dict[str, list[tuple[str, str]]] = defaultdict(list)
474 for match in matches:
475 home_team = match["home_team"]["name"]
476 away_team = match["away_team"]["name"]
477 home_score = match.get("home_score")
478 away_score = match.get("away_score")
479 match_date = match.get("match_date", "")
481 if home_score is None or away_score is None: 481 ↛ 482line 481 didn't jump to line 482 because the condition on line 481 was never true
482 continue
484 if home_score > away_score:
485 team_results[home_team].append((match_date, "W"))
486 team_results[away_team].append((match_date, "L"))
487 elif away_score > home_score:
488 team_results[home_team].append((match_date, "L"))
489 team_results[away_team].append((match_date, "W"))
490 else:
491 team_results[home_team].append((match_date, "D"))
492 team_results[away_team].append((match_date, "D"))
494 # Sort by date and take last N
495 form: dict[str, list[str]] = {}
496 for team, results in team_results.items():
497 results.sort(key=itemgetter(0))
498 form[team] = [r for _, r in results[-last_n:]]
500 return form
503def calculate_position_movement(
504 current_matches: list[dict],
505 only_team_ids: set[int] | None = None,
506) -> dict[str, int]:
507 """
508 Calculate position change for each team by comparing standings
509 with and without the most recent match day's results.
511 Args:
512 current_matches: All completed matches (with scores and match_date)
514 Returns:
515 Dict mapping team name to position change (positive = moved up,
516 negative = moved down, 0 = unchanged). Teams with no previous
517 position (first match day) get 0.
518 """
519 # Find distinct match dates
520 match_dates = set()
521 for match in current_matches:
522 md = match.get("match_date")
523 if md and match.get("home_score") is not None: 523 ↛ 521line 523 didn't jump to line 521 because the condition on line 523 was always true
524 match_dates.add(md)
526 if len(match_dates) < 2:
527 # Only one match day — no previous standings to compare
528 return {}
530 latest_date = max(match_dates)
532 # Previous standings: exclude the latest match day
533 previous_matches = [m for m in current_matches if m.get("match_date") != latest_date]
534 previous_table = calculate_standings(previous_matches, only_team_ids)
536 # Build position maps (1-indexed)
537 previous_positions = {row["team"]: i + 1 for i, row in enumerate(previous_table)}
539 current_table = calculate_standings(current_matches, only_team_ids)
540 current_positions = {row["team"]: i + 1 for i, row in enumerate(current_table)}
542 # Calculate movement: previous - current (positive = moved up)
543 movement: dict[str, int] = {}
544 for team, current_pos in current_positions.items():
545 previous_pos = previous_positions.get(team)
546 if previous_pos is None:
547 # New team (first match day for them)
548 movement[team] = 0
549 else:
550 movement[team] = previous_pos - current_pos
552 return movement
555def calculate_standings_with_extras(matches: list[dict], only_team_ids: set[int] | None = None) -> list[dict]:
556 """
557 Calculate standings enriched with position movement and recent form.
559 Wraps calculate_standings() and adds:
560 - form: list of last 5 results (e.g. ["W", "D", "L", "W", "W"])
561 - position_change: int (positive = moved up, negative = down, 0 = same)
563 Args:
564 matches: List of completed match dicts
566 Returns:
567 Same as calculate_standings() but each row also has 'form' and
568 'position_change' keys.
569 """
570 table = calculate_standings(matches, only_team_ids)
571 form = get_team_form(matches)
572 movement = calculate_position_movement(matches, only_team_ids)
574 for row in table:
575 team = row["team"]
576 row["form"] = form.get(team, [])
577 row["position_change"] = movement.get(team, 0)
579 return table