Coverage for dao/ingest_plan.py: 95.48%

464 statements  

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

1"""Planning the teams and aliases a tournament needs before it is ingested (SB-1763). 

2 

3Tournament ingest never creates a team: a name it cannot place becomes an 

4`ingest_failures` row (SB-1748). For an event the size of MLS NEXT Fest that 

5is hundreds of names, most of them a club's Academy side that MT only holds as 

6its Homegrown team. This module turns the list of names a tournament uses into 

7a report and a list of proposed actions for a person to review. Nothing here 

8is applied by planning, and nothing is applied until a reviewer marks it 

9`approved`. 

10 

11Pure: no database, no DAO imports. Each name's verdict comes from the 

12resolver ingest itself uses (`TeamDAO.resolve_tournament_team`) and is handed 

13in, so "resolved" in a plan means what ingest will do. What is decided here is 

14only what to *propose* for a name that failed — and never from a near match: 

15similar names are shown to the reviewer, not acted on. 

16""" 

17 

18from __future__ import annotations 

19 

20import hashlib 

21import json 

22import re 

23from dataclasses import dataclass, field 

24from typing import TYPE_CHECKING, Any 

25 

26from dao.team_sides import ( 

27 AMBIGUOUS, 

28 MISSING, 

29 RESOLVED, 

30 WRONG_SIDE, 

31 league_named, 

32 team_sides, 

33 top_level_league, 

34) 

35 

36if TYPE_CHECKING: 

37 from collections.abc import Callable, Iterable, Mapping 

38 

39# The message's age group is not one MT has: ingest drops the match before it 

40# looks at either team. 

41UNKNOWN_AGE_GROUP = "unknown_age_group" 

42 

43ALIAS = "alias" 

44CREATE_TEAM = "create_team" 

45ACTION_TYPES = (ALIAS, CREATE_TEAM) 

46 

47# A freshly generated plan holds only the first two. `approved` is written by 

48# the reviewer, by hand, and is the only status that is ever applied. 

49PROPOSED = "proposed" 

50NEEDS_REVIEW = "needs_review" 

51APPROVED = "approved" 

52 

53NO_HINT = "no hint" 

54 

55# A club's Academy-side team is stored as "<Club> Academy" ("IFA Academy", 

56# "FC Greater Boston Bolts Academy"). There is no such convention for a 

57# Homegrown-side team, so a name proposed for one is always for review. 

58CONVENTION_SIDE = "Academy" 

59 

60_PLACEHOLDERS = frozenset({"tbd", "tba", "bye"}) 

61# The select teams of a "Best Of" fixture: "East AD One", "West HD Two". 

62_SELECT_TEAM = re.compile(r"^(east|west|north|south|central) (ad|hd) \w+$") 

63 

64 

65class PlanInputError(ValueError): 

66 """The teams or brackets input is not in a shape this can read.""" 

67 

68 

69def normalise(name: str | None) -> str: 

70 """A name with its whitespace collapsed, as the resolver reads it.""" 

71 return " ".join((name or "").split()) 

72 

73 

74def name_key(name: str | None) -> str: 

75 """What two spellings of one name share: no case, no extra whitespace.""" 

76 return normalise(name).casefold() 

77 

78 

79def is_placeholder(name: str | None) -> bool: 

80 """Whether a name stands for a team not yet known, or for no club at all. 

81 

82 `TBD` in a bracket slot, and the select sides of a showcase game. Neither 

83 is a team MT should hold, so neither gets an action. 

84 """ 

85 key = name_key(name) 

86 return key in _PLACEHOLDERS or bool(_SELECT_TEAM.match(key)) 

87 

88 

89@dataclass(frozen=True) 

90class Entry: 

91 """One name a tournament uses, at one age group, on one side.""" 

92 

93 name: str 

94 age_group: str 

95 league: str | None = None 

96 

97 @property 

98 def key(self) -> tuple[str, str, str]: 

99 return (name_key(self.name), name_key(self.age_group), name_key(self.league)) 

100 

101 def as_dict(self) -> dict[str, Any]: 

102 return {"name": self.name, "age_group": self.age_group, "league": self.league} 

103 

104 

105@dataclass(frozen=True) 

106class Verdict: 

107 """What the resolver said about one entry. 

108 

109 `candidate_ids` is the teams the resolver found for the name before the 

110 side guard — the team that owns the name on the other side, when the 

111 status is WRONG_SIDE. 

112 """ 

113 

114 status: str 

115 team_id: int | None = None 

116 reason: str | None = None 

117 candidate_ids: tuple[int, ...] = () 

118 

119 

120@dataclass 

121class World: 

122 """What MT holds, as plain rows. 

123 

124 `teams` rows carry `id`, `name`, `club_id`, `league_id` and `mappings`, a 

125 list of `(age_group_id, league_id)` — the league being the mapped 

126 division's. `leagues` maps id → a row with `name` and `parent_league_id`, 

127 `divisions` rows carry `id`, `name`, `league_id`, `clubs` maps id → name 

128 and `age_groups` maps id → name. 

129 """ 

130 

131 teams: list[dict] = field(default_factory=list) 

132 clubs: dict[int, str] = field(default_factory=dict) 

133 leagues: dict[int, dict] = field(default_factory=dict) 

134 divisions: list[dict] = field(default_factory=list) 

135 age_groups: dict[int, str] = field(default_factory=dict) 

136 

137 def age_group_id(self, name: str | None) -> int | None: 

138 wanted = name_key(name) 

139 if not wanted: 139 ↛ 140line 139 didn't jump to line 140 because the condition on line 139 was never true

140 return None 

141 for age_group_id, age_name in self.age_groups.items(): 

142 if name_key(age_name) == wanted: 

143 return age_group_id 

144 return None 

145 

146 

147# --- Reading the inputs ----------------------------------------------------- 

148 

149 

150def _text(item: Mapping, key: str) -> str | None: 

151 value = item.get(key) 

152 if value is None: 

153 return None 

154 if not isinstance(value, str): 

155 raise PlanInputError(f"'{key}' must be text, not {type(value).__name__}") 

156 return normalise(value) or None 

157 

158 

159def parse_teams_input(items: Any) -> tuple[list[Entry], list[dict]]: 

160 """Read the `--teams` input into distinct entries and the matches it carries. 

161 

162 A list whose items are either: 

163 

164 - a scraper message, as `match-scraper-agent scrape-event --json` prints 

165 them: `home_team`, `away_team`, `age_group`, and optionally `league` 

166 and `competition`. Any other field is ignored. 

167 - a hand-made `{"name", "age_group", "league"}`, `league` optional. 

168 

169 The two may be mixed. Entries are distinct by name, age group and league, 

170 compared without case or extra whitespace; the first spelling is kept. 

171 Returns `(entries, matches)`, `matches` being one 

172 `{"home": Entry, "away": Entry, "competition"}` per message. 

173 """ 

174 if not isinstance(items, list): 

175 raise PlanInputError("the teams input must be a JSON list") 

176 

177 entries: dict[tuple[str, str, str], Entry] = {} 

178 matches: list[dict] = [] 

179 

180 def keep(name: str | None, age_group: str | None, league: str | None, where: str) -> Entry: 

181 if not name: 

182 raise PlanInputError(f"{where}: a team name is missing") 

183 if not age_group: 

184 raise PlanInputError(f"{where}: 'age_group' is missing") 

185 entry = Entry(name, age_group, league) 

186 return entries.setdefault(entry.key, entry) 

187 

188 for index, item in enumerate(items): 

189 where = f"teams[{index}]" 

190 if not isinstance(item, dict): 

191 raise PlanInputError(f"{where}: expected an object") 

192 try: 

193 age_group, league = _text(item, "age_group"), _text(item, "league") 

194 if "home_team" in item or "away_team" in item: 

195 home = keep(_text(item, "home_team"), age_group, league, where) 

196 away = keep(_text(item, "away_team"), age_group, league, where) 

197 matches.append({"home": home, "away": away, "competition": _text(item, "competition")}) 

198 elif "name" in item: 

199 keep(_text(item, "name"), age_group, league, where) 

200 else: 

201 raise PlanInputError(f"{where}: expected 'home_team' and 'away_team', or 'name'") 

202 except PlanInputError as exc: 

203 if str(exc).startswith(where): 

204 raise 

205 raise PlanInputError(f"{where}: {exc}") from exc 

206 

207 return list(entries.values()), matches 

208 

209 

210def parse_brackets_input(items: Any) -> list[dict]: 

211 """Read the `--brackets` input: which conference each team plays in. 

212 

213 A list of `{"league", "conference", "age_group", "teams": [names]}` — one 

214 per league standings bracket. Only the shape is checked here; whether MT 

215 has the league and conference is decided against the database, and one it 

216 does not have is reported, never created. 

217 """ 

218 if items is None: 

219 return [] 

220 if not isinstance(items, list): 

221 raise PlanInputError("the brackets input must be a JSON list") 

222 

223 brackets = [] 

224 for index, item in enumerate(items): 

225 where = f"brackets[{index}]" 

226 if not isinstance(item, dict): 

227 raise PlanInputError(f"{where}: expected an object") 

228 try: 

229 row = {key: _text(item, key) for key in ("league", "conference", "age_group")} 

230 except PlanInputError as exc: 

231 raise PlanInputError(f"{where}: {exc}") from exc 

232 for key, value in row.items(): 

233 if not value: 

234 raise PlanInputError(f"{where}: '{key}' is missing") 

235 teams = item.get("teams") 

236 if not isinstance(teams, list) or not all(isinstance(name, str) for name in teams): 

237 raise PlanInputError(f"{where}: 'teams' must be a list of names") 

238 row["teams"] = [normalise(name) for name in teams if normalise(name)] 

239 brackets.append(row) 

240 return brackets 

241 

242 

243# --- Planning --------------------------------------------------------------- 

244 

245 

246@dataclass 

247class _Group: 

248 """The failing entries that one action would fix: one name on one side.""" 

249 

250 name: str 

251 league_id: int | None 

252 league: str | None 

253 side: str | None 

254 entries: list[Entry] = field(default_factory=list) 

255 

256 

257class _Planner: 

258 def __init__( 

259 self, 

260 entries: list[Entry], 

261 verdicts: Mapping[tuple[str, str, str], Verdict], 

262 world: World, 

263 brackets: list[dict], 

264 near_matches: Callable[[str], list[dict]] | None, 

265 ): 

266 self.entries = entries 

267 self.verdicts = verdicts 

268 self.world = world 

269 self.near_matches = near_matches 

270 self.teams_by_id = {team["id"]: team for team in world.teams} 

271 self.teams_by_name: dict[str, list[dict]] = {} 

272 for team in world.teams: 

273 self.teams_by_name.setdefault(name_key(team.get("name")), []).append(team) 

274 self.clubs_by_name = {name_key(name): club_id for club_id, name in world.clubs.items()} 

275 self.actions: list[dict] = [] 

276 # entry key → "alias_fixable" | "needs_create" | "unknown", for the report. 

277 self.outcome: dict[tuple[str, str, str], str] = {} 

278 self.unknown: list[dict] = [] 

279 self.unknown_conferences: list[dict] = [] 

280 self.conferences = self._index_brackets(brackets) 

281 

282 # -- brackets -- 

283 

284 def _index_brackets(self, brackets: list[dict]) -> dict[tuple[str, str, str], list[dict]]: 

285 """(side, age group, name) → the conferences that name plays in there.""" 

286 index: dict[tuple[str, str, str], list[dict]] = {} 

287 reported: set[tuple[str, str, str]] = set() 

288 

289 def report(row: dict, reason: str) -> None: 

290 key = (name_key(row["league"]), name_key(row["conference"]), reason) 

291 if key not in reported: 291 ↛ exitline 291 didn't return from function 'report' because the condition on line 291 was always true

292 reported.add(key) 

293 self.unknown_conferences.append( 

294 {"league": row["league"], "conference": row["conference"], "reason": reason} 

295 ) 

296 

297 for row in brackets: 

298 league_id = league_named(row["league"], self.world.leagues) 

299 if league_id is None: 

300 report(row, "MT has no league by that name") 

301 continue 

302 division = next( 

303 ( 

304 d 

305 for d in self.world.divisions 

306 if d.get("league_id") == league_id and name_key(d.get("name")) == name_key(row["conference"]) 

307 ), 

308 None, 

309 ) 

310 if division is None: 

311 report(row, "MT has no conference by that name in that league") 

312 continue 

313 if self.world.age_group_id(row["age_group"]) is None: 313 ↛ 314line 313 didn't jump to line 314 because the condition on line 313 was never true

314 report(row, f"MT has no age group '{row['age_group']}'") 

315 continue 

316 side = top_level_league(league_id, self.world.leagues) 

317 placement = {"league": self.world.leagues[league_id]["name"], "conference": division["name"]} 

318 for name in row["teams"]: 

319 found = index.setdefault((name_key(side), name_key(row["age_group"]), name_key(name)), []) 

320 if placement not in found: 320 ↛ 318line 320 didn't jump to line 318 because the condition on line 320 was always true

321 found.append(placement) 

322 return index 

323 

324 def _placements(self, group: _Group) -> list[dict]: 

325 placements = [] 

326 for age_group in _age_groups(group.entries): 

327 for found in self.conferences.get((name_key(group.side), name_key(age_group), name_key(group.name)), []): 

328 placements.append({"age_group": age_group, **found}) 

329 return placements 

330 

331 # -- sides -- 

332 

333 def _sides(self, team: dict, age_group_ids: Iterable[int | None]) -> frozenset[str]: 

334 """Every side a team answers to at any of these age groups.""" 

335 sides: set[str] = set() 

336 for age_group_id in age_group_ids: 

337 sides |= team_sides(team.get("mappings") or [], team.get("league_id"), age_group_id, self.world.leagues) 

338 return frozenset(sides) 

339 

340 def _registered_on(self, team: dict, side: str) -> list[str]: 

341 """The age groups a team is registered at on this side, by name.""" 

342 ages = { 

343 self.world.age_groups.get(age_group_id) 

344 for age_group_id, league_id in team.get("mappings") or [] 

345 if name_key(top_level_league(league_id, self.world.leagues)) == name_key(side) 

346 } 

347 return sorted(age for age in ages if age) 

348 

349 def _candidate(self, team: dict, side: str | None) -> dict: 

350 row = {"team_id": team["id"], "team_name": team.get("name")} 

351 if side: 351 ↛ 353line 351 didn't jump to line 353 because the condition on line 351 was always true

352 row["registered_age_groups"] = self._registered_on(team, side) 

353 return row 

354 

355 # -- the plan -- 

356 

357 def run(self) -> None: 

358 groups: dict[tuple[str, int | None], _Group] = {} 

359 unhinted: dict[str, list[Entry]] = {} 

360 for entry in self.entries: 

361 verdict = self.verdicts[entry.key] 

362 if verdict.status not in (WRONG_SIDE, MISSING): 

363 continue 

364 if is_placeholder(entry.name): 

365 self._unknown(entry, "placeholder name, not a team") 

366 continue 

367 if not entry.league: 

368 unhinted.setdefault(name_key(entry.name), []).append(entry) 

369 continue 

370 league_id = league_named(entry.league, self.world.leagues) 

371 group = groups.setdefault( 

372 (name_key(entry.name), league_id), 

373 _Group( 

374 name=entry.name, 

375 league_id=league_id, 

376 league=self.world.leagues[league_id]["name"], 

377 side=top_level_league(league_id, self.world.leagues), 

378 ), 

379 ) 

380 group.entries.append(entry) 

381 

382 for group in groups.values(): 

383 self._plan_group(group) 

384 for key, entries in unhinted.items(): 

385 self._plan_unhinted(key, entries) 

386 for number, action in enumerate(self.actions, start=1): 

387 action["id"] = f"a{number:03d}" 

388 self._flag_clashes() 

389 

390 def _flag_clashes(self) -> None: 

391 """Two actions that would make the same team, or the same club. 

392 

393 The first keeps its status; each later one is for review, naming the 

394 action it clashes with. Applied as they stand, the second would be 

395 refused or would quietly share the first one's row. 

396 """ 

397 for key, what in (("team_name", "team"), ("new_club_name", "club")): 

398 first: dict[str, str] = {} 

399 for action in self.actions: 

400 if action["type"] != CREATE_TEAM or not action.get(key): 

401 continue 

402 earlier = first.setdefault(name_key(action[key]), action["id"]) 

403 if earlier == action["id"]: 

404 continue 

405 concern = f"action {earlier} proposes the same new {what}, '{normalise(action[key])}'" 

406 if action["status"] == PROPOSED: 

407 action["status"] = NEEDS_REVIEW 

408 action["reason"] = f"{action['reason']} Needs review: {concern}." 

409 else: 

410 action["reason"] = f"{action['reason'].rstrip('.')}; {concern}." 

411 

412 def _unknown(self, entry: Entry, reason: str) -> None: 

413 self.outcome[entry.key] = "unknown" 

414 self.unknown.append({**entry.as_dict(), "reason": reason}) 

415 

416 def _plan_group(self, group: _Group) -> None: 

417 age_group_ids = [self.world.age_group_id(entry.age_group) for entry in group.entries] 

418 candidate_ids = sorted( 

419 {team_id for entry in group.entries for team_id in self.verdicts[entry.key].candidate_ids} 

420 ) 

421 owners = [self.teams_by_id[team_id] for team_id in candidate_ids if team_id in self.teams_by_id] 

422 

423 if not owners: 

424 self._create_unknown(group) 

425 return 

426 

427 if not any(self._sides(team, age_group_ids) for team in owners): 

428 ids = ", ".join(str(team["id"]) for team in owners) 

429 for entry in group.entries: 

430 self._unknown( 

431 entry, 

432 f"team {ids} has this name but no league or division registration: " 

433 "register it rather than create another", 

434 ) 

435 return 

436 

437 club_ids = sorted({team["club_id"] for team in owners if team.get("club_id") is not None}) 

438 owner_ids = {team["id"] for team in owners} 

439 siblings = [ 

440 team 

441 for team in self.world.teams 

442 if team.get("club_id") in club_ids 

443 and team["id"] not in owner_ids 

444 and name_key(group.side) in {name_key(side) for side in self._sides(team, age_group_ids)} 

445 ] 

446 if siblings: 

447 self._alias(group, owners, siblings, age_group_ids) 

448 else: 

449 self._create_side_team(group, owners, club_ids) 

450 

451 def _redirects(self, group: _Group, team_id: int | None) -> str | None: 

452 """Why a league-scoped alias for this name would change a name that works. 

453 

454 The alias is rule 1 of the resolver at every age group, so it also 

455 moves any age group where the same name already resolves on this side. 

456 """ 

457 moved = [] 

458 for entry in self.entries: 

459 if name_key(entry.name) != name_key(group.name) or not entry.league: 

460 continue 

461 if league_named(entry.league, self.world.leagues) != group.league_id: 

462 continue 

463 verdict = self.verdicts[entry.key] 

464 if verdict.status == RESOLVED and verdict.team_id != team_id: 

465 moved.append(f"{entry.age_group} (team {verdict.team_id})") 

466 if not moved: 

467 return None 

468 return f"the name already resolves on this side at {', '.join(sorted(moved))}, and an alias would move it" 

469 

470 def _base(self, kind: str, group: _Group) -> dict: 

471 return { 

472 "id": "", 

473 "type": kind, 

474 "status": PROPOSED, 

475 "reason": "", 

476 "external_name": normalise(group.name), 

477 "league": group.league, 

478 } 

479 

480 def _finish(self, action: dict, group: _Group, outcome: str, concerns: list[str]) -> None: 

481 if concerns: 

482 action["status"] = NEEDS_REVIEW 

483 action["reason"] = f"{action['reason']} Needs review: {'; '.join(concerns)}." 

484 action["fixes"] = [{**entry.as_dict(), "status": self.verdicts[entry.key].status} for entry in group.entries] 

485 for entry in group.entries: 

486 self.outcome[entry.key] = outcome 

487 self.actions.append(action) 

488 

489 def _alias(self, group: _Group, owners: list[dict], siblings: list[dict], age_group_ids: list) -> None: 

490 action = self._base(ALIAS, group) 

491 owner = owners[0] 

492 club = self.world.clubs.get(owner.get("club_id"), f"club {owner.get('club_id')}") 

493 concerns = [] 

494 if len(siblings) == 1: 

495 target = siblings[0] 

496 action["team_id"] = target["id"] 

497 action["team_name"] = target.get("name") 

498 action["reason"] = ( 

499 f"'{group.name}' is team {owner['id']} on the other side; {club} has one {group.side} " 

500 f"team, '{target.get('name')}' ({target['id']})." 

501 ) 

502 if {name_key(side) for side in self._sides(target, age_group_ids)} != {name_key(group.side)}: 502 ↛ 503line 502 didn't jump to line 503 because the condition on line 502 was never true

503 concerns.append(f"team {target['id']} is registered on more than the {group.side} side") 

504 redirect = self._redirects(group, target["id"]) 

505 else: 

506 action["team_id"] = None 

507 action["team_name"] = None 

508 action["reason"] = ( 

509 f"'{group.name}' is team {owner['id']} on the other side; {club} has {len(siblings)} " 

510 f"{group.side} teams." 

511 ) 

512 concerns.append("pick one of the candidates and set team_id and team_name") 

513 redirect = self._redirects(group, None) 

514 if redirect: 

515 concerns.append(redirect) 

516 action["candidates"] = [self._candidate(team, group.side) for team in sorted(siblings, key=lambda t: t["id"])] 

517 self._finish(action, group, "alias_fixable", concerns) 

518 

519 def _team_name_concerns(self, team_name: str) -> list[str]: 

520 taken = self.teams_by_name.get(name_key(team_name)) or [] 

521 if not taken: 

522 return [] 

523 ids = ", ".join(str(team["id"]) for team in taken) 

524 return [f"the name '{team_name}' is already taken by team {ids}"] 

525 

526 def _create_base(self, group: _Group) -> tuple[dict, list[str]]: 

527 """A create action, in the side's own league. 

528 

529 `teams.league_id` is the side, never a child league: a hint of Flex 

530 makes a Homegrown team, and that is said. 

531 """ 

532 action = self._base(CREATE_TEAM, group) 

533 action["league"] = group.side 

534 concerns = [] 

535 if name_key(group.league) != name_key(group.side): 

536 concerns.append(f"the feed says {group.league}; the team and its alias are made in {group.side}") 

537 return action, concerns 

538 

539 def _create_side_team(self, group: _Group, owners: list[dict], club_ids: list[int]) -> None: 

540 action, concerns = self._create_base(group) 

541 owner = owners[0] 

542 if len(club_ids) == 1: 542 ↛ 549line 542 didn't jump to line 549 because the condition on line 542 was always true

543 club_name = self.world.clubs.get(club_ids[0]) or normalise(group.name) 

544 action.update(club_id=club_ids[0], club_name=club_name, new_club_name=None) 

545 action["reason"] = ( 

546 f"'{group.name}' is team {owner['id']} on the other side; {club_name} has no {group.side} team." 

547 ) 

548 else: 

549 club_name = normalise(group.name) 

550 action.update(club_id=None, club_name=None, new_club_name=club_name) 

551 action["reason"] = f"'{group.name}' is team {owner['id']} on the other side." 

552 if club_ids: 

553 ids = ", ".join(map(str, club_ids)) 

554 concerns.append(f"teams with this name belong to clubs {ids}: set club_id and club_name") 

555 else: 

556 concerns.append(f"team {owner['id']} has no club: set club_id and club_name, or accept a new club") 

557 

558 action["team_name"] = f"{club_name} {group.side}" 

559 if name_key(group.side) != name_key(CONVENTION_SIDE): 

560 concerns.append(f"there is no naming convention for a {group.side}-side team") 

561 if name_key(club_name).endswith(name_key(group.side)): 

562 concerns.append(f"the club's name already ends in '{group.side}'") 

563 concerns += self._team_name_concerns(action["team_name"]) 

564 redirect = self._redirects(group, None) 

565 if redirect: 565 ↛ 566line 565 didn't jump to line 566 because the condition on line 565 was never true

566 concerns.append(redirect) 

567 self._place(action, group) 

568 self._finish(action, group, "needs_create", concerns) 

569 

570 def _create_unknown(self, group: _Group) -> None: 

571 """A name MT has no team for. A new club and team, always for review.""" 

572 action, concerns = self._create_base(group) 

573 name = normalise(group.name) 

574 club_id = self.clubs_by_name.get(name_key(name)) 

575 concerns.append("MT has no team by this name: check the near matches before creating one") 

576 if club_id is not None: 

577 action.update(club_id=club_id, club_name=self.world.clubs[club_id], new_club_name=None) 

578 action["reason"] = f"MT has no team named '{name}'; the club exists ({club_id}) with no such team." 

579 else: 

580 action.update(club_id=None, club_name=None, new_club_name=name) 

581 action["reason"] = f"MT has no team or club named '{name}'." 

582 if group.league is None: 

583 concerns.append("the feed names no side: the team gets no league unless one is set") 

584 action["team_name"] = name 

585 concerns += self._team_name_concerns(name) 

586 self._place(action, group) 

587 action["near_matches"] = list(self.near_matches(name)) if self.near_matches else [] 

588 self._finish(action, group, "needs_create", concerns) 

589 

590 def _place(self, action: dict, group: _Group) -> None: 

591 action["age_groups"] = _age_groups(group.entries) 

592 action["placements"] = self._placements(group) if group.side else [] 

593 

594 def _plan_unhinted(self, key: str, entries: list[Entry]) -> None: 

595 """Names sent with no side that MT has no team for. 

596 

597 With no hint a single team by the name is the answer, so a team 

598 created for the same name on one side fixes these too. Two would make 

599 it ambiguous, and that is said rather than planned. 

600 """ 

601 creating = [ 

602 action for action in self.actions if action["type"] == CREATE_TEAM and name_key(action["team_name"]) == key 

603 ] 

604 if len(creating) == 1: 

605 action = creating[0] 

606 action["fixes"] += [{**entry.as_dict(), "status": self.verdicts[entry.key].status} for entry in entries] 

607 for entry in entries: 

608 self.outcome[entry.key] = "needs_create" 

609 return 

610 if creating: 610 ↛ 611line 610 didn't jump to line 611 because the condition on line 610 was never true

611 for entry in entries: 

612 self._unknown(entry, "sent with no side, and the plan creates a team by this name on each side") 

613 return 

614 group = _Group(name=entries[0].name, league_id=None, league=None, side=None, entries=list(entries)) 

615 self._create_unknown(group) 

616 

617 

618def _age_groups(entries: Iterable[Entry]) -> list[str]: 

619 seen: dict[str, str] = {} 

620 for entry in entries: 

621 seen.setdefault(name_key(entry.age_group), entry.age_group) 

622 return sorted(seen.values()) 

623 

624 

625def side_label(league: str | None) -> str: 

626 """The report's row for an entry: its league as sent, or "no hint".""" 

627 return normalise(league) or NO_HINT 

628 

629 

630def build_plan( 

631 entries: list[Entry], 

632 matches: list[dict], 

633 verdicts: Mapping[tuple[str, str, str], Verdict], 

634 world: World, 

635 brackets: list[dict] | None = None, 

636 near_matches: Callable[[str], list[dict]] | None = None, 

637) -> dict: 

638 """The report and the proposed actions for a tournament's team names. 

639 

640 `verdicts` maps each entry's `key` to what the resolver said about it. 

641 `near_matches` is asked for teams with a similar name, only for a name MT 

642 has no team for; what it returns is shown to the reviewer and never acted 

643 on. Returns `{"report", "actions"}`, both plain JSON-ready data. 

644 """ 

645 planner = _Planner(entries, verdicts, world, brackets or [], near_matches) 

646 planner.run() 

647 

648 sides: dict[str, dict] = {} 

649 ambiguous = [] 

650 for entry in entries: 

651 verdict = verdicts[entry.key] 

652 side = sides.setdefault( 

653 side_label(entry.league), 

654 { 

655 "entries": 0, 

656 "resolved": 0, 

657 "ambiguous": 0, 

658 "missing": {"total": 0, "alias_fixable": 0, "needs_create": 0, "unknown": 0}, 

659 "unknown_league": 0, 

660 "unknown_age_group": 0, 

661 "resolver": {"wrong_side": 0, "missing": 0}, 

662 }, 

663 ) 

664 side["entries"] += 1 

665 if verdict.status in (WRONG_SIDE, MISSING): 

666 side["resolver"][verdict.status] += 1 

667 side["missing"]["total"] += 1 

668 side["missing"][planner.outcome[entry.key]] += 1 

669 else: 

670 side[verdict.status] += 1 

671 if verdict.status == AMBIGUOUS: 

672 ambiguous.append({**entry.as_dict(), "reason": verdict.reason}) 

673 

674 fixed = { 

675 (name_key(fix["name"]), name_key(fix["age_group"]), name_key(fix["league"])) 

676 for action in planner.actions 

677 for fix in action["fixes"] 

678 } 

679 

680 def lands(entry: Entry, after: bool) -> bool: 

681 return verdicts[entry.key].status == RESOLVED or (after and entry.key in fixed) 

682 

683 match_report = None 

684 if matches: 

685 match_report = { 

686 "total": len(matches), 

687 "would_land": sum(lands(m["home"], False) and lands(m["away"], False) for m in matches), 

688 "would_land_after_plan": sum(lands(m["home"], True) and lands(m["away"], True) for m in matches), 

689 } 

690 

691 placed: dict[tuple[str, str], dict] = {} 

692 unplaced = 0 

693 for action in planner.actions: 

694 if action["type"] != CREATE_TEAM: 

695 continue 

696 if not action["placements"]: 

697 unplaced += 1 

698 for league, conference in {(p["league"], p["conference"]) for p in action["placements"]}: 

699 row = placed.setdefault( 

700 (league, conference), {"league": league, "conference": conference, "teams": 0, "registrations": 0} 

701 ) 

702 row["teams"] += 1 

703 row["registrations"] += sum( 

704 1 for p in action["placements"] if (p["league"], p["conference"]) == (league, conference) 

705 ) 

706 

707 counts: dict[str, dict[str, int]] = {kind: {PROPOSED: 0, NEEDS_REVIEW: 0} for kind in ACTION_TYPES} 

708 for action in planner.actions: 

709 counts[action["type"]][action["status"]] += 1 

710 

711 report = { 

712 "entries": len(entries), 

713 "sides": sides, 

714 "matches": match_report, 

715 "conferences": { 

716 "placed": sorted(placed.values(), key=lambda row: (row["league"], row["conference"])), 

717 "unplaced": unplaced, 

718 "unknown": planner.unknown_conferences, 

719 }, 

720 "ambiguous": ambiguous, 

721 "unknown": planner.unknown, 

722 "actions": counts, 

723 } 

724 return {"report": report, "actions": planner.actions} 

725 

726 

727def plan_id_for(actions: list[dict], generated_at: str) -> str: 

728 """A name for a plan: when it was made, and a digest of what it proposes.""" 

729 digest = hashlib.sha256(json.dumps(actions, sort_keys=True).encode()).hexdigest()[:8] 

730 stamp = re.sub(r"[^0-9T]", "", generated_at.split(".")[0].split("+")[0]) 

731 return f"plan-{stamp}-{digest}" 

732 

733 

734# --- Reading a reviewed plan back ------------------------------------------- 

735 

736 

737def _is_text(value: Any) -> bool: 

738 return isinstance(value, str) and bool(normalise(value)) 

739 

740 

741def action_error(action: Any) -> str | None: 

742 """Why an action from a plan file cannot be read, or None if it can. 

743 

744 A plan file is edited by hand between planning and applying, so every 

745 field is checked rather than trusted. 

746 """ 

747 if not isinstance(action, dict): 

748 return "not an object" 

749 kind = action.get("type") 

750 if kind not in ACTION_TYPES: 

751 return f"unknown action type '{kind}'" 

752 if not _is_text(action.get("external_name")): 

753 return "external_name is missing" 

754 league = action.get("league") 

755 if league is not None and not _is_text(league): 

756 return "league must be a league name or null" 

757 fixes = action.get("fixes", []) 

758 if not isinstance(fixes, list) or not all( 

759 isinstance(fix, dict) and _is_text(fix.get("name")) and _is_text(fix.get("age_group")) for fix in fixes 

760 ): 

761 return "fixes must be a list of {name, age_group, league, status}" 

762 if any(name_key(fix["name"]) != name_key(action["external_name"]) for fix in fixes): 

763 return "every entry in fixes must be for external_name" 

764 

765 if kind == ALIAS: 

766 if league is None: 

767 return "an alias needs a league" 

768 team_id = action.get("team_id") 

769 if not isinstance(team_id, int) or isinstance(team_id, bool): 

770 return "team_id is not set" 

771 if not _is_text(action.get("team_name")): 

772 return "team_name is not set: it must name the team team_id refers to" 

773 return None 

774 

775 if not _is_text(action.get("team_name")): 

776 return "team_name is missing" 

777 club_id, new_club_name = action.get("club_id"), action.get("new_club_name") 

778 if club_id is not None and (not isinstance(club_id, int) or isinstance(club_id, bool)): 

779 return "club_id must be a club id or null" 

780 if club_id is None and not _is_text(new_club_name): 

781 return "one of club_id and new_club_name must be set" 

782 if club_id is not None and new_club_name: 

783 return "club_id and new_club_name are both set: keep one" 

784 if club_id is not None and not _is_text(action.get("club_name")): 

785 return "club_name is not set: it must name the club club_id refers to" 

786 placements = action.get("placements", []) 

787 if not isinstance(placements, list) or not all( 

788 isinstance(p, dict) and all(_is_text(p.get(key)) for key in ("age_group", "league", "conference")) 

789 for p in placements 

790 ): 

791 return "placements must be a list of {age_group, league, conference}" 

792 return None 

793 

794 

795def is_approved(action: Any) -> bool: 

796 """Whether a reviewer approved this action. Nothing else is ever applied.""" 

797 return isinstance(action, dict) and action.get("status") == APPROVED 

798 

799 

800def applicable(actions: Iterable[Any]) -> list[dict]: 

801 """The actions of a plan that may be applied: the approved ones.""" 

802 return [action for action in actions if is_approved(action)] 

803 

804 

805def read_plan(plan: Any) -> dict: 

806 """A plan file's content, checked for the two things apply needs. 

807 

808 Raises PlanInputError for something that is not a plan at all. An action 

809 that is individually unreadable is left in: apply refuses it by itself, 

810 with the reason, rather than the whole file. 

811 """ 

812 if not isinstance(plan, dict): 

813 raise PlanInputError("a plan must be a JSON object") 

814 if not _is_text(plan.get("plan_id")): 

815 raise PlanInputError("the plan has no plan_id") 

816 if not isinstance(plan.get("actions"), list): 

817 raise PlanInputError("the plan has no actions list") 

818 return plan