Coverage for mt_tools/my_team.py: 98.01%

123 statements  

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

1"""Which team is "mine" (SB-1317): the one place a caller's team membership is read. 

2 

3Today membership is the caller's profile — `team_id`, or `club_id` alone for club 

4managers and club fans — plus, for fans, the age group they were assigned 

5(`assigned_age_group_id`, SB-1543). Since SB-1608 only an invite or an admin 

6writes those; a fan's own squad choices are follows (alerts), not membership. A team row is a club in one league (IFA 

7Homegrown, IFA Academy); the age group makes it the squad a fan means. This is 

8the one place my-tier and team-write tools read membership. auth.py's 

9`can_manage_team` reads the profile itself, and must change together with this 

10module when membership moves to its own table (SB-1319). A team-write tool still 

11re-checks the resolved team with `can_manage_team` before it 

12writes: knowing your team is not permission to edit it. 

13 

14Most callers have no team, and that is a normal answer (`no_team`), not an error. 

15A profile pointing at a team or club that no longer exists — or one this viewer 

16may not see — is logged and skipped: a dead `team_id` falls back to `club_id`, 

17and with nothing left the answer is `no_team`. A failed read is `unavailable`, 

18never `no_team`: "MT could not check" must not read as "you have no team". 

19 

20Visibility is search_teams': the same team index, so a test team never reaches a 

21real viewer through here either. 

22 

23Active (SB-1322) means the team has at least one match in the current season. 

24It is derived from scraped fixtures, never flagged: nothing to maintain, and a 

25team that returns next season comes back on its own. A club lists only its 

26active teams unless `include_inactive`, and says how many it hid. A caller's own 

27team is always returned, marked inactive if it is: it is still their team. No 

28current season, or a failed activity read, is `unavailable` — never "everything 

29inactive". 

30""" 

31 

32from typing import Any, Literal 

33 

34import structlog 

35from pydantic import BaseModel 

36 

37from mt_ai.tools.deps import ToolDeps 

38from mt_ai.tools.schemas import TeamCandidate, ToolError, Viewer 

39from mt_ai.tools.visibility import TeamIndex, load_team_index 

40 

41logger = structlog.get_logger() 

42 

43 

44class ClubRef(BaseModel): 

45 id: int 

46 name: str 

47 

48 

49class MyTeamResult(BaseModel): 

50 """The caller's team, their club's teams, or neither. 

51 

52 `teams` is one entry per age group a team plays in (as search_teams returns 

53 them): the caller's team for `team` (only the age group they picked, when 

54 they picked one), the club's teams for `club`, and null 

55 for `no_team` or when the read failed. Each entry carries `active`. 

56 

57 A club lists its active teams only, unless include_inactive; `inactive_hidden` 

58 counts the teams (not entries) left out, and is 0 when nothing was. So 

59 `teams: []` with `inactive_hidden: 7` is a club with seven teams and none 

60 playing this season (August, before schedules load), while `teams: []` with 

61 `inactive_hidden: 0` is a club with nothing to show: no teams, or none this 

62 viewer can see. A `team` caller's [] means their team plays in no 

63 competition the viewer can see (all its registrations are test content). 

64 

65 `season` is the current season's name, the season "active" was judged on. 

66 It and `inactive_hidden` are null for `no_team` and on error. 

67 """ 

68 

69 status: Literal["team", "club", "no_team"] | None = None 

70 team_id: int | None = None 

71 club: ClubRef | None = None 

72 teams: list[TeamCandidate] | None = None 

73 season: str | None = None 

74 inactive_hidden: int | None = None 

75 error: ToolError | None = None 

76 

77 

78class _NoCurrentSeason(Exception): 

79 """No season is current: activity cannot be judged, so nothing is called inactive.""" 

80 

81 

82UNAVAILABLE = "Your team is unavailable right now." 

83 

84 

85def resolve_my_team( 

86 deps: ToolDeps, user: dict[str, Any], viewer: Viewer, include_inactive: bool = False 

87) -> MyTeamResult: 

88 """The caller's team from their profile (`team_id`, else `club_id`).""" 

89 team_id = user.get("team_id") 

90 club_id = user.get("club_id") 

91 if team_id is None and club_id is None: 

92 return MyTeamResult(status="no_team") 

93 

94 try: 

95 return _resolve(deps, user, viewer, team_id, club_id, include_inactive) 

96 except _NoCurrentSeason: 

97 logger.warning("my_team_no_current_season", user_id=user.get("user_id")) 

98 except Exception: 

99 logger.exception("resolve_my_team failed", user_id=user.get("user_id")) 

100 return MyTeamResult(error=ToolError(kind="unavailable", message=UNAVAILABLE)) 

101 

102 

103def _resolve( 

104 deps: ToolDeps, 

105 user: dict[str, Any], 

106 viewer: Viewer, 

107 team_id: int | None, 

108 club_id: int | None, 

109 include_inactive: bool, 

110) -> MyTeamResult: 

111 index = load_team_index(deps, viewer) 

112 

113 if team_id is not None: 

114 team = index.teams.get(team_id) 

115 if team is not None: 

116 season = _current_season(deps) 

117 active = deps.matches.team_has_matches_in_season(team_id, season["id"], viewer.include_test) 

118 return MyTeamResult( 

119 status="team", 

120 team_id=team_id, 

121 club=_club_ref(index, team.get("club_id")), 

122 teams=_picked(_marked(index, team, active), user), 

123 season=season.get("name"), 

124 inactive_hidden=0, 

125 ) 

126 logger.warning("my_team_dangling", user_id=user.get("user_id"), team_id=team_id) 

127 

128 if club_id is None: 

129 return MyTeamResult(status="no_team") 

130 club = _club_ref(index, club_id) 

131 if club is None: 

132 logger.warning("my_club_dangling", user_id=user.get("user_id"), club_id=club_id) 

133 return MyTeamResult(status="no_team") 

134 season = _current_season(deps) 

135 teams = sorted( 

136 (t for t in index.teams.values() if t.get("club_id") == club_id), key=lambda t: (t.get("name") or "", t["id"]) 

137 ) 

138 shown: list[TeamCandidate] = [] 

139 hidden = 0 

140 for t in teams: 

141 active = deps.matches.team_has_matches_in_season(t["id"], season["id"], viewer.include_test) 

142 entries = _marked(index, t, active) 

143 if active or include_inactive: 

144 shown.extend(entries) 

145 elif entries: # a team this viewer cannot see at all is not "hidden" 145 ↛ 140line 145 didn't jump to line 140 because the condition on line 145 was always true

146 hidden += 1 

147 return MyTeamResult(status="club", club=club, teams=shown, season=season.get("name"), inactive_hidden=hidden) 

148 

149 

150def _picked(entries: list[TeamCandidate], user: dict[str, Any]) -> list[TeamCandidate]: 

151 """Just the age group the user picked, when they picked one the team still plays. 

152 

153 A pick the team no longer plays (its registration was removed) is ignored, not 

154 an empty answer: the team is still theirs, and the agent can ask which age. 

155 """ 

156 age_group_id = user.get("assigned_age_group_id") 

157 if age_group_id is None: 

158 return entries 

159 chosen = [e for e in entries if e.age_group and e.age_group.id == age_group_id] 

160 if not chosen: 

161 logger.warning("my_team_pick_stale", user_id=user.get("user_id"), age_group_id=age_group_id) 

162 return entries 

163 return chosen 

164 

165 

166# --- picking a team (SB-1543) ------------------------------------------------- 

167 

168# Both spellings: real accounts carry either (SB-668, frontend utils/roles.js). 

169PICK_ROLES = frozenset({"team-fan", "club-fan", "team_fan", "club_fan"}) 

170 

171 

172class TeamPickOptions(BaseModel): 

173 """The squads a fan may follow: their club's teams, one entry per age group. 

174 

175 `status` "no_club" means the profile has no club (or one this viewer can't see): 

176 nothing to pick from. `current_*` is the team a manager or admin assigned, if any. 

177 """ 

178 

179 status: Literal["ok", "no_club"] 

180 club: ClubRef | None = None 

181 options: list[TeamCandidate] = [] 

182 current_team_id: int | None = None 

183 current_age_group_id: int | None = None 

184 

185 

186def club_of(user: dict[str, Any], index: TeamIndex) -> int | None: 

187 """The fan's club: `club_id`, else their team's club.""" 

188 if user.get("club_id") is not None: 

189 return user["club_id"] 

190 team = index.teams.get(user.get("team_id") or 0) 

191 return team.get("club_id") if team else None 

192 

193 

194def team_pick_options(deps: ToolDeps, user: dict[str, Any], viewer: Viewer) -> TeamPickOptions: 

195 """Every (team, age group) in the fan's club this viewer can see, by league then age.""" 

196 index = load_team_index(deps, viewer) 

197 club_id = club_of(user, index) 

198 club = _club_ref(index, club_id) 

199 if club is None: 

200 return TeamPickOptions(status="no_club") 

201 teams = [t for t in index.teams.values() if t.get("club_id") == club_id] 

202 options = [c for t in teams for c in index.candidates(t) if c.age_group is not None] 

203 options.sort(key=lambda c: (c.league_name or "", age_number_of(c), c.name, c.team_id)) 

204 return TeamPickOptions( 

205 status="ok", 

206 club=club, 

207 options=options, 

208 current_team_id=user.get("team_id"), 

209 current_age_group_id=user.get("assigned_age_group_id"), 

210 ) 

211 

212 

213def age_number_of(candidate: TeamCandidate) -> int: 

214 digits = "".join(ch for ch in (candidate.age_group.name if candidate.age_group else "") if ch.isdigit()) 

215 return int(digits) if digits else 999 

216 

217 

218def is_valid_pick(options: TeamPickOptions, team_id: int, age_group_id: int) -> bool: 

219 """Only a team in the fan's own club, at an age group it plays (SB-1608: the 

220 multi-squad picker is limited to the fan's club).""" 

221 return options.status == "ok" and any( 

222 c.team_id == team_id and c.age_group is not None and c.age_group.id == age_group_id for c in options.options 

223 ) 

224 

225 

226def _current_season(deps: ToolDeps) -> dict: 

227 season = deps.seasons.get_current_season() 

228 if not season: 

229 raise _NoCurrentSeason 

230 return season 

231 

232 

233def _marked(index: TeamIndex, team: dict, active: bool) -> list[TeamCandidate]: 

234 return [c.model_copy(update={"active": active}) for c in index.candidates(team)] 

235 

236 

237def _club_ref(index: TeamIndex, club_id: int | None) -> ClubRef | None: 

238 club = index.visible_club(club_id) 

239 return ClubRef(id=club["id"], name=club["name"]) if club else None 

240 

241 

242# --- channel membership (SB-1607) --------------------------------------------- 

243 

244ViewerKind = Literal["admin", "club_manager", "team_manager", "fan", "player", "none"] 

245 

246_KIND_BY_ROLE: dict[str, ViewerKind] = { 

247 "admin": "admin", 

248 "club_manager": "club_manager", 

249 "team-manager": "team_manager", 

250 "team_manager": "team_manager", 

251 "team-player": "player", 

252 "team_player": "player", 

253 **dict.fromkeys(PICK_ROLES, "fan"), 

254} 

255 

256 

257class Squad(BaseModel): 

258 """A squad a player is currently on: a team row at one age group.""" 

259 

260 team_id: int 

261 age_group_id: int | None 

262 club_id: int | None 

263 age_group_name: str | None 

264 

265 

266class ChannelViewer(BaseModel): 

267 """Who is asking, as far as notification channels care. 

268 

269 `club_id` is the profile's club, else the club of the profile's team (a team 

270 manager's My Club). `squads` is only filled for players: where a player plays 

271 is their current squad history, not their profile. 

272 """ 

273 

274 kind: ViewerKind 

275 club_id: int | None = None 

276 team_id: int | None = None 

277 squads: list[Squad] = [] 

278 

279 

280def channel_viewer(user: dict[str, Any], team_club_id: int | None, squads: list[Squad]) -> ChannelViewer: 

281 """The caller's channel standing. `team_club_id` is the club of `user['team_id']`.""" 

282 kind = _KIND_BY_ROLE.get(user.get("role") or "", "none") 

283 club_id = user.get("club_id") 

284 if club_id is None: 284 ↛ 285line 284 didn't jump to line 285 because the condition on line 284 was never true

285 club_id = team_club_id 

286 return ChannelViewer( 

287 kind=kind, 

288 club_id=club_id, 

289 team_id=user.get("team_id"), 

290 squads=squads if kind == "player" else [], 

291 )