brackt/app/services/sync-tournament-results.ts

364 lines
14 KiB
TypeScript
Raw Normal View History

Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
import { eq, and, inArray } from "drizzle-orm";
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
import { database } from "~/database/context";
import * as schema from "~/database/schema";
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
import {
processQualifyingEvent,
recalculateAffectedLeagues,
buildTieCountByPlacement,
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
} from "~/models/scoring-calculator";
import { completeScoringEvent, getScoringEventById } from "~/models/scoring-event";
import { getEventResults } from "~/models/event-result";
import { upsertTournamentResult } from "~/models/tournament-result";
import { logger } from "~/lib/logger";
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
export interface SyncReport {
tournamentId: string;
windowsSynced: number;
windowsFailed: number;
failures: Array<{
scoringEventId: string;
sportsSeasonId: string;
error: string;
}>;
}
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
export interface SyncOptions {
/**
* Mark each synced window's scoring_event as complete (is_complete +
* completed_at). Use for final results (golf batch entry, finalize-bracket).
* Leave false for mid-tournament fan-out (e.g. live bracket rounds) so a major
* isn't marked complete before it actually finishes.
* @default true
*/
markComplete?: boolean;
/**
* Skip the primary window when fanning out from a bracket/stage major the
* primary is already scored in place, so re-running it would be wasted work.
*/
skipEventId?: string;
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
/**
* Suppress ALL Discord notifications for this fan-out (both the per-window QP
* update from processQualifyingEvent and the league standings recalc). Used by
* one-off backfills that re-score historical events the QP values change
* (e.g. a mis-split 2 correct 1.5), which would otherwise re-ping every league.
*/
skipNotifications?: boolean;
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
}
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
/**
* Fan out canonical tournament_results to every scoring_event window that
* points at this tournament. For each linked window:
* 1. Upsert event_results rows mirroring canonical placement / rawScore for
* every roster participant that appears in the canonical results.
* 2. Write 0-QP filler rows for roster participants who have no result.
* 3. Delegate to processQualifyingEvent to compute QP.
*
* Each window runs in its own transaction so partial failures isolate.
* Errors in one window never interrupt sync of the remaining windows.
*
* This service NEVER writes qualifying_points_awarded directly (except the
* "0" filler for participants with no placement) QP calculation for real
* results is owned by processQualifyingEvent.
*/
export async function syncTournamentResults(
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
tournamentId: string,
options: SyncOptions = {}
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
): Promise<SyncReport> {
const db = database();
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
const { markComplete = true, skipEventId, skipNotifications = false } = options;
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
const report: SyncReport = {
tournamentId,
windowsSynced: 0,
windowsFailed: 0,
failures: [],
};
// 1. Load canonical results for this tournament.
const canonicalResults = await db
.select()
.from(schema.tournamentResults)
.where(eq(schema.tournamentResults.tournamentId, tournamentId));
// The full-field tie span (placement → count) is a property of the whole
// tournament, so compute it once here and hand it to every window's
// processQualifyingEvent instead of re-querying canonical results per window.
const canonicalTieCountByPlacement = buildTieCountByPlacement(canonicalResults);
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
// 2. Load every scoring_event that points at this tournament.
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
const allLinkedEvents = await db
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
.select()
.from(schema.scoringEvents)
.where(eq(schema.scoringEvents.tournamentId, tournamentId));
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
// The primary window (when fanning out from a bracket/stage major) is already
// scored in place — skip it so we don't redo its work.
const linkedEvents = skipEventId
? allLinkedEvents.filter((ev) => ev.id !== skipEventId)
: allLinkedEvents;
// Windows that synced cleanly — used to propagate to leagues after the loop
// (kept out of the per-window transaction so a recalc failure can't roll back
// the result write).
const syncedWindows: Array<{
sportsSeasonId: string;
eventId: string;
eventName: string | null;
}> = [];
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
// 3. Fan out — each event gets its own transaction.
for (const ev of linkedEvents) {
try {
await db.transaction(async (tx: typeof db) => {
// 3a. Window roster = season_participants for this event's sports_season.
const rosters = await tx
.select()
.from(schema.seasonParticipants)
.where(eq(schema.seasonParticipants.sportsSeasonId, ev.sportsSeasonId));
// 3b. For each canonical result whose participant is on the roster,
// upsert the matching event_results row. Only placement / rawScore
// are copied; qualifying_points_awarded is left for
// processQualifyingEvent to recompute.
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
const canonicalSpIds = new Set<string>();
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
for (const cr of canonicalResults) {
const sp = rosters.find((r) => r.participantId === cr.participantId);
if (!sp) continue;
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
canonicalSpIds.add(sp.id);
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
const [existing] = await tx
.select()
.from(schema.eventResults)
.where(
and(
eq(schema.eventResults.scoringEventId, ev.id),
eq(schema.eventResults.seasonParticipantId, sp.id)
)
);
if (existing) {
await tx
.update(schema.eventResults)
.set({
placement: cr.placement,
rawScore: cr.rawScore,
updatedAt: new Date(),
})
.where(eq(schema.eventResults.id, existing.id));
} else {
await tx.insert(schema.eventResults).values({
scoringEventId: ev.id,
seasonParticipantId: sp.id,
placement: cr.placement,
rawScore: cr.rawScore,
});
}
}
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
// 3c. Reconcile every roster member NOT in the canonical results to a
// 0-QP filler row (placement=null, QP=0). This both creates missing rows
// AND resets rows for participants whose canonical placement was removed
// (a correction) — without this, a stale placement/rawScore would persist
// and keep fanning out. notParticipating markers are left untouched.
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
const afterRows = await tx
.select()
.from(schema.eventResults)
.where(eq(schema.eventResults.scoringEventId, ev.id));
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
const existingBySp = new Map(afterRows.map((r) => [r.seasonParticipantId, r]));
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
for (const sp of rosters) {
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
if (canonicalSpIds.has(sp.id)) continue;
const existing = existingBySp.get(sp.id);
if (!existing) {
await tx.insert(schema.eventResults).values({
scoringEventId: ev.id,
seasonParticipantId: sp.id,
placement: null,
qualifyingPointsAwarded: "0",
});
} else if (!existing.notParticipating && existing.placement !== null) {
// Stale placement from a prior sync — reset to filler.
await tx
.update(schema.eventResults)
.set({
placement: null,
rawScore: null,
qualifyingPointsAwarded: "0",
updatedAt: new Date(),
})
.where(eq(schema.eventResults.id, existing.id));
}
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
}
// 3d. Delegate to scoring engine inside the same transaction.
await processQualifyingEvent(ev.id, tx, {
skipNotifications,
canonicalTieCountByPlacement,
});
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
// 3e. Mark the window event complete (final-results sync only). This is
// what makes "score once" actually complete every window — without it,
// each sibling stayed "In Progress" and had to be completed by hand.
// Skip windows already complete so a re-run (e.g. a backfill) doesn't
// needlessly re-stamp completedAt.
if (markComplete && !ev.isComplete) {
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
await completeScoringEvent(ev.id, tx);
}
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
});
report.windowsSynced += 1;
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
syncedWindows.push({
sportsSeasonId: ev.sportsSeasonId,
eventId: ev.id,
eventName: ev.name,
});
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
} catch (e: unknown) {
report.windowsFailed += 1;
const msg =
e instanceof Error ? e.message : typeof e === "string" ? e : String(e);
report.failures.push({
scoringEventId: ev.id,
sportsSeasonId: ev.sportsSeasonId,
error: msg,
});
}
}
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
// 4. Propagate to leagues for every cleanly-synced window. Done outside the
// per-window transactions: recalculateAffectedLeagues touches many fantasy
// seasons and must not roll back a committed result write if it fails.
for (const w of syncedWindows) {
try {
await recalculateAffectedLeagues(w.sportsSeasonId, undefined, {
eventId: w.eventId,
eventName: w.eventName ?? undefined,
// Mid-tournament fan-out (markComplete=false) updates standings silently;
// the primary window already announced the round. Only the final sync
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
// (completion) announces to each window's leagues. A backfill
// (skipNotifications) is always silent.
skipDiscord: skipNotifications || !markComplete,
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
});
} catch (e: unknown) {
const msg =
e instanceof Error ? e.message : typeof e === "string" ? e : String(e);
// Count this as a failed window so the caller's status derivation
// (windowsFailed === 0 ? "completed") doesn't mask stale standings behind
// a green badge — the result write committed, but the league is not current.
report.windowsFailed += 1;
report.failures.push({
scoringEventId: w.eventId,
sportsSeasonId: w.sportsSeasonId,
error: `League recalc failed: ${msg}`,
});
}
}
Canonical tournament layer: cutover + cleanup (2/2) (#367) * 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> * schema: add check constraint requiring tournament_id for qualifying events Team sports (NHL, NBA, etc.) have scoring_events with no canonical tournament, so we can't require tournament_id globally. The constraint only applies when is_qualifying_event=true. Phase 3 Task 1 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(BatchResultEntry): make form intent configurable Canonical tournament admin page will submit with a different intent (batch-upsert-results). Existing per-window callers continue to get "batch-add-results" as the default, so no behavior changes. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(services): syncTournamentResults fan-out service * schema: add unique (scoring_event_id, season_participant_id) on event_results syncTournamentResults uses check-then-write on event_results. The unique index defends against race conditions (unlikely today — admin is single-writer — but safe to enforce). WARNING: if existing prod data has duplicate (scoring_event_id, season_participant_id) pairs, the migration will fail. Verify with: SELECT scoring_event_id, season_participant_id, count(*) FROM event_results GROUP BY 1, 2 HAVING count(*) > 1; Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): getSurfaceEloMap reads from canonical Switch the tennis simulator's Elo source from the per-window table to the canonical participant_surface_elos via season_participants.participant_id. Map key stays season_participant.id so the simulator's call pattern is unchanged. Other functions in this file still read/write the per-window table (seasonParticipantSurfaceElos). They back the old admin surface-elo page and are removed in Phase 4 after the canonical admin flow replaces them. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(admin): canonical tournament list + result entry routes New routes /admin/tournaments and /admin/tournaments/:id. The detail page lets admins enter tournament results once via paste-and-parse, then calls syncTournamentResults to fan out to every linked window. Phase 3 Task 4 of canonical tournament layer migration. * feat: per-window batch-add-results routes through canonical when linked If the scoring_event has a tournament_id, translate season_participant ids to canonical participant ids, upsert tournament_results, and fan out via syncTournamentResults. Team sports (no tournament link) keep the legacy direct-write path. Phase 3 Task 8 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(surface-elo): mirror batchUpsert writes to canonical table The simulator now reads surface Elo from the canonical table (participant_surface_elos). The existing per-window admin page still posts to batchUpsertSurfaceElos; without this change, those edits would silently fail to affect simulator output. Mirror every write to both tables until Phase 4 removes the per-window path entirely. Phase 3 Task 5 (partial — canonical write path; dedicated canonical admin UI deferred; existing page continues to work and now edits both tables). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: auto-provision canonical tournaments and participants on create Creating new qualifying scoring_events or season_participants now auto-upserts the matching canonical rows. Needed so the check constraint doesn't reject qualifying events, and so new season participants flow through syncTournamentResults. - Extract tournament identity shared between backfill and event-creation into app/lib/tournament-identity.ts; scripts/backfill re-exports it. - createScoringEvent + bulkCreateScoringEvents now accept tournamentId. - Event creation routes auto-compute (name, year) and upsert tournament. - createParticipant + createManyParticipants auto-link to canonical participants by (sportId, name). Phase 3 Task 7 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update surface-elo tests for canonical mirror getSurfaceEloMap now joins through season_participants and returns rows keyed by seasonParticipantId (was participantId). batchUpsertSurfaceElos now performs a second db.select to resolve canonical links before mirroring writes; tests mock the lookup explicitly and exercise both the "no canonical link" short-circuit path and the "mirror to canonical" path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: add check constraint + unique index for canonical * refactor(surface-elo): canonical-only; drop per-window path batchUpsertSurfaceElos now writes only to the canonical participant_surface_elos table (the mirror step is now the only step). getSurfaceElosForSeason joins through season_participants → canonical participants so the admin UI keeps its existing (id, participantId, sportsSeasonId, ...) row shape. season_participants without a canonical link get silently skipped. In practice every qualifying-points roster entry is canonical-linked after Phase 2 backfill + Phase 3 auto-linking on createParticipant. Phase 4 Tasks 2 + 3 of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: remove legacy direct-write fallback in batch-add-results Every qualifying scoring_event now has tournament_id (check constraint enforces it), so the non-canonical fallback is dead. Replace with an explicit error surface so any configuration regression becomes visible instead of silently bypassing canonical. Phase 4 Task 4. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * schema: drop season_participant_surface_elos table Table had no remaining readers after Phase 3 and no remaining writers after Phase 4 Task 2. Also removes the now-unrunnable Phase 2 backfill scripts and the backfill:canonical npm script — the backfill ran once and is preserved in git history (commits 85bca8b, 8186dbb, 6f3438b, bc0f530, 327c7b9). Phase 4 Task 5. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(agents): describe canonical/per-window split Update database.md with the canonical/per-window model explanation, the syncTournamentResults fan-out contract, the check constraint, and the tennis-Men/Women quirk. Update domain-models.md to reflect the renamed per-window entities and the new canonical layer. Also update the drizzle-kit gotchas section with lessons from the migration: do not use --custom for renames; FK constraint naming can mismatch Drizzle convention. Phase 4 Task 6. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: drop season_participant_surface_elos * feat(admin): add Tournaments link to admin sidebar Missed in Phase 3 Task 4 — the /admin/tournaments route exists but was not reachable from the admin nav without typing the URL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(lint): address 4 oxlint errors on canonical-layer-pr2 - Remove unused filterNewResults import (events batch-add-results legacy path was removed in Phase 4 Task 4). - Replace import() type annotation in sync-tournament-results test with a top-level type import (consistent-type-imports rule). - Hoist tableName helper out of makeFakeDb closure so it's not recreated per call (consistent-function-scoping rule). - eqeqeq: replace `!= null` with explicit null/undefined checks in tournament-identity. 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 21:04:48 -07:00
return report;
}
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
/**
* Fan out a bracket/stage major (tennis, CS2) from its primary window.
*
* The admin builds and scores the bracket/Swiss stages on ONE window (the
* primary). Those derive per-participant placements into the primary's
* event_results. This reads them back, translates each window-scoped
* season_participant to its canonical participant, and persists them as the
* tournament's canonical tournament_results the exact same shape golf produces
* by hand. It then runs the normal fan-out to every sibling window (skipping the
* primary, which is already scored).
*
* markComplete: pass false while a tournament is still in progress (live rounds)
* so siblings stay in sync without being marked finished; pass true on finalize.
*/
export async function syncMajorFromPrimaryEvent(
primaryEventId: string,
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
options: { markComplete?: boolean; skipNotifications?: boolean } = {}
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
): Promise<SyncReport> {
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
const { markComplete = false, skipNotifications = false } = options;
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
const primaryEvent = await getScoringEventById(primaryEventId);
if (!primaryEvent) {
throw new Error(`Primary event ${primaryEventId} not found`);
}
if (!primaryEvent.tournamentId) {
throw new Error(
`Event ${primaryEventId} is not linked to a tournament; cannot fan out`
);
}
const tournamentId = primaryEvent.tournamentId;
// Read the primary window's derived results and persist them as canonical
// tournament_results, keyed by canonical participant. Only real placements are
// promoted — unplaced/filler rows are reconstructed per-window by the fan-out.
const primaryResults = await getEventResults(primaryEventId);
const promotedCanonicalIds = new Set<string>();
for (const r of primaryResults) {
if (r.placement === null || r.notParticipating) continue;
const canonicalParticipantId = r.seasonParticipant?.participantId;
if (!canonicalParticipantId) {
logger.warn(
`[syncMajorFromPrimaryEvent] season_participant ${r.seasonParticipantId} has no canonical participant link; skipping`
);
continue;
}
await upsertTournamentResult({
tournamentId,
participantId: canonicalParticipantId,
placement: r.placement,
rawScore: r.rawScore,
});
promotedCanonicalIds.add(canonicalParticipantId);
}
// Remove canonical rows for participants no longer placed on the primary (a
// correction that dropped someone) so the stale placement stops fanning out.
const db = database();
const existingCanonical = await db
.select({ participantId: schema.tournamentResults.participantId })
.from(schema.tournamentResults)
.where(eq(schema.tournamentResults.tournamentId, tournamentId));
const staleIds = existingCanonical
.map((r) => r.participantId)
.filter((id) => !promotedCanonicalIds.has(id));
if (staleIds.length > 0) {
await db
.delete(schema.tournamentResults)
.where(
and(
eq(schema.tournamentResults.tournamentId, tournamentId),
inArray(schema.tournamentResults.participantId, staleIds)
)
);
}
logger.log(
`[syncMajorFromPrimaryEvent] promoted ${promotedCanonicalIds.size} result(s) from primary ${primaryEventId} to tournament ${tournamentId}; removed ${staleIds.length} stale`
);
return syncTournamentResults(tournamentId, {
markComplete,
skipEventId: primaryEventId,
Fix qualifying points scoring, Discord rounding, and majors count Four related bugs in the Qualifying Points subsystem surfaced on Wimbledon: 1. Some leagues stored 2 QP instead of 1.5 for Round-of-16 losers. Sibling/ mirror windows scored via the placement-group path in processQualifyingEvent, which took the tie span from the players present on that window's roster (a draftable subset) instead of the full field. A window holding fewer than the 8 tied R16 losers split the 9-16 points too few ways and over-awarded. The tie span is now derived from the canonical tournament_results (the whole field) for tournament-linked events, falling back to the live count only for standalone events. Every league now scores identically. 2. Discord notifications rounded QP with Math.round, turning 1.5 into "2". Both the "Points Awarded" and "QP Standings" values now use a 2-decimal formatter mirroring the web UI's formatQP, so Discord and the site agree. 3. The Discord "QP Standings" block ranked players only among that event's scorers, showing two R16 losers as T1 instead of T9. Rank is now computed over the full season field and passed through to the notifier. 4. "N of M majors completed" reached "11 of 4": majorsCompleted was a stored counter incremented on every fan-out sync with a guard that misfired. It is now derived on read (getMajorsCompleted = count of completed qualifying events), which is self-correcting; the increment/decrement writes are removed along with the now-unused hasProcessedQualifyingPlacement helper. Adds scripts/backfill-qp-resplit.ts to silently re-score existing majors so already-corrupted seasons are corrected (2 -> 1.5), and threads a skipNotifications option through processQualifyingEvent / syncTournamentResults so the backfill does not re-ping every league. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017AUcHy9m7aF6axsY6Grpe4
2026-07-03 20:40:47 +00:00
skipNotifications,
Unify majors: score once, fan out across windows + tennis bracket EV Make a "major" (golf/tennis/CS2) scored once on its canonical tournament and fan out to every linked sports_season window and league. Fan-out & completion (app/services/sync-tournament-results.ts): - syncTournamentResults now marks each synced window's event complete (gated by markComplete), recalculates affected leagues, and counts recalc failures so a stale league can't hide behind a "completed" badge - syncMajorFromPrimaryEvent promotes a primary window's derived results to canonical tournament_results (deleting rows for dropped placements) and fans out to siblings; fanOutMajorIfPrimary guards on the primary - placement removals now propagate (stale rows reset to filler) Primary-event model (scoring_events.is_primary, migration 0122): - getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent / setPrimaryEvent; event creation auto-seeds a primary for bracket majors; "Make primary" button on the tournament page - per-window event/bracket/cs2 pages are read-only for non-primary linked events (not-participating stays editable) Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG): - bracket-scored qualifying major via the existing bracket pipeline - simulator conditions in-progress EV on the real bracket (honoring completed matches, walkover for withdrawals), QP derived from config, round structure read from the template; CS2 + tennis share resolveStructureSource Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile of existing majors (link orphans, designate primary, promote canonical, sync). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:32:22 -07:00
});
}
/**
* Convenience guard for route handlers: fan out a just-scored bracket/stage event
* to its sibling windows ONLY when it's the designated primary of a shared
* tournament. No-ops for standalone events (no tournament_id) or non-primary
* windows (which are read-only and never scored directly). Failures are logged
* but never thrown fan-out must not break the admin's local scoring action.
*/
export async function fanOutMajorIfPrimary(
event: { id: string; isPrimary: boolean; tournamentId: string | null },
options: { markComplete?: boolean } = {}
): Promise<void> {
if (!event.isPrimary || !event.tournamentId) return;
try {
await syncMajorFromPrimaryEvent(event.id, options);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
logger.error(
`[fanOutMajorIfPrimary] fan-out failed for primary event ${event.id}: ${msg}`
);
}
}