Coverage for notifications/formatters.py: 98.21%
157 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"""Plain-text formatters for live-match notifications.
3Pure functions — no I/O. The same text goes to every platform; each
4adapter applies its own escaping at send time.
6All timestamps are rendered in the home club's timezone.
7"""
9from __future__ import annotations
11from datetime import datetime
12from zoneinfo import ZoneInfo # noqa: TC003 — used at runtime for tz conversion
14# Event type → emoji prefix
15_EMOJI = {
16 "kickoff": "⏱",
17 "goal": "⚽",
18 "yellow_card": "🟨",
19 "red_card": "🟥",
20 "halftime": "⏸",
21 "fulltime": "🏁",
22}
25def _matchup_line(match: dict) -> str:
26 return f"{match.get('home_team_name', 'Home')} vs {match.get('away_team_name', 'Away')}"
29def _score_inline(match: dict) -> str:
30 """Compact score for the headline, e.g. 'IFA 2-1 NEFC'.
32 Lives on the first line of the message because that line becomes the Web
33 Push *title* — the only field rendered prominently (and at all, on iOS) when
34 the notification is collapsed. The score must be there, not in the body.
35 """
36 home = match.get("home_score") or 0
37 away = match.get("away_score") or 0
38 return f"{match.get('home_team_name', 'Home')} {home}-{away} {match.get('away_team_name', 'Away')}"
41def _minute_str(event: dict) -> str:
42 """Return a match-minute label like "34'" or "90+3'"."""
43 minute = event.get("match_minute")
44 extra = event.get("extra_time") or 0
45 if minute is None:
46 return ""
47 if extra:
48 return f"{minute}+{extra}'"
49 return f"{minute}'"
52def _competition(match: dict) -> str | None:
53 """Which competition the match belongs to, e.g. 'Homegrown Flex' (SB-1731).
55 Division names alone are ambiguous: Academy and Homegrown both have a
56 "Northeast" and a "New England", and a Homegrown team plays League and
57 Flex fixtures side by side. Flex is stored as its own league ("Flex") with
58 its own match type, but to a fan it is part of Homegrown, so it is named
59 that way. A tournament match is named by its tournament.
60 """
61 if match.get("tournament_name"):
62 return str(match["tournament_name"])
64 match_type = match.get("match_type_name")
65 if match_type == "Friendly":
66 return "Friendly"
68 league = ((match.get("division") or {}).get("leagues") or {}).get("name")
69 if not league or league == "Unknown":
70 league = match.get("home_team_league_name")
72 if league == "Flex" or match_type == "Flex":
73 name = "Homegrown Flex"
74 elif league == "Homegrown":
75 name = "Homegrown League"
76 elif league:
77 name = str(league)
78 else:
79 return None
81 if match_type == "Playoff":
82 name = f"{name} Playoff"
83 return name
86def _tag(match: dict) -> str:
87 """Compact competition/age-group tag line, e.g. 'Homegrown League · U14 · Northeast'."""
88 parts: list[str] = []
89 competition = _competition(match)
90 if competition:
91 parts.append(competition)
92 age_group = match.get("age_group_name")
93 division = match.get("division_name")
94 if age_group:
95 parts.append(str(age_group))
96 if division and division != "Unknown":
97 parts.append(str(division))
98 return " · ".join(parts)
101def _kickoff_time_str(match: dict, tz: ZoneInfo) -> str:
102 raw = match.get("scheduled_kickoff") or match.get("kickoff_time")
103 if not raw:
104 return ""
105 try:
106 dt = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
107 except (ValueError, TypeError):
108 return ""
109 local = dt.astimezone(tz)
110 return local.strftime("%-I:%M %p %Z").strip()
113def format_kickoff(match: dict, tz: ZoneInfo) -> str:
114 """Match has kicked off."""
115 lines = [f"{_EMOJI['kickoff']} KICKOFF — {_matchup_line(match)}"]
116 tag = _tag(match)
117 if tag:
118 lines.append(tag)
119 time_str = _kickoff_time_str(match, tz)
120 if time_str:
121 lines.append(time_str)
122 return "\n".join(lines)
125def format_goal(event: dict, match: dict, tz: ZoneInfo) -> str:
126 """A goal was scored. `event` carries team_id, player_name, minute, extra."""
127 scoring_team_id = event.get("team_id")
128 if scoring_team_id == match.get("home_team_id"):
129 scoring_team = match.get("home_team_name", "Home")
130 elif scoring_team_id == match.get("away_team_id"):
131 scoring_team = match.get("away_team_name", "Away")
132 else:
133 scoring_team = "Unknown"
135 player = event.get("player_name") or "Unknown player"
136 minute = _minute_str(event)
137 minute_suffix = f" ({minute})" if minute else ""
139 # Headline = score (becomes the push title); scorer drops to the body.
140 lines = [f"{_EMOJI['goal']} {_score_inline(match)}{minute_suffix}"]
141 lines.append(f"{player} ({scoring_team})")
142 return "\n".join(lines)
145def format_card(event: dict, match: dict, tz: ZoneInfo) -> str:
146 """A yellow or red card was shown."""
147 card_type = event.get("card_type", "yellow_card")
148 emoji = _EMOJI.get(card_type, "🟨")
149 label = "Red card" if card_type == "red_card" else "Yellow card"
151 carded_team_id = event.get("team_id")
152 if carded_team_id == match.get("home_team_id"):
153 team = match.get("home_team_name", "Home")
154 elif carded_team_id == match.get("away_team_id"):
155 team = match.get("away_team_name", "Away")
156 else:
157 team = "Unknown"
159 player = event.get("player_name") or "Unknown player"
160 minute = _minute_str(event)
161 minute_suffix = f" {minute}" if minute else ""
163 lines = [f"{emoji} {label} — {_matchup_line(match)}"]
164 lines.append(f"{player} ({team}){minute_suffix}")
165 return "\n".join(lines)
168def format_halftime(match: dict, tz: ZoneInfo) -> str:
169 """Halftime has begun. Score-first headline."""
170 lines = [f"{_EMOJI['halftime']} HT · {_score_inline(match)}"]
171 tag = _tag(match)
172 if tag:
173 lines.append(tag)
174 return "\n".join(lines)
177def format_fulltime(match: dict, tz: ZoneInfo) -> str:
178 """Final whistle. Score-first headline."""
179 lines = [f"{_EMOJI['fulltime']} FT · {_score_inline(match)}"]
180 tag = _tag(match)
181 if tag:
182 lines.append(tag)
183 return "\n".join(lines)
186EVENT_FORMATTERS = {
187 "kickoff": format_kickoff,
188 "halftime": format_halftime,
189 "fulltime": format_fulltime,
190}
193def thread_title(match: dict, tz: ZoneInfo) -> str:
194 """A match thread's name (SB-1606), e.g. 'IFA vs NEFC · U15 · Sat Nov 14'. Max 100 chars."""
195 parts = [_matchup_line(match)]
196 age = match.get("age_group_name")
197 if age:
198 parts.append(str(age))
199 raw = match.get("scheduled_kickoff") or match.get("match_date")
200 if raw:
201 try:
202 when = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
203 if when.tzinfo is not None: 203 ↛ 205line 203 didn't jump to line 205 because the condition on line 203 was always true
204 when = when.astimezone(tz)
205 parts.append(when.strftime("%a %b %-d"))
206 except (ValueError, TypeError):
207 pass
208 return " · ".join(parts)[:100]
211def format_lineup(event: dict, match: dict, tz: ZoneInfo) -> str | None:
212 """A squad's lineup was saved (SB-1610). Player channels only.
214 Names stay in Missing Table: the post says the lineup is up, with the
215 formation and how many players are in it, not who. `event` carries
216 team_id, formation and player_count; no players means nothing to post.
217 """
218 count = event.get("player_count") or 0
219 if count <= 0:
220 return None
221 team_id = event.get("team_id")
222 if team_id == match.get("home_team_id"):
223 team = match.get("home_team_name", "Home")
224 elif team_id == match.get("away_team_id"):
225 team = match.get("away_team_name", "Away")
226 else:
227 return None
228 lines = [f"📋 LINEUP — {_matchup_line(match)}"]
229 tag = _tag(match)
230 if tag:
231 lines.append(tag)
232 formation = event.get("formation")
233 detail = f"{team} lineup is up in Missing Table: {count} player{'s' if count != 1 else ''}"
234 lines.append(f"{detail}, {formation}" if formation else detail)
235 time_str = _kickoff_time_str(match, tz)
236 if time_str:
237 lines.append(f"Kickoff {time_str}")
238 return "\n".join(lines)
241def format_event(event_type: str, match: dict, extra: dict | None, tz: ZoneInfo) -> str | None:
242 """Entry point: dispatch to the right formatter. Returns None if unsupported."""
243 if event_type == "lineup":
244 return format_lineup(extra or {}, match, tz)
245 if event_type == "goal":
246 return format_goal(extra or {}, match, tz)
247 if event_type in {"yellow_card", "red_card"}:
248 merged = {**(extra or {}), "card_type": event_type}
249 return format_card(merged, match, tz)
250 formatter = EVENT_FORMATTERS.get(event_type)
251 if formatter is None:
252 return None
253 return formatter(match, tz)