Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution
- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
or "Western" on the participant, mirroring the LLWS pool-assignment pattern
so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
and error paths
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Address code review feedback on MLS standings + simulator
1. Update mls-simulator.ts module comment to document the new step-3
externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
Conference" instead of broad substring, preventing false matches
on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
and parseConferenceFromExternalId (case-insensitivity, null/undefined,
numeric ESPN IDs, unrecognized strings)
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Fix lint: replace != null with !== null && !== undefined
oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
|
|
|
import type { FetchedStandingsRecord, StandingsSyncAdapter } from "./types";
|
Fix MLB standings 406 error and refactor ESPN adapter shared code (#62)
## Summary
- **Root cause**: `statsapi.mlb.com` returns 406 (deprecated). Switched MLB to ESPN's free standings API (`site.api.espn.com/apis/v2/sports/baseball/mlb/standings`), consistent with NBA, WNBA, and MLS.
- **Refactor**: Extracted a shared `espn.ts` utility module, eliminating 4× duplication of `statsMap()`, `flattenEspnStandings()`, ESPN interfaces, and the `playoffSeed` → conference rank logic across adapters.
- **Bug fixes** found during review and applied across all affected adapters:
- `parseConferenceRank`: `|| undefined` falsy-zero bug replaced with `isNaN` guard
- Sort comparators: stable alphabetical tiebreaker added to MLB, NBA, WNBA
- `winPct`: falls back to `wins/(wins+losses)` if ESPN omits the stat (was silently 0)
- statsMap pre-built once per entry before sorting in all adapters (was rebuilt per comparison)
- WNBA `parseEntry`: accepts pre-computed `sm` instead of rebuilding it internally
- MLB `gamesBack`: tests updated to reflect ESPN returns numeric `0` for division leaders (old API used `"-"` → `undefined`)
## Test plan
- [ ] All 60 standings-sync unit tests pass (`npm run test:run -- app/services/standings-sync`)
- [ ] Trigger MLB standings sync from admin panel and confirm it returns data without a 406
- [ ] Confirm NBA, WNBA, MLS syncs still work (adapters touched but behaviour unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/62
2026-06-01 03:31:18 +00:00
|
|
|
import {
|
|
|
|
|
flattenEspnStandings,
|
|
|
|
|
parseConferenceRank,
|
|
|
|
|
statsMap,
|
|
|
|
|
type EspnStandingsResponse,
|
|
|
|
|
} from "./espn";
|
Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution
- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
or "Western" on the participant, mirroring the LLWS pool-assignment pattern
so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
and error paths
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Address code review feedback on MLS standings + simulator
1. Update mls-simulator.ts module comment to document the new step-3
externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
Conference" instead of broad substring, preventing false matches
on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
and parseConferenceFromExternalId (case-insensitivity, null/undefined,
numeric ESPN IDs, unrecognized strings)
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Fix lint: replace != null with !== null && !== undefined
oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
|
|
|
|
|
|
|
|
const MLS_STANDINGS_URL =
|
|
|
|
|
"https://site.api.espn.com/apis/v2/sports/soccer/usa.1/standings";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Normalize ESPN conference group names to "Eastern" or "Western".
|
|
|
|
|
* ESPN returns names like "Eastern Conference" or "Western Conference".
|
|
|
|
|
*/
|
|
|
|
|
function normalizeConference(raw: string): string {
|
|
|
|
|
const upper = raw.toUpperCase();
|
|
|
|
|
if (upper === "EASTERN" || upper === "EASTERN CONFERENCE") return "Eastern";
|
|
|
|
|
if (upper === "WESTERN" || upper === "WESTERN CONFERENCE") return "Western";
|
|
|
|
|
return raw;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export class MlsStandingsAdapter implements StandingsSyncAdapter {
|
|
|
|
|
async fetchStandings(): Promise<FetchedStandingsRecord[]> {
|
|
|
|
|
const response = await fetch(MLS_STANDINGS_URL);
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`MLS standings API returned ${response.status}: ${response.statusText}`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const json = (await response.json()) as EspnStandingsResponse;
|
|
|
|
|
const flattened = flattenEspnStandings(json);
|
|
|
|
|
|
|
|
|
|
if (flattened.length === 0) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
"MLS standings API returned no entries — response shape may have changed"
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
Fix MLB standings 406 error and refactor ESPN adapter shared code (#62)
## Summary
- **Root cause**: `statsapi.mlb.com` returns 406 (deprecated). Switched MLB to ESPN's free standings API (`site.api.espn.com/apis/v2/sports/baseball/mlb/standings`), consistent with NBA, WNBA, and MLS.
- **Refactor**: Extracted a shared `espn.ts` utility module, eliminating 4× duplication of `statsMap()`, `flattenEspnStandings()`, ESPN interfaces, and the `playoffSeed` → conference rank logic across adapters.
- **Bug fixes** found during review and applied across all affected adapters:
- `parseConferenceRank`: `|| undefined` falsy-zero bug replaced with `isNaN` guard
- Sort comparators: stable alphabetical tiebreaker added to MLB, NBA, WNBA
- `winPct`: falls back to `wins/(wins+losses)` if ESPN omits the stat (was silently 0)
- statsMap pre-built once per entry before sorting in all adapters (was rebuilt per comparison)
- WNBA `parseEntry`: accepts pre-computed `sm` instead of rebuilding it internally
- MLB `gamesBack`: tests updated to reflect ESPN returns numeric `0` for division leaders (old API used `"-"` → `undefined`)
## Test plan
- [ ] All 60 standings-sync unit tests pass (`npm run test:run -- app/services/standings-sync`)
- [ ] Trigger MLB standings sync from admin panel and confirm it returns data without a 406
- [ ] Confirm NBA, WNBA, MLS syncs still work (adapters touched but behaviour unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/62
2026-06-01 03:31:18 +00:00
|
|
|
// Pre-parse each entry's stats once, then sort by points desc for overall league rank.
|
|
|
|
|
const withSm = flattened.map(({ entry, conference }) => ({
|
Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution
- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
or "Western" on the participant, mirroring the LLWS pool-assignment pattern
so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
and error paths
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Address code review feedback on MLS standings + simulator
1. Update mls-simulator.ts module comment to document the new step-3
externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
Conference" instead of broad substring, preventing false matches
on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
and parseConferenceFromExternalId (case-insensitivity, null/undefined,
numeric ESPN IDs, unrecognized strings)
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Fix lint: replace != null with !== null && !== undefined
oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
|
|
|
entry,
|
|
|
|
|
conference,
|
|
|
|
|
sm: statsMap(entry.stats),
|
|
|
|
|
}));
|
|
|
|
|
|
Fix MLB standings 406 error and refactor ESPN adapter shared code (#62)
## Summary
- **Root cause**: `statsapi.mlb.com` returns 406 (deprecated). Switched MLB to ESPN's free standings API (`site.api.espn.com/apis/v2/sports/baseball/mlb/standings`), consistent with NBA, WNBA, and MLS.
- **Refactor**: Extracted a shared `espn.ts` utility module, eliminating 4× duplication of `statsMap()`, `flattenEspnStandings()`, ESPN interfaces, and the `playoffSeed` → conference rank logic across adapters.
- **Bug fixes** found during review and applied across all affected adapters:
- `parseConferenceRank`: `|| undefined` falsy-zero bug replaced with `isNaN` guard
- Sort comparators: stable alphabetical tiebreaker added to MLB, NBA, WNBA
- `winPct`: falls back to `wins/(wins+losses)` if ESPN omits the stat (was silently 0)
- statsMap pre-built once per entry before sorting in all adapters (was rebuilt per comparison)
- WNBA `parseEntry`: accepts pre-computed `sm` instead of rebuilding it internally
- MLB `gamesBack`: tests updated to reflect ESPN returns numeric `0` for division leaders (old API used `"-"` → `undefined`)
## Test plan
- [ ] All 60 standings-sync unit tests pass (`npm run test:run -- app/services/standings-sync`)
- [ ] Trigger MLB standings sync from admin panel and confirm it returns data without a 406
- [ ] Confirm NBA, WNBA, MLS syncs still work (adapters touched but behaviour unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/62
2026-06-01 03:31:18 +00:00
|
|
|
const sorted = [...withSm].toSorted((a, b) => {
|
Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution
- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
or "Western" on the participant, mirroring the LLWS pool-assignment pattern
so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
and error paths
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Address code review feedback on MLS standings + simulator
1. Update mls-simulator.ts module comment to document the new step-3
externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
Conference" instead of broad substring, preventing false matches
on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
and parseConferenceFromExternalId (case-insensitivity, null/undefined,
numeric ESPN IDs, unrecognized strings)
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Fix lint: replace != null with !== null && !== undefined
oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
|
|
|
const ptsA = a.sm.get("points")?.value ?? 0;
|
|
|
|
|
const ptsB = b.sm.get("points")?.value ?? 0;
|
|
|
|
|
if (ptsB !== ptsA) return ptsB - ptsA;
|
|
|
|
|
const gdA = a.sm.get("pointDifferential")?.value ?? 0;
|
|
|
|
|
const gdB = b.sm.get("pointDifferential")?.value ?? 0;
|
|
|
|
|
return gdB - gdA;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return sorted.map(({ entry, conference, sm }, leagueIdx): FetchedStandingsRecord => {
|
|
|
|
|
const wins = sm.get("wins")?.value ?? 0;
|
|
|
|
|
const losses = sm.get("losses")?.value ?? 0;
|
|
|
|
|
const ties = sm.get("ties")?.value ?? sm.get("draws")?.value ?? 0;
|
|
|
|
|
const gamesPlayed = Math.round(
|
|
|
|
|
sm.get("gamesPlayed")?.value ?? wins + losses + ties
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const tablePoints = sm.get("points")?.value;
|
|
|
|
|
const goalsFor = sm.get("pointsFor")?.value ?? sm.get("gf")?.value;
|
|
|
|
|
const goalsAgainst = sm.get("pointsAgainst")?.value ?? sm.get("ga")?.value;
|
|
|
|
|
const goalDifference = sm.get("pointDifferential")?.value ?? sm.get("gd")?.value;
|
|
|
|
|
|
|
|
|
|
const homeRecord = sm.get("Home")?.displayValue ?? undefined;
|
|
|
|
|
const awayRecord = sm.get("Road")?.displayValue ?? undefined;
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
teamName: entry.team.displayName,
|
|
|
|
|
externalTeamId: entry.team.id,
|
|
|
|
|
wins: Math.round(wins),
|
|
|
|
|
losses: Math.round(losses),
|
|
|
|
|
ties: Math.round(ties),
|
|
|
|
|
tablePoints: tablePoints !== null && tablePoints !== undefined ? Math.round(tablePoints) : undefined,
|
|
|
|
|
goalsFor: goalsFor !== null && goalsFor !== undefined ? Math.round(goalsFor) : undefined,
|
|
|
|
|
goalsAgainst: goalsAgainst !== null && goalsAgainst !== undefined ? Math.round(goalsAgainst) : undefined,
|
|
|
|
|
goalDifference: goalDifference !== null && goalDifference !== undefined ? Math.round(goalDifference) : undefined,
|
|
|
|
|
winPct: gamesPlayed > 0 ? wins / gamesPlayed : 0,
|
|
|
|
|
gamesPlayed,
|
|
|
|
|
conference: normalizeConference(conference),
|
Fix MLB standings 406 error and refactor ESPN adapter shared code (#62)
## Summary
- **Root cause**: `statsapi.mlb.com` returns 406 (deprecated). Switched MLB to ESPN's free standings API (`site.api.espn.com/apis/v2/sports/baseball/mlb/standings`), consistent with NBA, WNBA, and MLS.
- **Refactor**: Extracted a shared `espn.ts` utility module, eliminating 4× duplication of `statsMap()`, `flattenEspnStandings()`, ESPN interfaces, and the `playoffSeed` → conference rank logic across adapters.
- **Bug fixes** found during review and applied across all affected adapters:
- `parseConferenceRank`: `|| undefined` falsy-zero bug replaced with `isNaN` guard
- Sort comparators: stable alphabetical tiebreaker added to MLB, NBA, WNBA
- `winPct`: falls back to `wins/(wins+losses)` if ESPN omits the stat (was silently 0)
- statsMap pre-built once per entry before sorting in all adapters (was rebuilt per comparison)
- WNBA `parseEntry`: accepts pre-computed `sm` instead of rebuilding it internally
- MLB `gamesBack`: tests updated to reflect ESPN returns numeric `0` for division leaders (old API used `"-"` → `undefined`)
## Test plan
- [ ] All 60 standings-sync unit tests pass (`npm run test:run -- app/services/standings-sync`)
- [ ] Trigger MLB standings sync from admin panel and confirm it returns data without a 406
- [ ] Confirm NBA, WNBA, MLS syncs still work (adapters touched but behaviour unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/62
2026-06-01 03:31:18 +00:00
|
|
|
conferenceRank: parseConferenceRank(sm),
|
Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution
- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
or "Western" on the participant, mirroring the LLWS pool-assignment pattern
so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
and error paths
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Address code review feedback on MLS standings + simulator
1. Update mls-simulator.ts module comment to document the new step-3
externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
Conference" instead of broad substring, preventing false matches
on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
and parseConferenceFromExternalId (case-insensitivity, null/undefined,
numeric ESPN IDs, unrecognized strings)
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
* Fix lint: replace != null with !== null && !== undefined
oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.
https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
|
|
|
leagueRank: leagueIdx + 1,
|
|
|
|
|
homeRecord,
|
|
|
|
|
awayRecord,
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|