2026-03-21 00:12:01 -07:00
|
|
|
import { database } from "~/database/context";
|
2026-06-08 07:42:14 +00:00
|
|
|
import { eq, inArray } from "drizzle-orm";
|
2026-03-21 00:12:01 -07:00
|
|
|
import * as schema from "~/database/schema";
|
Canonical tournament layer: schema + backfill (1/2) (#365)
* refactor(schema): rename per-window tables to season_* prefix
Renames participants, participant_expected_values, participant_qualifying_totals,
participant_results, participant_surface_elos to season_* prefixed names.
Renames event_results.participant_id to season_participant_id.
Phase 1a of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor: rename participant.ts model file to season-participant.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(models): update model layer to use renamed schema exports
Updated all model files to use the renamed schema exports from Task 1:
- participants → seasonParticipants
- participantExpectedValues → seasonParticipantExpectedValues
- participantQualifyingTotals → seasonParticipantQualifyingTotals
- participantResults → seasonParticipantResults
- participantSurfaceElos → seasonParticipantSurfaceElos
- eventResults.participantId → eventResults.seasonParticipantId
- db.query relation accessors updated
- Relation field .participant → .seasonParticipant where applicable
- Import paths updated: ./participant → ./season-participant
Files updated (14 model files + 3 test files):
- draft-pick.ts
- draft-utils.ts
- event-result.ts
- group-stage-match.ts
- participant-result.ts
- qualifying-points.ts
- scoring-calculator.ts
- scoring-event.ts
- sports-season.ts
- surface-elo.ts
- team-score-events.ts
- cs2-major-stage.ts
- golf-skills.ts
- participant-expected-value.ts
- __tests__/sports-season.clone.test.ts
- __tests__/auto-pick.test.ts
- __tests__/executeAutoPick.timer.test.ts
Typecheck errors decreased: 779 → 499 (280 fewer)
All model file errors related to renamed schemas resolved.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(routes): update route layer to use renamed schema exports
- Update model import from ~/models/participant to ~/models/season-participant
- Rename schema.participants to schema.seasonParticipants
- Rename schema.participantResults to schema.seasonParticipantResults
- Rename db.query.participants to db.query.seasonParticipants
- Update 9 route files and 1 test file
Affected files:
- admin.sports-seasons.$id.events.$eventId.bracket.server.ts
- admin.sports-seasons.$id.participants.tsx
- api/draft.force-manual-pick.ts
- api/draft.make-pick.ts
- api/draft.replace-pick.ts
- api/seasons.$seasonId.draft.ts
- leagues/$leagueId.draft-board.$seasonId.tsx
- leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts
- admin/__tests__/sports-seasons-participants.test.ts
Error count reduced from 499 to 453 (46 errors fixed).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(routes): update route files for schema rename
Update route imports from ~/models/participant to ~/models/season-participant
and fix references to .participant/.participantId on event results to use
.seasonParticipant/.seasonParticipantId after schema rename.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(services): update simulators and services for renamed schema
Update all simulators, services, and server files to use renamed schema tables:
- participants → seasonParticipants
- participantExpectedValues → seasonParticipantExpectedValues
- participantResults → seasonParticipantResults
- eventResults.participantId → eventResults.seasonParticipantId
Files updated:
- 20 sport simulators (NBA, NHL, NFL, MLB, etc.)
- probability-updater.ts
- standings-sync/index.ts
- sports-data-sync.server.ts
- server/socket.ts
Typecheck errors reduced from 365 to 0.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* migration: rename per-window tables to season_* prefix
* fix(tests): update mock query keys after participants table rename
Change mock db.query.participants to db.query.seasonParticipants in test
files to match the schema rename from commit 66145a9. This fixes
"Cannot read properties of undefined (reading 'findFirst'/'findMany')"
errors that occurred when production code queries db.query.seasonParticipants
but test mocks only defined the old participants key.
Files updated:
- app/services/simulations/__tests__/world-cup-simulator.test.ts
- app/routes/api/__tests__/draft.force-manual-pick.test.ts
- app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts
- app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts
- server/__tests__/timer-autodraft.test.ts
- app/models/__tests__/team-score-events.test.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(tests): update remaining mock paths and keys after schema rename
* fix(tests): final two mock stragglers after schema rename
- draft-pick.test.ts: assertion on db.query.participantQualifyingTotals
- process-match-result.test.ts: mock key participants → seasonParticipants
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* chore: add post-phase1a baseline capture (temp, for diff verification)
* chore: capture pre-migration baselines
* chore: remove post-phase1a capture helper after verification
* schema: add canonical tournament & participant tables
Adds tournaments, participants (canonical), tournament_results, and
participant_surface_elos (canonical). Adds nullable tournament_id to
scoring_events and nullable participant_id to season_participants.
Phase 1b of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(models): add canonical tournament, participant, result, surface-elo models
Adds CRUD modules for the canonical tables created in commit 775b905.
Each module mirrors existing app/models conventions (database() from
~/database/context, schema from ~/database/schema, mock-based tests).
Key implementation notes:
- participant.ts exports use "Canonical" prefix (CanonicalParticipant,
createCanonicalParticipant, etc.) to avoid collision with existing
season-participant.ts exports
- All four models include comprehensive unit tests following the
audit-log.test.ts pattern
- Tests use mocked db responses (no real database access)
- Upsert functions use onConflictDoUpdate for appropriate unique constraints
Part of Phase 1b of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* migration: create canonical tables, add nullable FKs
* scripts: add extractTournamentIdentity helper for backfill
Pure function that derives canonical (name, year) identity from a
scoring_events row, stripping trailing 4-digit years from the name or
falling back to eventDate. Used by the Phase 2 backfill to group
per-window events into canonical tournaments.
* scripts: add backfill orchestrator for canonical layer
Populates canonical tournaments, participants, tournament_results, and
participant_surface_elos from per-window data for qualifying-points
sports. Skips already-linked rows, is idempotent, and supports dry-run
mode.
Critical invariants enforced by the implementation:
- qualifying_points_awarded is never copied to tournament_results
- season_participant_qualifying_totals is never touched
- conflicting surface-Elo values between windows raise a loud error
(recorded in report.errors) rather than overwriting
* scripts: add backfill CLI with dry-run default
Wires backfill-canonical-layer.ts to a CLI entry point exposed as
`npm run backfill:canonical`. Defaults to --dry-run; requires --apply
to actually write. Supports --sport=<uuid> to limit to a single sport.
Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts).
* fix(backfill-cli): wrap runBackfill in DatabaseContext.run
The orchestrator uses database() from ~/database/context, which requires
AsyncLocalStorage to be populated. Wrap the CLI invocation with
DatabaseContext.run(db, ...) using server/db's cached connection pool.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(backfill-cli): exit 0 on success so pg pool doesn't block
The cached postgres connection pool keeps the Node event loop open after
main() returns. Explicit process.exit(0) on success mirrors the pattern
in scripts/capture-baseline.ts.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Chris Parsons <chrisp@extrahop.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
|
|
|
import { findParticipantsBySportsSeasonId, updateParticipant } from "~/models/season-participant";
|
2026-03-21 00:12:01 -07:00
|
|
|
import { upsertRegularSeasonStandings } from "~/models/regular-season-standings";
|
|
|
|
|
import { upsertPendingStandingsMappings } from "~/models/pending-standings-mappings";
|
2026-06-10 04:25:48 +00:00
|
|
|
import { upsertSeasonResultsBulk } from "~/models/participant-season-result";
|
2026-03-21 00:12:01 -07:00
|
|
|
import { findMatchingTeamName } from "~/lib/normalize-team-name";
|
|
|
|
|
import { NhlStandingsAdapter } from "./nhl";
|
|
|
|
|
import { NbaStandingsAdapter } from "./nba";
|
2026-03-22 01:57:39 -07:00
|
|
|
import { AflStandingsAdapter } from "./afl";
|
Add MLB playoff simulator with AL/NL division standings, fixes #121 (#225)
* Add MLB playoff simulator with AL/NL division standings, fixes #121
- New `mlb-simulator.ts`: 50k Monte Carlo sim drawing division winners
(weighted by p_div) and 3 WC teams per league, then simulating
WC best-of-3 → DS best-of-5 → LCS best-of-7 → World Series.
Elo parity factor 350; blends Vegas odds 30/70 when sourceOdds available.
- New `standings-sync/mlb.ts`: adapter for free statsapi.mlb.com API,
mapping AL/NL conferences, division ranks, streaks, home/away/L10 splits.
- New `mlb-divisions` display mode in RegularSeasonStandings: shows 1 division
winner per division section + Wild Card section with 3-spot playoff line,
headings read "AL/NL League" instead of "Conference".
- Refactored buildNhlSections/buildMlbSections into shared buildDivisionSections
(divisionSpots + wcSpots params); conferenceLabel now flows through group
objects rather than being derived from displayMode in the render.
- DB migration 0062 adds `mlb_bracket` to simulator_type enum.
- 37 new tests across simulator, adapter, and component.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix flaky tennis simulator test: increase trials and lower threshold
500 trials with a ~3–5% expected win rate had enough variance to
occasionally land below the 0.03 threshold (~2% failure rate).
Bumping to 2000 trials reduces the std dev by 2x; lowering the
threshold to 0.02 keeps the assertion meaningful (still well above
random 0.78%) while eliminating the flakiness.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 08:47:02 -07:00
|
|
|
import { MlbStandingsAdapter } from "./mlb";
|
2026-03-26 00:34:51 -07:00
|
|
|
import { WnbaStandingsAdapter } from "./wnba";
|
2026-05-07 11:48:57 -07:00
|
|
|
import { EplStandingsAdapter } from "./epl";
|
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 { MlsStandingsAdapter } from "./mls";
|
2026-07-06 21:20:47 -07:00
|
|
|
import { F1StandingsAdapter, OcBlacktopIndyCarStandingsAdapter } from "./f1";
|
2026-03-21 00:12:01 -07:00
|
|
|
import type { StandingsSyncAdapter, SyncResult, UnmatchedTeam } from "./types";
|
|
|
|
|
|
|
|
|
|
function getAdapter(simulatorType: string): StandingsSyncAdapter {
|
|
|
|
|
switch (simulatorType) {
|
|
|
|
|
case "nba_bracket":
|
|
|
|
|
return new NbaStandingsAdapter();
|
|
|
|
|
case "nhl_bracket":
|
|
|
|
|
return new NhlStandingsAdapter();
|
2026-03-22 01:57:39 -07:00
|
|
|
case "afl_bracket":
|
|
|
|
|
return new AflStandingsAdapter();
|
2026-05-07 11:48:57 -07:00
|
|
|
case "epl_standings":
|
|
|
|
|
return new EplStandingsAdapter();
|
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
|
|
|
case "mls_bracket":
|
|
|
|
|
return new MlsStandingsAdapter();
|
Add MLB playoff simulator with AL/NL division standings, fixes #121 (#225)
* Add MLB playoff simulator with AL/NL division standings, fixes #121
- New `mlb-simulator.ts`: 50k Monte Carlo sim drawing division winners
(weighted by p_div) and 3 WC teams per league, then simulating
WC best-of-3 → DS best-of-5 → LCS best-of-7 → World Series.
Elo parity factor 350; blends Vegas odds 30/70 when sourceOdds available.
- New `standings-sync/mlb.ts`: adapter for free statsapi.mlb.com API,
mapping AL/NL conferences, division ranks, streaks, home/away/L10 splits.
- New `mlb-divisions` display mode in RegularSeasonStandings: shows 1 division
winner per division section + Wild Card section with 3-spot playoff line,
headings read "AL/NL League" instead of "Conference".
- Refactored buildNhlSections/buildMlbSections into shared buildDivisionSections
(divisionSpots + wcSpots params); conferenceLabel now flows through group
objects rather than being derived from displayMode in the render.
- DB migration 0062 adds `mlb_bracket` to simulator_type enum.
- 37 new tests across simulator, adapter, and component.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix flaky tennis simulator test: increase trials and lower threshold
500 trials with a ~3–5% expected win rate had enough variance to
occasionally land below the 0.03 threshold (~2% failure rate).
Bumping to 2000 trials reduces the std dev by 2x; lowering the
threshold to 0.02 keeps the assertion meaningful (still well above
random 0.78%) while eliminating the flakiness.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 08:47:02 -07:00
|
|
|
case "mlb_bracket":
|
|
|
|
|
return new MlbStandingsAdapter();
|
2026-03-26 00:34:51 -07:00
|
|
|
case "wnba_bracket":
|
|
|
|
|
return new WnbaStandingsAdapter();
|
2026-03-21 00:12:01 -07:00
|
|
|
case "f1_standings":
|
2026-06-10 04:25:48 +00:00
|
|
|
return new F1StandingsAdapter();
|
2026-03-21 00:12:01 -07:00
|
|
|
case "indycar_standings":
|
2026-07-06 21:20:47 -07:00
|
|
|
return new OcBlacktopIndyCarStandingsAdapter();
|
2026-03-21 00:12:01 -07:00
|
|
|
default:
|
|
|
|
|
throw new Error(
|
|
|
|
|
`No standings sync adapter available for simulator type "${simulatorType}". ` +
|
2026-06-10 04:25:48 +00:00
|
|
|
"NBA, NHL, AFL, MLB, WNBA, EPL, MLS, F1, and IndyCar are currently supported."
|
2026-03-21 00:12:01 -07:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sync current standings from the appropriate external API for a sports season.
|
|
|
|
|
* Matches API team names to participants by name and bulk-upserts the results.
|
|
|
|
|
*
|
2026-06-10 04:25:48 +00:00
|
|
|
* For season_standings sports (F1, IndyCar), upserts into participantSeasonResults.
|
|
|
|
|
* For all other sports, upserts into regularSeasonStandings.
|
|
|
|
|
*
|
|
|
|
|
* Returns the count of synced entries and any API names that couldn't be matched.
|
2026-03-21 00:12:01 -07:00
|
|
|
*/
|
|
|
|
|
export async function syncStandings(sportsSeasonId: string): Promise<SyncResult> {
|
|
|
|
|
const db = database();
|
|
|
|
|
|
|
|
|
|
// Load sports season with sport relation
|
|
|
|
|
const sportsSeason = await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasons.id, sportsSeasonId),
|
|
|
|
|
with: { sport: true },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!sportsSeason) {
|
|
|
|
|
throw new Error(`Sports season ${sportsSeasonId} not found`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const simulatorType = sportsSeason.sport?.simulatorType;
|
|
|
|
|
if (!simulatorType) {
|
|
|
|
|
const sportName = sportsSeason.sport?.name ?? "(no sport linked)";
|
|
|
|
|
throw new Error(`Sport "${sportName}" has no simulator type configured`);
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
const isSeasonStandings = sportsSeason.scoringPattern === "season_standings";
|
|
|
|
|
|
2026-03-21 00:12:01 -07:00
|
|
|
const adapter = getAdapter(simulatorType);
|
|
|
|
|
const fetchedRecords = await adapter.fetchStandings();
|
|
|
|
|
|
|
|
|
|
// Load all participants for this season
|
|
|
|
|
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
|
|
|
|
const participantNames = participants.map((p) => p.name);
|
|
|
|
|
const participantByName = new Map(participants.map((p) => [p.name, p]));
|
|
|
|
|
const participantByExternalId = new Map(
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
participants.filter((p) => p.externalId).map((p) => [p.externalId ?? "", p])
|
2026-03-21 00:12:01 -07:00
|
|
|
);
|
|
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
type RegularUpsertRow = Parameters<typeof upsertRegularSeasonStandings>[0][number];
|
|
|
|
|
type SeasonResultRow = Parameters<typeof upsertSeasonResultsBulk>[0][number];
|
|
|
|
|
|
|
|
|
|
const toUpsertRegular: RegularUpsertRow[] = [];
|
|
|
|
|
const toUpsertSeason: SeasonResultRow[] = [];
|
2026-06-08 07:42:14 +00:00
|
|
|
const matchedParticipantIds: string[] = [];
|
2026-06-10 04:25:48 +00:00
|
|
|
const unmatchedRecords: typeof fetchedRecords = [];
|
2026-03-21 00:12:01 -07:00
|
|
|
|
|
|
|
|
for (const record of fetchedRecords) {
|
|
|
|
|
let participant = participantByExternalId.get(record.externalTeamId) ?? null;
|
|
|
|
|
|
|
|
|
|
if (!participant) {
|
|
|
|
|
const matchedName = findMatchingTeamName(record.teamName, participantNames);
|
|
|
|
|
if (matchedName) {
|
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations
Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.
no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).
consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix no-non-null-assertion lint violations and promote to error
Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.
Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers
Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.
- prefer-add-event-listener: converted onchange/onclick/onload
assignments to addEventListener in useDraftNotifications.ts and
admin.data-sync.tsx; stored changeHandler ref for proper cleanup
with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
side-effect imports (*.css, @testing-library/jest-dom,
@testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
cypress/support/e2e.ts (file already has an import)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors from no-non-null-assertion fixes
Two fixes introduced by the non-null assertion cleanup produced type
errors:
- scoring-event.ts: `?? ""` was wrong type for a participant object map;
restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
truthy guarantee, causing TS18047 on the write-back block; added
`participant &&` guard before accessing its properties
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add npm run typecheck as Stop hook in Claude settings
Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
|
|
|
participant = participantByName.get(matchedName) ?? null;
|
|
|
|
|
if (participant && !participant.externalId) {
|
2026-03-21 00:12:01 -07:00
|
|
|
await updateParticipant(participant.id, { externalId: record.externalTeamId });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!participant) {
|
|
|
|
|
unmatchedRecords.push(record);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-08 07:42:14 +00:00
|
|
|
matchedParticipantIds.push(participant.id);
|
2026-06-10 04:25:48 +00:00
|
|
|
|
|
|
|
|
if (isSeasonStandings) {
|
|
|
|
|
toUpsertSeason.push({
|
|
|
|
|
participantId: participant.id,
|
|
|
|
|
sportsSeasonId,
|
|
|
|
|
currentPoints: record.currentPoints ?? 0,
|
|
|
|
|
currentPosition: record.leagueRank,
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
toUpsertRegular.push({
|
|
|
|
|
participantId: participant.id,
|
|
|
|
|
sportsSeasonId,
|
|
|
|
|
wins: record.wins,
|
|
|
|
|
losses: record.losses,
|
|
|
|
|
otLosses: record.otLosses ?? null,
|
|
|
|
|
ties: record.ties ?? null,
|
|
|
|
|
tablePoints: record.tablePoints ?? null,
|
|
|
|
|
goalsFor: record.goalsFor ?? null,
|
|
|
|
|
goalsAgainst: record.goalsAgainst ?? null,
|
|
|
|
|
goalDifference: record.goalDifference ?? null,
|
|
|
|
|
winPct: record.winPct,
|
|
|
|
|
gamesPlayed: record.gamesPlayed,
|
|
|
|
|
gamesBack: record.gamesBack ?? null,
|
|
|
|
|
conference: record.conference ?? null,
|
|
|
|
|
division: record.division ?? null,
|
|
|
|
|
conferenceRank: record.conferenceRank ?? null,
|
|
|
|
|
divisionRank: record.divisionRank ?? null,
|
|
|
|
|
leagueRank: record.leagueRank,
|
|
|
|
|
streak: record.streak ?? null,
|
|
|
|
|
lastTen: record.lastTen ?? null,
|
|
|
|
|
homeRecord: record.homeRecord ?? null,
|
|
|
|
|
awayRecord: record.awayRecord ?? null,
|
|
|
|
|
externalTeamId: record.externalTeamId,
|
|
|
|
|
srs: record.srs ?? null,
|
|
|
|
|
syncedAt: new Date(),
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-03-21 00:12:01 -07:00
|
|
|
}
|
|
|
|
|
|
2026-06-08 07:42:14 +00:00
|
|
|
let changed = false;
|
2026-06-10 04:25:48 +00:00
|
|
|
|
|
|
|
|
if (isSeasonStandings && toUpsertSeason.length > 0) {
|
|
|
|
|
const currentRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
participantId: schema.participantSeasonResults.participantId,
|
|
|
|
|
currentPoints: schema.participantSeasonResults.currentPoints,
|
|
|
|
|
currentPosition: schema.participantSeasonResults.currentPosition,
|
|
|
|
|
})
|
|
|
|
|
.from(schema.participantSeasonResults)
|
|
|
|
|
.where(inArray(schema.participantSeasonResults.participantId, matchedParticipantIds));
|
|
|
|
|
|
|
|
|
|
const currentByParticipant = new Map(currentRows.map((r) => [r.participantId, r]));
|
|
|
|
|
|
|
|
|
|
changed = toUpsertSeason.some((row) => {
|
|
|
|
|
const current = currentByParticipant.get(row.participantId);
|
|
|
|
|
if (!current) return true;
|
|
|
|
|
return (
|
|
|
|
|
current.currentPosition !== row.currentPosition ||
|
|
|
|
|
parseFloat(current.currentPoints ?? "0") !== (row.currentPoints ?? 0)
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await upsertSeasonResultsBulk(toUpsertSeason);
|
|
|
|
|
|
|
|
|
|
if (changed) {
|
|
|
|
|
await db
|
|
|
|
|
.update(schema.sportsSeasons)
|
|
|
|
|
.set({ standingsLastChangedAt: new Date() })
|
|
|
|
|
.where(eq(schema.sportsSeasons.id, sportsSeasonId));
|
|
|
|
|
}
|
|
|
|
|
} else if (!isSeasonStandings && toUpsertRegular.length > 0) {
|
2026-06-08 07:42:14 +00:00
|
|
|
const currentRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
participantId: schema.regularSeasonStandings.participantId,
|
|
|
|
|
gamesPlayed: schema.regularSeasonStandings.gamesPlayed,
|
|
|
|
|
leagueRank: schema.regularSeasonStandings.leagueRank,
|
|
|
|
|
})
|
|
|
|
|
.from(schema.regularSeasonStandings)
|
|
|
|
|
.where(inArray(schema.regularSeasonStandings.participantId, matchedParticipantIds));
|
|
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
const currentByParticipant = new Map(currentRows.map((r) => [r.participantId, r]));
|
2026-06-08 07:42:14 +00:00
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
changed = toUpsertRegular.some((row) => {
|
2026-06-08 07:42:14 +00:00
|
|
|
const current = currentByParticipant.get(row.participantId);
|
2026-06-10 04:25:48 +00:00
|
|
|
if (!current) return true;
|
2026-06-08 07:42:14 +00:00
|
|
|
return current.gamesPlayed !== row.gamesPlayed || current.leagueRank !== row.leagueRank;
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
await upsertRegularSeasonStandings(toUpsertRegular);
|
2026-06-08 07:42:14 +00:00
|
|
|
|
|
|
|
|
if (changed) {
|
|
|
|
|
await db
|
|
|
|
|
.update(schema.sportsSeasons)
|
|
|
|
|
.set({ standingsLastChangedAt: new Date() })
|
|
|
|
|
.where(eq(schema.sportsSeasons.id, sportsSeasonId));
|
|
|
|
|
}
|
2026-03-21 00:12:01 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (unmatchedRecords.length > 0) {
|
|
|
|
|
await upsertPendingStandingsMappings(sportsSeasonId, unmatchedRecords);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const unmatched: UnmatchedTeam[] = unmatchedRecords.map((r) => ({
|
|
|
|
|
teamName: r.teamName,
|
|
|
|
|
externalTeamId: r.externalTeamId,
|
|
|
|
|
}));
|
|
|
|
|
|
2026-06-10 04:25:48 +00:00
|
|
|
const synced = isSeasonStandings ? toUpsertSeason.length : toUpsertRegular.length;
|
|
|
|
|
return { synced, unmatched, changed };
|
2026-03-21 00:12:01 -07:00
|
|
|
}
|