brackt/app/models/scoring-event.ts

1255 lines
44 KiB
TypeScript
Raw Normal View History

import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq, and, desc, asc, gte, lte, or, inArray, isNotNull, sql } from "drizzle-orm";
import type { BracketRegion } from "~/lib/bracket-templates";
import { recalculateAffectedLeagues } from "./scoring-calculator";
import { recalculateParticipantQP } from "./qualifying-points";
2026-06-16 22:11:01 +00:00
import { findParticipantNamesByIds } from "./season-participant";
import { deleteTournament } from "./tournament";
import type { EventType } from "./scoring-event-types";
export { type EventType, getEventTypeLabel } from "./scoring-event-types";
export interface CreateScoringEventData {
sportsSeasonId: string;
name: string;
eventDate?: Date;
eventStartsAt?: Date;
eventType: EventType;
isQualifyingEvent?: boolean;
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
/** Required when isQualifyingEvent=true (DB check constraint). */
tournamentId?: string;
// Template system fields (Phase 2.6)
bracketTemplateId?: string;
scoringStartsAtRound?: string;
}
export interface UpdateScoringEventData {
name?: string;
eventDate?: Date | null;
eventStartsAt?: Date | null;
isComplete?: boolean;
completedAt?: Date;
bracketTemplateId?: string;
scoringStartsAtRound?: string;
/** Per-event region config for NCAA-style brackets (overrides template defaults) */
bracketRegionConfig?: BracketRegion[] | null;
Auto-populate & auto-score tennis Grand Slam brackets from Wikipedia Add a per-event "Sync Draw" that pulls a tennis major's full 128-player draw from its Wikipedia article, auto-creates/links participants (and propagates them to every linked sibling season), builds the bracket, and runs the qualifying-points scorer. Re-running advances the bracket and scoring as matches complete. Core - match-sync: WikipediaTennisAdapter + wikitext bracket parser, DrawSync DTOs, syncTennisDraw orchestrator, pure draw->rows mapping - playoff-match: populateBracketFromDraw (idempotent upsert on externalMatchId) - scoring_events.externalSourceKey column (Wikipedia article; migration 0123) - admin bracket "Sync Draw" card (accepts URL or title) + cron pass Scoring fix - deriveBracketQualifyingStates only floors players who have reached the scoring stage; for deep brackets (tennis_128) early-round losers earn 0 QP instead of a phantom 9th-place floor. CS2/simple_8 behavior preserved (gated on rounds[0].isScoring). Re-sync reconciles stale QP rows in a transaction. Matching & parsing - accent-folding in normalizeTeamName; strip Wikipedia "(tennis)" disambiguators; treat Bye/TBD/Qualifier as TBD; extract wikilink before template-stripping so {{nowrap}}-wrapped players parse Admin UX - dry-run preview (matched / will-create / possible duplicates / unfilled slots) with inline "rename existing" / "create as new" resolution via fetcher (no full reload) Tests: parser vs real 2025 Wimbledon fixture, draw mapping, tennis_128 scoring, accent/disambiguator/nowrap parsing, URL parsing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 00:32:35 -07:00
/** External data-source locator (e.g. Wikipedia article title for tennis draws) */
externalSourceKey?: string | null;
}
/**
* Create a new scoring event
*/
export async function createScoringEvent(
data: CreateScoringEventData,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
const [event] = await db
.insert(schema.scoringEvents)
.values({
sportsSeasonId: data.sportsSeasonId,
name: data.name,
eventDate: data.eventDate ? data.eventDate.toISOString().split('T')[0] : undefined,
eventStartsAt: data.eventStartsAt,
eventType: data.eventType,
isQualifyingEvent: data.isQualifyingEvent || false,
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
tournamentId: data.tournamentId,
bracketTemplateId: data.bracketTemplateId,
scoringStartsAtRound: data.scoringStartsAtRound,
isComplete: false,
})
.returning();
return event;
}
/**
* Get a scoring event by ID
*/
export async function getScoringEventById(
eventId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return await db.query.scoringEvents.findFirst({
where: eq(schema.scoringEvents.id, eventId),
with: {
sportsSeason: {
with: {
sport: true,
},
},
},
});
}
/**
* Get all scoring events for a sports season
*/
export async function getScoringEventsForSportsSeason(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return await db.query.scoringEvents.findMany({
where: eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
orderBy: [desc(schema.scoringEvents.eventDate), desc(schema.scoringEvents.eventStartsAt), desc(schema.scoringEvents.createdAt)],
with: {
eventResults: {
with: {
Canonical tournament layer: schema + backfill (1/2) (#365) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit 66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit 775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
seasonParticipant: true,
},
},
},
});
}
/**
* Get incomplete scoring events for a sports season
*/
export async function getIncompleteScoringEvents(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return await db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, false)
),
orderBy: [desc(schema.scoringEvents.eventDate), desc(schema.scoringEvents.createdAt)],
});
}
/**
* Get qualifying events for a sports season
*/
export async function getQualifyingEvents(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return await db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isQualifyingEvent, true)
),
orderBy: [desc(schema.scoringEvents.eventDate), desc(schema.scoringEvents.createdAt)],
});
}
/**
* Number of "majors completed" for a sports season, derived on read as the count of
* qualifying events that have been marked complete. Replaces the old stored
* sportsSeasons.majorsCompleted counter, which was incremented per fan-out sync and
* over-counted past totalMajors ("11 of 4"). Computing it makes the value
* self-correcting and immune to double-counting.
*/
export async function getMajorsCompleted(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
): Promise<number> {
const db = providedDb || database();
const rows = await db
.select({ count: sql<number>`count(*)::int` })
.from(schema.scoringEvents)
.where(
and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isQualifyingEvent, true),
eq(schema.scoringEvents.isComplete, true)
)
);
return rows[0]?.count ?? 0;
}
/**
* Update a scoring event
*/
export async function updateScoringEvent(
eventId: string,
data: UpdateScoringEventData,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
const updateData: Partial<typeof schema.scoringEvents.$inferInsert> = { updatedAt: new Date() };
if (data.name !== undefined) updateData.name = data.name;
if (data.eventDate !== undefined) {
updateData.eventDate = data.eventDate ? data.eventDate.toISOString().split('T')[0] : null;
}
if (data.eventStartsAt !== undefined) updateData.eventStartsAt = data.eventStartsAt;
if (data.isComplete !== undefined) updateData.isComplete = data.isComplete;
if (data.completedAt !== undefined) updateData.completedAt = data.completedAt;
if (data.bracketTemplateId !== undefined) updateData.bracketTemplateId = data.bracketTemplateId;
if (data.scoringStartsAtRound !== undefined) updateData.scoringStartsAtRound = data.scoringStartsAtRound;
if (data.bracketRegionConfig !== undefined) updateData.bracketRegionConfig = data.bracketRegionConfig;
Auto-populate & auto-score tennis Grand Slam brackets from Wikipedia Add a per-event "Sync Draw" that pulls a tennis major's full 128-player draw from its Wikipedia article, auto-creates/links participants (and propagates them to every linked sibling season), builds the bracket, and runs the qualifying-points scorer. Re-running advances the bracket and scoring as matches complete. Core - match-sync: WikipediaTennisAdapter + wikitext bracket parser, DrawSync DTOs, syncTennisDraw orchestrator, pure draw->rows mapping - playoff-match: populateBracketFromDraw (idempotent upsert on externalMatchId) - scoring_events.externalSourceKey column (Wikipedia article; migration 0123) - admin bracket "Sync Draw" card (accepts URL or title) + cron pass Scoring fix - deriveBracketQualifyingStates only floors players who have reached the scoring stage; for deep brackets (tennis_128) early-round losers earn 0 QP instead of a phantom 9th-place floor. CS2/simple_8 behavior preserved (gated on rounds[0].isScoring). Re-sync reconciles stale QP rows in a transaction. Matching & parsing - accent-folding in normalizeTeamName; strip Wikipedia "(tennis)" disambiguators; treat Bye/TBD/Qualifier as TBD; extract wikilink before template-stripping so {{nowrap}}-wrapped players parse Admin UX - dry-run preview (matched / will-create / possible duplicates / unfilled slots) with inline "rename existing" / "create as new" resolution via fetcher (no full reload) Tests: parser vs real 2025 Wimbledon fixture, draw mapping, tennis_128 scoring, accent/disambiguator/nowrap parsing, URL parsing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 00:32:35 -07:00
if (data.externalSourceKey !== undefined) updateData.externalSourceKey = data.externalSourceKey;
const [updated] = await db
.update(schema.scoringEvents)
.set(updateData)
.where(eq(schema.scoringEvents.id, eventId))
.returning();
return updated;
}
/**
* Mark a scoring event as complete
*/
export async function completeScoringEvent(
eventId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return await updateScoringEvent(
eventId,
{
isComplete: true,
completedAt: new Date(),
},
db
);
}
/**
* Delete a scoring event.
* For bracket events (playoff_game), also clears all participant results for the
* sports season (placements are stored there with no FK back to the event) and
* recalculates league standings.
*/
export interface DeleteScoringEventOptions {
/**
* When this was the last window linked to its shared tournament, also delete
* the now-orphaned canonical tournament (and its results). No-op when other
* windows remain. Off by default so deleting one season's event never touches
* the shared tournament unless explicitly requested.
*/
deleteOrphanTournament?: boolean;
}
export interface DeleteScoringEventResult {
/** The shared tournament this event was linked to, if any. */
tournamentId: string | null;
/** How many other windows still link to that tournament after the delete. */
remainingWindows: number;
/** Event promoted to primary because the deleted event was the primary window. */
promotedPrimaryId: string | null;
/** Whether the orphaned canonical tournament was deleted. */
deletedTournament: boolean;
}
export async function deleteScoringEvent(
eventId: string,
providedDb?: ReturnType<typeof database>,
opts?: DeleteScoringEventOptions
): Promise<DeleteScoringEventResult> {
const db = providedDb || database();
const event = await db.query.scoringEvents.findFirst({
where: eq(schema.scoringEvents.id, eventId),
});
if (!event) {
return {
tournamentId: null,
remainingWindows: 0,
promotedPrimaryId: null,
deletedTournament: false,
};
}
// For qualifying events: capture affected participant IDs before the cascade deletes
// eventResults (which is how we know who had QP awarded from this event).
let affectedParticipantIds: string[] = [];
if (event.isQualifyingEvent) {
const results = await db.query.eventResults.findMany({
where: eq(schema.eventResults.scoringEventId, eventId),
});
Canonical tournament layer: schema + backfill (1/2) (#365) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit 66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit 775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
affectedParticipantIds = results.map((r) => r.seasonParticipantId);
}
await db.transaction(async (tx) => {
if (event.eventType === "playoff_game" || event.eventType === "major_tournament") {
await tx
Canonical tournament layer: schema + backfill (1/2) (#365) * refactor(schema): rename per-window tables to season_* prefix Renames participants, participant_expected_values, participant_qualifying_totals, participant_results, participant_surface_elos to season_* prefixed names. Renames event_results.participant_id to season_participant_id. Phase 1a of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: rename participant.ts model file to season-participant.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(models): update model layer to use renamed schema exports Updated all model files to use the renamed schema exports from Task 1: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantQualifyingTotals → seasonParticipantQualifyingTotals - participantResults → seasonParticipantResults - participantSurfaceElos → seasonParticipantSurfaceElos - eventResults.participantId → eventResults.seasonParticipantId - db.query relation accessors updated - Relation field .participant → .seasonParticipant where applicable - Import paths updated: ./participant → ./season-participant Files updated (14 model files + 3 test files): - draft-pick.ts - draft-utils.ts - event-result.ts - group-stage-match.ts - participant-result.ts - qualifying-points.ts - scoring-calculator.ts - scoring-event.ts - sports-season.ts - surface-elo.ts - team-score-events.ts - cs2-major-stage.ts - golf-skills.ts - participant-expected-value.ts - __tests__/sports-season.clone.test.ts - __tests__/auto-pick.test.ts - __tests__/executeAutoPick.timer.test.ts Typecheck errors decreased: 779 → 499 (280 fewer) All model file errors related to renamed schemas resolved. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route layer to use renamed schema exports - Update model import from ~/models/participant to ~/models/season-participant - Rename schema.participants to schema.seasonParticipants - Rename schema.participantResults to schema.seasonParticipantResults - Rename db.query.participants to db.query.seasonParticipants - Update 9 route files and 1 test file Affected files: - admin.sports-seasons.$id.events.$eventId.bracket.server.ts - admin.sports-seasons.$id.participants.tsx - api/draft.force-manual-pick.ts - api/draft.make-pick.ts - api/draft.replace-pick.ts - api/seasons.$seasonId.draft.ts - leagues/$leagueId.draft-board.$seasonId.tsx - leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts - admin/__tests__/sports-seasons-participants.test.ts Error count reduced from 499 to 453 (46 errors fixed). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(routes): update route files for schema rename Update route imports from ~/models/participant to ~/models/season-participant and fix references to .participant/.participantId on event results to use .seasonParticipant/.seasonParticipantId after schema rename. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(services): update simulators and services for renamed schema Update all simulators, services, and server files to use renamed schema tables: - participants → seasonParticipants - participantExpectedValues → seasonParticipantExpectedValues - participantResults → seasonParticipantResults - eventResults.participantId → eventResults.seasonParticipantId Files updated: - 20 sport simulators (NBA, NHL, NFL, MLB, etc.) - probability-updater.ts - standings-sync/index.ts - sports-data-sync.server.ts - server/socket.ts Typecheck errors reduced from 365 to 0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: rename per-window tables to season_* prefix * fix(tests): update mock query keys after participants table rename Change mock db.query.participants to db.query.seasonParticipants in test files to match the schema rename from commit 66145a9. This fixes "Cannot read properties of undefined (reading 'findFirst'/'findMany')" errors that occurred when production code queries db.query.seasonParticipants but test mocks only defined the old participants key. Files updated: - app/services/simulations/__tests__/world-cup-simulator.test.ts - app/routes/api/__tests__/draft.force-manual-pick.test.ts - app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts - app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts - server/__tests__/timer-autodraft.test.ts - app/models/__tests__/team-score-events.test.ts Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(tests): update remaining mock paths and keys after schema rename * fix(tests): final two mock stragglers after schema rename - draft-pick.test.ts: assertion on db.query.participantQualifyingTotals - process-match-result.test.ts: mock key participants → seasonParticipants Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore: add post-phase1a baseline capture (temp, for diff verification) * chore: capture pre-migration baselines * chore: remove post-phase1a capture helper after verification * schema: add canonical tournament & participant tables Adds tournaments, participants (canonical), tournament_results, and participant_surface_elos (canonical). Adds nullable tournament_id to scoring_events and nullable participant_id to season_participants. Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(models): add canonical tournament, participant, result, surface-elo models Adds CRUD modules for the canonical tables created in commit 775b905. Each module mirrors existing app/models conventions (database() from ~/database/context, schema from ~/database/schema, mock-based tests). Key implementation notes: - participant.ts exports use "Canonical" prefix (CanonicalParticipant, createCanonicalParticipant, etc.) to avoid collision with existing season-participant.ts exports - All four models include comprehensive unit tests following the audit-log.test.ts pattern - Tests use mocked db responses (no real database access) - Upsert functions use onConflictDoUpdate for appropriate unique constraints Part of Phase 1b of canonical tournament layer migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * migration: create canonical tables, add nullable FKs * scripts: add extractTournamentIdentity helper for backfill Pure function that derives canonical (name, year) identity from a scoring_events row, stripping trailing 4-digit years from the name or falling back to eventDate. Used by the Phase 2 backfill to group per-window events into canonical tournaments. * scripts: add backfill orchestrator for canonical layer Populates canonical tournaments, participants, tournament_results, and participant_surface_elos from per-window data for qualifying-points sports. Skips already-linked rows, is idempotent, and supports dry-run mode. Critical invariants enforced by the implementation: - qualifying_points_awarded is never copied to tournament_results - season_participant_qualifying_totals is never touched - conflicting surface-Elo values between windows raise a loud error (recorded in report.errors) rather than overwriting * scripts: add backfill CLI with dry-run default Wires backfill-canonical-layer.ts to a CLI entry point exposed as `npm run backfill:canonical`. Defaults to --dry-run; requires --apply to actually write. Supports --sport=<uuid> to limit to a single sport. Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts). * fix(backfill-cli): wrap runBackfill in DatabaseContext.run The orchestrator uses database() from ~/database/context, which requires AsyncLocalStorage to be populated. Wrap the CLI invocation with DatabaseContext.run(db, ...) using server/db's cached connection pool. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backfill-cli): exit 0 on success so pg pool doesn't block The cached postgres connection pool keeps the Node event loop open after main() returns. Explicit process.exit(0) on success mirrors the pattern in scripts/capture-baseline.ts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Chris Parsons <chrisp@extrahop.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
.delete(schema.seasonParticipantResults)
.where(eq(schema.seasonParticipantResults.sportsSeasonId, event.sportsSeasonId));
}
// Cascades: playoffMatches, eventResults, tournamentGroups/Members
await tx.delete(schema.scoringEvents).where(eq(schema.scoringEvents.id, eventId));
});
if (event.eventType === "playoff_game" || event.eventType === "major_tournament") {
await recalculateAffectedLeagues(event.sportsSeasonId, db);
}
if (event.isQualifyingEvent && affectedParticipantIds.length > 0) {
// eventResults have been cascade-deleted; recalculate QP totals from remaining events
for (const participantId of affectedParticipantIds) {
await recalculateParticipantQP(participantId, event.sportsSeasonId, db);
}
// majorsCompleted is derived on read (getMajorsCompleted), so deleting the event
// — which removes it from the completed-qualifying-event count — self-corrects the
// number. No stored counter to decrement.
await recalculateAffectedLeagues(event.sportsSeasonId, db);
}
// Shared-tournament bookkeeping: keep the primary window valid and optionally
// clean up a canonical tournament left with no windows.
let remainingWindows = 0;
let promotedPrimaryId: string | null = null;
let deletedTournament = false;
if (event.tournamentId) {
const remaining = await db.query.scoringEvents.findMany({
where: eq(schema.scoringEvents.tournamentId, event.tournamentId),
orderBy: asc(schema.scoringEvents.createdAt),
});
remainingWindows = remaining.length;
if (remaining.length > 0) {
// Auto-heal: if the deleted event was the primary window, promote the
// earliest remaining window so the shared major stays scorable and
// fan-out stays deterministic. Only heal when we actually removed the
// primary — golf-style majors intentionally have no primary (scored on the
// canonical tournament page), and event.isPrimary is false for them, so
// they are left untouched.
if (event.isPrimary) {
await setPrimaryEvent(remaining[0].id, db);
promotedPrimaryId = remaining[0].id;
}
} else if (opts?.deleteOrphanTournament) {
await deleteTournament(event.tournamentId, db);
deletedTournament = true;
}
}
return {
tournamentId: event.tournamentId,
remainingWindows,
promotedPrimaryId,
deletedTournament,
};
}
/**
* Check if all events for a sports season are complete
*/
export async function areAllEventsComplete(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
): Promise<boolean> {
const db = providedDb || database();
const incompleteEvents = await getIncompleteScoringEvents(sportsSeasonId, db);
return incompleteEvents.length === 0;
}
/**
* Get upcoming (not yet complete) scoring events for a sports season,
2026-06-16 14:11:51 +00:00
* ordered by effective start date ascending (soonest first).
*
* Effective date = min(eventDate, eventStartsAt, earliest future bracket-game scheduledAt).
* This ensures CS2 Champions Stage events (which have game times set on
* playoff_match_games but no eventDate on the event record) sort correctly.
*/
export async function getUpcomingScoringEvents(
sportsSeasonId: string,
limit = 5,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
2026-06-16 14:11:51 +00:00
// Over-fetch relative to the requested limit so the subsequent game-time
// re-sort has enough candidates without an unbounded query.
const events = await db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, false)
),
orderBy: [asc(schema.scoringEvents.eventDate), asc(schema.scoringEvents.eventStartsAt), asc(schema.scoringEvents.createdAt)],
2026-06-16 14:11:51 +00:00
limit: Math.max(limit * 5, 50),
});
2026-06-16 14:11:51 +00:00
if (events.length === 0) return [];
// Find earliest upcoming game time per event from both bracket match games
// and group stage matches (FIFA World Cup style).
2026-06-16 14:11:51 +00:00
const eventIds = events.map((e) => e.id);
const now = new Date();
const [gameTimeRows, groupStageTimeRows] = await Promise.all([
db
.select({
eventId: schema.scoringEvents.id,
scheduledAt: schema.playoffMatchGames.scheduledAt,
})
.from(schema.scoringEvents)
.innerJoin(
schema.playoffMatches,
eq(schema.playoffMatches.scoringEventId, schema.scoringEvents.id)
)
.innerJoin(
schema.playoffMatchGames,
eq(schema.playoffMatchGames.playoffMatchId, schema.playoffMatches.id)
)
.where(
and(
inArray(schema.scoringEvents.id, eventIds),
isNotNull(schema.playoffMatchGames.scheduledAt),
gte(schema.playoffMatchGames.scheduledAt, now)
)
),
db
.select({
eventId: schema.tournamentGroups.scoringEventId,
scheduledAt: schema.groupStageMatches.scheduledAt,
})
.from(schema.groupStageMatches)
.innerJoin(
schema.tournamentGroups,
eq(schema.groupStageMatches.tournamentGroupId, schema.tournamentGroups.id)
2026-06-16 14:11:51 +00:00
)
.where(
and(
inArray(schema.tournamentGroups.scoringEventId, eventIds),
isNotNull(schema.groupStageMatches.scheduledAt),
gte(schema.groupStageMatches.scheduledAt, now)
)
),
]);
2026-06-16 14:11:51 +00:00
const earliestGameById = new Map<string, Date>();
for (const row of [...gameTimeRows, ...groupStageTimeRows]) {
2026-06-16 14:11:51 +00:00
if (!row.scheduledAt) continue;
const prev = earliestGameById.get(row.eventId);
if (!prev || row.scheduledAt < prev) {
earliestGameById.set(row.eventId, row.scheduledAt);
}
}
const getEffectiveMs = (e: (typeof events)[0]): number => {
const candidates: number[] = [];
if (e.eventDate) candidates.push(new Date(e.eventDate + "T00:00:00Z").getTime());
if (e.eventStartsAt) candidates.push(e.eventStartsAt.getTime());
const game = earliestGameById.get(e.id);
if (game) candidates.push(game.getTime());
return candidates.length > 0 ? Math.min(...candidates) : Infinity;
};
return events
.toSorted((a, b) => getEffectiveMs(a) - getEffectiveMs(b))
.slice(0, limit)
.map((e) => ({
...e,
earliestGameTime: earliestGameById.get(e.id)?.toISOString()
?? e.eventStartsAt?.toISOString()
?? null,
}));
}
/**
* Get the single next upcoming event for a sports season (for card display).
*/
export async function getNextScoringEvent(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
) {
const upcoming = await getUpcomingScoringEvents(sportsSeasonId, 1, providedDb);
return upcoming[0] || null;
}
/**
* Get recently completed scoring events for a sports season,
* ordered by completedAt descending (most recent first).
*/
export async function getRecentCompletedEvents(
sportsSeasonId: string,
limit = 3,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
return db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, true)
),
orderBy: [desc(schema.scoringEvents.completedAt), desc(schema.scoringEvents.eventDate)],
limit,
});
}
2026-03-12 10:12:38 -07:00
// Scoring patterns where each participant competes in every event.
// Valid scoringPatternEnum values: playoff_bracket | season_standings | qualifying_points
const ALL_COMPETE_PATTERNS = new Set(["season_standings", "qualifying_points"]);
export interface UpcomingParticipantEvent {
id: string;
2026-06-16 14:11:51 +00:00
/**
* The actual scoring event database ID. For all-compete events this equals id;
* for bracket events id is a composite key (eventId|matchId|gameNum) so this
* separate field is needed to build event-detail page links.
* null/undefined for group-stage match entries and legacy callers.
*/
scoringEventId?: string | null;
2026-03-12 10:12:38 -07:00
name: string;
eventDate: string | null;
/**
* Earliest scheduledAt timestamp (ISO string) across individual playoff match
* games for this event bracket sports only. Used when eventDate is null.
*/
earliestGameTime: string | null;
/**
2026-06-16 22:11:01 +00:00
* e.g. "Team Spirit vs G2 Esports" the bracket matchup, derived from
* playoffMatches.participant1Id/participant2Id (or group-stage match
* participants). Falls back to a round/game-number label (e.g. "Semifinals
* Game #1") when neither participant's name resolves. null when unavailable
* or redundant with event name.
2026-03-12 10:12:38 -07:00
*/
matchLabel: string | null;
eventType: string;
sportsSeasonId: string;
/** simulatorType from the parent sport — used to distinguish bracket-majors from manual-entry majors */
simulatorType?: string | null;
2026-03-12 10:12:38 -07:00
/** Only the current user's drafted participants involved in this event */
relevantParticipants: Array<{ id: string; name: string }>;
}
/**
* Get upcoming scoring events (within the given date window) that involve
* at least one of the given drafted participants.
*
* - Bracket sports (playoff_bracket, ucl_bracket): only events where a
* participant appears in a playoff match.
* - All-compete sports (season_standings, qualifying_points, etc.): every
* upcoming event; all draftedParticipants are attached.
*
* Events without a date or that are already complete are excluded.
*/
export async function getUpcomingEventsForDraftedParticipants(
sportsSeasonId: string,
scoringPattern: string,
draftedParticipants: Array<{ id: string; name: string }>,
dateFromStr: string,
dateToStr: string,
2026-03-12 10:12:38 -07:00
providedDb?: ReturnType<typeof database>
): Promise<UpcomingParticipantEvent[]> {
if (draftedParticipants.length === 0) return [];
const db = providedDb || database();
const draftedIds = draftedParticipants.map((p) => p.id);
const draftedMap = new Map(draftedParticipants.map((p) => [p.id, p]));
2026-06-16 14:11:51 +00:00
// Timestamp bounds used by both all-compete and bracket paths below.
const dateFromTimestampAllCompete = new Date(dateFromStr + "T00:00:00.000Z");
const dateToTimestampAllCompete = new Date(dateToStr + "T23:59:59.999Z");
2026-03-12 10:12:38 -07:00
if (ALL_COMPETE_PATTERNS.has(scoringPattern)) {
2026-06-16 14:11:51 +00:00
// Primary: events with eventDate in the window.
const eventsByDate = await db.query.scoringEvents.findMany({
2026-03-12 10:12:38 -07:00
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, false),
isNotNull(schema.scoringEvents.eventDate),
gte(schema.scoringEvents.eventDate, dateFromStr),
lte(schema.scoringEvents.eventDate, dateToStr)
),
orderBy: [asc(schema.scoringEvents.eventDate)],
});
2026-06-16 14:11:51 +00:00
const foundByDateIds = new Set(eventsByDate.map((e) => e.id));
// Secondary: events that have bracket game times within the window.
// This catches CS2 Champions Stage bracket events whose eventDate is in
// the past (or unset) but which have upcoming playoff_match_games scheduled.
const gameTimeRows = await db
.select({
eventId: schema.scoringEvents.id,
scheduledAt: schema.playoffMatchGames.scheduledAt,
})
.from(schema.scoringEvents)
.innerJoin(
schema.playoffMatches,
eq(schema.playoffMatches.scoringEventId, schema.scoringEvents.id)
)
.innerJoin(
schema.playoffMatchGames,
eq(schema.playoffMatchGames.playoffMatchId, schema.playoffMatches.id)
)
.where(
and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, false),
isNotNull(schema.playoffMatchGames.scheduledAt),
gte(schema.playoffMatchGames.scheduledAt, dateFromTimestampAllCompete),
lte(schema.playoffMatchGames.scheduledAt, dateToTimestampAllCompete)
)
);
// Collect earliest game time per event; track which event IDs are new.
const earliestGameTimeById = new Map<string, Date>();
const extraEventIds = new Set<string>();
for (const row of gameTimeRows) {
if (!row.scheduledAt) continue;
const prev = earliestGameTimeById.get(row.eventId);
if (!prev || row.scheduledAt < prev) {
earliestGameTimeById.set(row.eventId, row.scheduledAt);
}
if (!foundByDateIds.has(row.eventId)) {
extraEventIds.add(row.eventId);
}
}
// Fetch full event records for any extras not already in eventsByDate.
let extraEvents: (typeof eventsByDate)[0][] = [];
if (extraEventIds.size > 0) {
extraEvents = await db.query.scoringEvents.findMany({
where: inArray(schema.scoringEvents.id, [...extraEventIds]),
});
}
// Merge and sort by effective start date (eventDate → eventStartsAt → game time).
const allEvents = [...eventsByDate, ...extraEvents];
const getEffectiveMs = (e: (typeof allEvents)[0]): number => {
const candidates: number[] = [];
if (e.eventDate) candidates.push(new Date(e.eventDate + "T00:00:00Z").getTime());
if (e.eventStartsAt) candidates.push(e.eventStartsAt.getTime());
const game = earliestGameTimeById.get(e.id);
if (game) candidates.push(game.getTime());
return candidates.length > 0 ? Math.min(...candidates) : Infinity;
};
allEvents.sort((a, b) => getEffectiveMs(a) - getEffectiveMs(b));
return allEvents.map((e) => {
const gameTime = earliestGameTimeById.get(e.id);
return {
id: e.id,
scoringEventId: e.id,
name: e.name,
eventDate: e.eventDate,
earliestGameTime: gameTime
? gameTime.toISOString()
: e.eventStartsAt
? e.eventStartsAt.toISOString()
: null,
matchLabel: null,
eventType: e.eventType,
sportsSeasonId: e.sportsSeasonId,
relevantParticipants: draftedParticipants,
};
});
2026-03-12 10:12:38 -07:00
}
// Bracket sports: join through playoff_matches → playoff_match_games to find relevant events.
// scoringEvent.eventDate may be null — admins often set dates on individual games
// (playoffMatchGames.scheduledAt) rather than on the event record itself.
// We include an event if EITHER its eventDate OR any of its game scheduledAt timestamps
// falls within the window.
2026-06-16 14:11:51 +00:00
const dateFromTimestamp = dateFromTimestampAllCompete;
const dateToTimestamp = dateToTimestampAllCompete;
2026-03-12 10:12:38 -07:00
const rows = await db
.selectDistinct({
id: schema.scoringEvents.id,
name: schema.scoringEvents.name,
eventDate: schema.scoringEvents.eventDate,
eventType: schema.scoringEvents.eventType,
sportsSeasonId: schema.scoringEvents.sportsSeasonId,
playoffMatchId: schema.playoffMatches.id,
2026-03-12 10:12:38 -07:00
participant1Id: schema.playoffMatches.participant1Id,
participant2Id: schema.playoffMatches.participant2Id,
round: schema.playoffMatches.round,
gameNumber: schema.playoffMatchGames.gameNumber,
scheduledAt: schema.playoffMatchGames.scheduledAt,
})
.from(schema.scoringEvents)
.innerJoin(
schema.playoffMatches,
eq(schema.playoffMatches.scoringEventId, schema.scoringEvents.id)
)
.leftJoin(
schema.playoffMatchGames,
eq(schema.playoffMatchGames.playoffMatchId, schema.playoffMatches.id)
)
.where(
and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.scoringEvents.isComplete, false),
eq(schema.playoffMatches.isComplete, false),
2026-03-12 10:12:38 -07:00
or(
inArray(schema.playoffMatches.participant1Id, draftedIds),
// participant2Id is nullable UUID — same underlying type as participant1Id;
// the notNull difference only exists at the TypeScript layer
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
// oxlint-disable-next-line typescript/no-explicit-any -- participant2Id is nullable UUID; notNull difference only exists at the TypeScript layer
2026-03-12 10:12:38 -07:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
inArray(schema.playoffMatches.participant2Id as any, draftedIds)
),
or(
// scoringEvent has an explicit date within the window
and(
isNotNull(schema.scoringEvents.eventDate),
gte(schema.scoringEvents.eventDate, dateFromStr),
lte(schema.scoringEvents.eventDate, dateToStr)
),
// Or one of the individual games is scheduled within the window
and(
isNotNull(schema.playoffMatchGames.scheduledAt),
gte(schema.playoffMatchGames.scheduledAt, dateFromTimestamp),
lte(schema.playoffMatchGames.scheduledAt, dateToTimestamp)
)
)
)
)
.orderBy(asc(schema.scoringEvents.eventDate));
2026-06-16 22:11:01 +00:00
// Look up names for ALL participants in these matches (not just drafted
// ones) so matchLabel can show the "P1 vs P2" matchup, mirroring the
// group-stage matchLabel below. Run alongside the max-game-number lookup
// below since neither depends on the other's result.
const allMatchParticipantIds = [
...new Set(
rows.flatMap((r) => [r.participant1Id, r.participant2Id]).filter((id): id is string => !!id)
),
];
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const eventIdsFromRows = [...new Set(rows.map((r) => r.id))];
2026-06-16 22:11:01 +00:00
const [matchParticipantNameById, maxGameNumberByEvent] = await Promise.all([
findParticipantNamesByIds(db, allMatchParticipantIds),
(async () => {
// Determine max game number per event across ALL games (not date-filtered)
// so we can distinguish single-game matchups from multi-game series.
const map = new Map<string, number>();
if (eventIdsFromRows.length === 0) return map;
const allGameRows = await db
.selectDistinct({
eventId: schema.scoringEvents.id,
gameNumber: schema.playoffMatchGames.gameNumber,
})
.from(schema.scoringEvents)
.innerJoin(
schema.playoffMatches,
eq(schema.playoffMatches.scoringEventId, schema.scoringEvents.id)
)
.innerJoin(
schema.playoffMatchGames,
eq(schema.playoffMatchGames.playoffMatchId, schema.playoffMatches.id)
)
.where(inArray(schema.scoringEvents.id, eventIdsFromRows));
for (const row of allGameRows) {
if (row.gameNumber !== null) {
const current = map.get(row.eventId) ?? 0;
map.set(row.eventId, Math.max(current, row.gameNumber));
}
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
}
2026-06-16 22:11:01 +00:00
return map;
})(),
]);
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
// Group rows into calendar entries.
// Series events (max game number > 1) get one entry per game so each game
// appears as its own row on the calendar. Single-game events get one entry.
const entryMap = new Map<string, UpcomingParticipantEvent>();
const participantsByEntry = new Map<string, Map<string, { id: string; name: string }>>();
const gameKeysByEntry = new Map<string, Set<string>>();
const earliestTimeByEntry = new Map<string, Date>();
const isSeriesByEntry = new Map<string, boolean>();
2026-06-16 22:11:01 +00:00
const matchupIdsByEntry = new Map<string, { p1Id: string | null; p2Id: string | null }>();
2026-03-12 10:12:38 -07:00
for (const row of rows) {
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const isSeries = (maxGameNumberByEvent.get(row.id) ?? 1) > 1;
const entryKey =
isSeries && row.gameNumber !== null
? `${row.id}|${row.playoffMatchId}|${row.gameNumber}`
: `${row.id}|${row.playoffMatchId}`;
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
if (!entryMap.has(entryKey)) {
entryMap.set(entryKey, {
id: entryKey,
2026-06-16 14:11:51 +00:00
scoringEventId: row.id,
2026-03-12 10:12:38 -07:00
name: row.name,
eventDate: row.eventDate,
earliestGameTime: null,
matchLabel: null,
eventType: row.eventType,
sportsSeasonId: row.sportsSeasonId,
relevantParticipants: [],
});
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
participantsByEntry.set(entryKey, new Map());
gameKeysByEntry.set(entryKey, new Set());
isSeriesByEntry.set(entryKey, isSeries);
2026-06-16 22:11:01 +00:00
matchupIdsByEntry.set(entryKey, { p1Id: row.participant1Id, p2Id: row.participant2Id });
2026-03-12 10:12:38 -07:00
}
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const pMap = participantsByEntry.get(entryKey);
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196) * Fix no-shadow and consistent-function-scoping lint violations Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint warnings and promotes both rules to errors in .oxlintrc.json. no-shadow: renamed Drizzle callback params (sports→s, matches→m, seasons→s) to avoid shadowing outer imports; removed shadowed destructures (eq, inArray) from where callbacks; renamed inner template→bracketTemplate, prev→currentTimers, season→ss, name→teamName (with name: teamName fix to preserve semantics). consistent-function-scoping: moved formatDate, getRankBadge, getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr, elo (×2), weightedPick, sortByMatchNumber (×2) to module scope; moved formatTime (×2), isValidLeagueName, getDraftTimes, makeSeasonQueues to file scope in test files. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-non-null-assertion lint violations and promote to error Eliminates all 208 no-non-null-assertion warnings across 38 files. Promotes typescript/no-non-null-assertion from warn to error in .oxlintrc.json. Fix patterns applied: - Map.get(key)! after .has() check → extract with get() + null guard - Map.get(key)! on pre-populated count maps → ?? 0 default - .set(id, map.get(id)! + 1) increment → ?? 0 before adding - participant1Id!/participant2Id! on DB matches → ?? "" fallback - array.find()! in tests → guard + throw or expect().toBeDefined() - bracketTemplateCache.get(id)! → null guard extract - Various nullable field accesses → optional chain or ?? default Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers Resolves all 9 remaining non-console lint warnings and promotes all three rules to errors in .oxlintrc.json. - prefer-add-event-listener: converted onchange/onclick/onload assignments to addEventListener in useDraftNotifications.ts and admin.data-sync.tsx; stored changeHandler ref for proper cleanup with removeEventListener - no-unassigned-import: configured rule with allow list for legitimate side-effect imports (*.css, @testing-library/jest-dom, @testing-library/cypress/add-commands) - require-module-specifiers: removed redundant `export {}` from cypress/support/e2e.ts (file already has an import) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix TypeScript errors from no-non-null-assertion fixes Two fixes introduced by the non-null assertion cleanup produced type errors: - scoring-event.ts: `?? ""` was wrong type for a participant object map; restructured to explicit null guards so TypeScript can narrow correctly - standings-sync/index.ts: `?? null` after name-match lookup lost the truthy guarantee, causing TS18047 on the write-back block; added `participant &&` guard before accessing its properties Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Add npm run typecheck as Stop hook in Claude settings Runs a full project typecheck at the end of each Claude turn so type errors surface as feedback before the next message. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
if (pMap) {
if (row.participant1Id) {
const p1 = draftedMap.get(row.participant1Id);
if (p1) pMap.set(row.participant1Id, p1);
}
if (row.participant2Id) {
const p2 = draftedMap.get(row.participant2Id);
if (p2) pMap.set(row.participant2Id, p2);
}
2026-03-12 10:12:38 -07:00
}
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
if (row.round && row.gameNumber !== null) {
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
gameKeysByEntry.get(entryKey)?.add(`${row.round}|${row.gameNumber}`);
2026-03-12 10:12:38 -07:00
}
if (row.scheduledAt) {
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const prev = earliestTimeByEntry.get(entryKey);
2026-03-12 10:12:38 -07:00
if (!prev || row.scheduledAt < prev) {
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
earliestTimeByEntry.set(entryKey, row.scheduledAt);
2026-03-12 10:12:38 -07:00
}
}
}
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
for (const [entryKey, event] of entryMap) {
event.relevantParticipants = Array.from(participantsByEntry.get(entryKey)?.values() ?? []);
2026-03-12 10:12:38 -07:00
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const earliest = earliestTimeByEntry.get(entryKey);
2026-03-12 10:12:38 -07:00
event.earliestGameTime = earliest ? earliest.toISOString() : null;
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
const isSeries = isSeriesByEntry.get(entryKey) ?? false;
const gameKeys = gameKeysByEntry.get(entryKey) ?? new Set<string>();
2026-06-16 22:11:01 +00:00
// matchLabel shows the "P1 vs P2" matchup whenever either participant's
// name is known — the round/game-number info is intentionally NOT
// included (the event name + sport already give that context); it's
// only used as a last-resort fallback when no participant name resolved
// at all (e.g. a deleted/orphaned participant row).
const matchupIds = matchupIdsByEntry.get(entryKey);
const p1Name = matchupIds?.p1Id ? matchParticipantNameById.get(matchupIds.p1Id) : undefined;
const p2Name = matchupIds?.p2Id ? matchParticipantNameById.get(matchupIds.p2Id) : undefined;
const matchupLabel = p1Name || p2Name ? `${p1Name ?? "?"} vs ${p2Name ?? "?"}` : null;
let roundLabel: string | null = null;
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
if (isSeries) {
if (gameKeys.size >= 1) {
const [round, gameNumberStr] = [...gameKeys][0].split("|");
2026-06-16 22:11:01 +00:00
roundLabel =
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
round === event.name ? `Game #${gameNumberStr}` : `${round} Game #${gameNumberStr}`;
}
} else {
// Single-game: omit the game number, just show the round name.
if (gameKeys.size === 1) {
const [round] = [...gameKeys][0].split("|");
2026-06-16 22:11:01 +00:00
roundLabel = round === event.name ? null : round;
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
} else if (gameKeys.size > 1) {
const rounds = new Set([...gameKeys].map((k) => k.split("|")[0]));
if (rounds.size === 1) {
const round = [...rounds][0];
2026-06-16 22:11:01 +00:00
roundLabel = round === event.name ? null : round;
Don't show Game #1 label for single-game matchups in calendar (#206) * Don't show Game #1 label for single-game matchups in calendar When a matchup has only one game, showing "Game #1" is redundant and unhelpful. Only show game numbers when there are multiple games in a matchup (gameKeys.size > 1). For single-game matchups, show just the round name (or null if it matches the event name). Closes #198 https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number for Game #2+ in series, hide Game #1 for single-game matchups If a matchup has only one game (game #1), the number is redundant — show just the round name. If game #2 or higher is upcoming, it clearly belongs to a multi-game series, so show the game number to distinguish it. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Fix Game #1 label for multi-game series when only Game #1 is in date window Previously, Game #1 of a multi-game series showed no game number (e.g. "Semifinals") if Game #2 fell outside the calendar date range. Since at least 2 games are always entered for a series from the start, a second un-date-filtered query now checks the max game number per event. If max > 1, the event is a series and Game #1 is labelled accordingly (e.g. "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Show game number when multiple games from same series are in date window The gameKeys.size > 1 branch previously showed only the round name, contradicting the rule that multi-game series always show "Game #x". Now shows the lowest game number visible in the window (e.g. both Game #1 and #2 upcoming → "Semifinals Game #1"). https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Split series games into individual calendar entries, each showing Game #x Each game in a multi-game bracket series (e.g. Game #1 on Mar 23, Game #2 on Mar 25) now appears as its own row on the calendar with its own date and "Round Game #x" label. Single-game matchups are unchanged. Grouping key changes from eventId to eventId|gameNumber for series events. The max-game-number lookup now runs before grouping so the correct key can be determined while processing each row. https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX * Cache isSeries per entry to avoid re-deriving it in the finalization loop https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
}
2026-03-12 10:12:38 -07:00
}
}
2026-06-16 22:11:01 +00:00
event.matchLabel = matchupLabel ?? roundLabel;
2026-03-12 10:12:38 -07:00
}
Fix World Cup group stage display and upcoming events (#55) ## Summary - **Group stage match list**: Removed MD 1/2/3 headings; matches now listed chronologically under date separators (e.g. "Jun 14"). Kick-off time appears below the team names instead of between them. - **Sort order**: \`findMatchesByGroupIds\` / \`findMatchesByEventId\` now order by \`scheduledAt ASC NULLS LAST\` so unscheduled matches always trail scheduled ones. - **Groups/Bracket toggle**: When both group stage and knockout bracket exist, a toggle appears (mirroring the NBA/AFL standings toggle). Sports with both regular-season standings and a group stage get all views available. - **Upcoming events**: \`getUpcomingEventsForDraftedParticipants\` now also queries \`groupStageMatches\`, so World Cup group fixtures appear on the home page calendar sorted by kick-off time with a label like "Group A — France vs Germany". - **\`isAllCompete\` fix**: \`UpcomingEventsCard\` and \`UpcomingCalendarPanel\` now treat \`group_stage_match\` as a bracket-style event, showing team badges instead of "N of your picks". Fixes #53 ## Test plan - [ ] Navigate to a World Cup sports season page — groups should be listed chronologically under date headers with no MD labels; kick-off time should appear below each match row - [ ] Once the knockout bracket has matches, confirm the Groups/Bracket toggle appears and both views render correctly - [ ] On the home page, a user with drafted World Cup participants should see upcoming group fixtures in the calendar panel with individual team badges (not a participant count) - [ ] NBA/AFL/NHL pages unaffected — their standings/playoffs/finished toggle still works normally - [ ] \`npm run typecheck\` and \`npm run test:run\` pass Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com> Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/55
2026-05-27 05:43:08 +00:00
const bracketResults = Array.from(entryMap.values());
// Also include group stage matches for the drafted participants.
// Group stage matches live in groupStageMatches, not playoffMatches, so
// the bracket query above misses them entirely.
const groupStageRows = await db
.select({
matchId: schema.groupStageMatches.id,
groupName: schema.tournamentGroups.groupName,
scoringEventName: schema.scoringEvents.name,
sportsSeasonId: schema.scoringEvents.sportsSeasonId,
scheduledAt: schema.groupStageMatches.scheduledAt,
participant1Id: schema.groupStageMatches.participant1Id,
participant2Id: schema.groupStageMatches.participant2Id,
})
.from(schema.groupStageMatches)
.innerJoin(
schema.tournamentGroups,
eq(schema.groupStageMatches.tournamentGroupId, schema.tournamentGroups.id)
)
.innerJoin(
schema.scoringEvents,
eq(schema.tournamentGroups.scoringEventId, schema.scoringEvents.id)
)
.where(
and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
eq(schema.groupStageMatches.isComplete, false),
or(
inArray(schema.groupStageMatches.participant1Id, draftedIds),
inArray(schema.groupStageMatches.participant2Id, draftedIds)
),
isNotNull(schema.groupStageMatches.scheduledAt),
gte(schema.groupStageMatches.scheduledAt, dateFromTimestamp),
lte(schema.groupStageMatches.scheduledAt, dateToTimestamp)
)
)
.orderBy(asc(schema.groupStageMatches.scheduledAt));
if (groupStageRows.length > 0) {
const allGroupParticipantIds = [
...new Set(groupStageRows.flatMap((r) => [r.participant1Id, r.participant2Id])),
];
const groupParticipantRows = await db.query.seasonParticipants.findMany({
where: inArray(schema.seasonParticipants.id, allGroupParticipantIds),
});
const groupParticipantMap = new Map(groupParticipantRows.map((p) => [p.id, p]));
for (const row of groupStageRows) {
if (!row.scheduledAt) continue;
const p1 = groupParticipantMap.get(row.participant1Id);
const p2 = groupParticipantMap.get(row.participant2Id);
const relevantParticipants: Array<{ id: string; name: string }> = [];
if (draftedIds.includes(row.participant1Id) && p1) {
relevantParticipants.push({ id: row.participant1Id, name: p1.name });
}
if (draftedIds.includes(row.participant2Id) && p2) {
relevantParticipants.push({ id: row.participant2Id, name: p2.name });
}
bracketResults.push({
id: `group|${row.matchId}`,
2026-06-16 14:11:51 +00:00
scoringEventId: null,
Fix World Cup group stage display and upcoming events (#55) ## Summary - **Group stage match list**: Removed MD 1/2/3 headings; matches now listed chronologically under date separators (e.g. "Jun 14"). Kick-off time appears below the team names instead of between them. - **Sort order**: \`findMatchesByGroupIds\` / \`findMatchesByEventId\` now order by \`scheduledAt ASC NULLS LAST\` so unscheduled matches always trail scheduled ones. - **Groups/Bracket toggle**: When both group stage and knockout bracket exist, a toggle appears (mirroring the NBA/AFL standings toggle). Sports with both regular-season standings and a group stage get all views available. - **Upcoming events**: \`getUpcomingEventsForDraftedParticipants\` now also queries \`groupStageMatches\`, so World Cup group fixtures appear on the home page calendar sorted by kick-off time with a label like "Group A — France vs Germany". - **\`isAllCompete\` fix**: \`UpcomingEventsCard\` and \`UpcomingCalendarPanel\` now treat \`group_stage_match\` as a bracket-style event, showing team badges instead of "N of your picks". Fixes #53 ## Test plan - [ ] Navigate to a World Cup sports season page — groups should be listed chronologically under date headers with no MD labels; kick-off time should appear below each match row - [ ] Once the knockout bracket has matches, confirm the Groups/Bracket toggle appears and both views render correctly - [ ] On the home page, a user with drafted World Cup participants should see upcoming group fixtures in the calendar panel with individual team badges (not a participant count) - [ ] NBA/AFL/NHL pages unaffected — their standings/playoffs/finished toggle still works normally - [ ] \`npm run typecheck\` and \`npm run test:run\` pass Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com> Reviewed-on: https://forge.brackt.com/chrisp/brackt/pulls/55
2026-05-27 05:43:08 +00:00
name: row.scoringEventName,
eventDate: null,
earliestGameTime: row.scheduledAt.toISOString(),
matchLabel: `Group ${row.groupName}${p1?.name ?? "?"} vs ${p2?.name ?? "?"}`,
eventType: "group_stage_match",
sportsSeasonId: row.sportsSeasonId,
relevantParticipants,
});
}
}
return bracketResults;
2026-03-12 10:12:38 -07:00
}
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
export interface DashboardScoringEvent {
id: string;
name: string;
eventDate: string | null;
/** Resolved date for tab bucketing: eventDate if set, else earliest matched game date. */
displayDate: string | null;
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
eventStartsAt: Date | null;
eventType: string;
isComplete: boolean;
completedAt: Date | null;
sportsSeasonId: string;
sportsSeasonName: string;
sportName: string;
sportSlug: string | null;
}
/**
* Get all scoring events (excluding schedule_event type) for the given dates,
* joined with their sports season and sport info. Used for the admin dashboard
* "Games to Score" widget.
*
* An event is included if EITHER its own eventDate falls on one of the given
* dates, OR any of its playoffMatchGames has a scheduledAt timestamp on one of
* those dates. This ensures bracket events where the admin set dates on
* individual games (rather than the event itself) are still surfaced.
*/
export async function getEventsForDates(
dates: string[],
providedDb?: ReturnType<typeof database>
): Promise<DashboardScoringEvent[]> {
if (dates.length === 0) return [];
const db = providedDb || database();
// Build timestamp bounds covering the full span of the requested dates so we
// can range-check the playoffMatchGames.scheduledAt timestamp column.
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
const sortedDates = [...dates].toSorted();
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
const dateFromTimestamp = new Date(sortedDates[0] + "T00:00:00.000Z");
const dateToTimestamp = new Date(sortedDates[sortedDates.length - 1] + "T23:59:59.999Z");
// Step 1: collect event IDs where the event date OR any game's scheduledAt
// falls within the requested dates. Also capture the matched date so we can
// bucket events that have no eventDate (bracket events) into the right tab.
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
const rows = await db
.select({
id: schema.scoringEvents.id,
eventDate: schema.scoringEvents.eventDate,
gameDate: sql<string | null>`DATE(${schema.playoffMatchGames.scheduledAt} AT TIME ZONE 'UTC')`,
})
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
.from(schema.scoringEvents)
.leftJoin(
schema.playoffMatches,
eq(schema.playoffMatches.scoringEventId, schema.scoringEvents.id)
)
.leftJoin(
schema.playoffMatchGames,
eq(schema.playoffMatchGames.playoffMatchId, schema.playoffMatches.id)
)
.where(
and(
inArray(schema.scoringEvents.eventType, [
"playoff_game",
"major_tournament",
"final_standings",
]),
or(
inArray(schema.scoringEvents.eventDate, dates),
and(
isNotNull(schema.playoffMatchGames.scheduledAt),
gte(schema.playoffMatchGames.scheduledAt, dateFromTimestamp),
lte(schema.playoffMatchGames.scheduledAt, dateToTimestamp)
)
)
)
);
if (rows.length === 0) return [];
// Collect ALL dates each event qualifies for. For bracket events, the
// game's scheduledAt date (gameDate) takes priority over the event-level
// eventDate — the event-level date might be set to the overall round date
// (e.g. "April 5") while an individual game is actually scheduled today.
// Using a Set per event also de-duplicates naturally when multiple matches
// in the same bracket have games on the same day.
const eventDatesMap = new Map<string, Set<string>>();
for (const row of rows) {
if (!eventDatesMap.has(row.id)) {
eventDatesMap.set(row.id, new Set());
}
const dateSet = eventDatesMap.get(row.id);
if (!dateSet) continue;
if (row.eventDate && dates.includes(row.eventDate)) {
dateSet.add(row.eventDate);
}
if (row.gameDate && dates.includes(row.gameDate)) {
dateSet.add(row.gameDate);
}
// Fallback: row passed the WHERE clause so at least one date is relevant;
// if neither mapped to a requested date (shouldn't happen), keep something.
if (dateSet.size === 0) {
const fallback = row.gameDate ?? row.eventDate ?? null;
if (fallback) dateSet.add(fallback);
}
}
const eventIds = [...eventDatesMap.keys()];
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
// Step 2: fetch the matched events with sport season + sport info.
const events = await db.query.scoringEvents.findMany({
where: inArray(schema.scoringEvents.id, eventIds),
orderBy: [
asc(schema.scoringEvents.eventDate),
asc(schema.scoringEvents.eventStartsAt),
asc(schema.scoringEvents.createdAt),
],
with: {
sportsSeason: {
with: {
sport: true,
},
},
},
});
// Return one entry per (event, date) pair so that an event with games on
// both today and tomorrow appears in both tabs of the dashboard widget.
return events.flatMap((e) => {
const matchingDates = [...(eventDatesMap.get(e.id) ?? [])].toSorted();
const base = {
id: e.id,
name: e.name,
eventDate: e.eventDate,
eventStartsAt: e.eventStartsAt,
eventType: e.eventType,
isComplete: e.isComplete,
completedAt: e.completedAt,
sportsSeasonId: e.sportsSeasonId,
sportsSeasonName: e.sportsSeason.name,
sportName: e.sportsSeason.sport.name,
sportSlug: e.sportsSeason.sport.slug,
};
if (matchingDates.length === 0) {
return [{ ...base, displayDate: e.eventDate ?? null }];
}
return matchingDates.map((date) => ({ ...base, displayDate: date }));
});
Add "Games to Score" widget to admin dashboard (#183) * Add "Games to Score" widget to admin dashboard Shows scoring events for today and tomorrow in a tabbed card, with status badges (Pending/Scored), a scored/total progress counter, and direct "Score" / "View" links to each event's results page. Excludes non-scoring schedule_event types so only actionable events surface. - app/models/scoring-event.ts: add getEventsForDates() model function that queries scoringEvents joined with sportsSeasons/sport for a given list of date strings - app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow]) in the loader and render the GamesToScore component below the stats row - app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests covering empty input, shape mapping, multi-date filtering, completed events, and the inArray where conditions https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Fix getEventsForDates to include bracket events by game scheduledAt The previous implementation only matched on scoringEvents.eventDate, which is often null for bracket events where individual game times are set on playoffMatchGames.scheduledAt instead. Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants: 1. selectDistinct event IDs via left joins through playoffMatches → playoffMatchGames, matching where eventDate IN dates OR any game's scheduledAt falls within the date range's timestamp bounds 2. findMany on the matched IDs with sportsSeason + sport relations Updated tests to cover the two-step flow, leftJoin usage, and the scheduledAt timestamp bounds appearing in the where clause. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 * Document dual game date storage in CLAUDE.md scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game dates depending on the event type. Added a dedicated section under Important Patterns explaining when each is used and the two-step selectDistinct + findMany pattern required for correct date queries. https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5 --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
}
/**
* Bulk create scoring events for a sports season.
* Returns created events in order.
*/
export async function bulkCreateScoringEvents(
sportsSeasonId: 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
events: Array<{ name: string; eventDate?: Date; eventStartsAt?: Date; eventType: EventType; isQualifyingEvent?: boolean; tournamentId?: string }>,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
if (events.length === 0) return [];
const rows = events.map((e) => ({
sportsSeasonId,
name: e.name,
eventDate: e.eventDate ? e.eventDate.toISOString().split("T")[0] : undefined,
eventStartsAt: e.eventStartsAt,
eventType: e.eventType,
isQualifyingEvent: e.isQualifyingEvent ?? false,
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
tournamentId: e.tournamentId,
isComplete: false,
}));
return db.insert(schema.scoringEvents).values(rows).returning();
}
export async function getTournamentsBySportsSeason(sportsSeasonId: string) {
const db = database();
const rows = await db.query.scoringEvents.findMany({
where: and(
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
isNotNull(schema.scoringEvents.tournamentId)
),
with: { tournament: true },
});
const seen = new Set<string>();
return rows.filter((r) => {
if (!r.tournamentId || seen.has(r.tournamentId)) return false;
seen.add(r.tournamentId);
return true;
});
}
export async function getSportsSeasonsByTournament(tournamentId: string) {
const db = database();
const rows = await db.query.scoringEvents.findMany({
where: eq(schema.scoringEvents.tournamentId, tournamentId),
with: { sportsSeason: { with: { sport: true } } },
});
const seen = new Set<string>();
return rows.filter((r) => {
if (seen.has(r.sportsSeasonId)) return false;
seen.add(r.sportsSeasonId);
return true;
});
}
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
/**
* Count the distinct sports-season windows linked to a tournament. Cheaper than
* getSportsSeasonsByTournament when only the count is needed (no relations).
*/
export async function countWindowsByTournament(
tournamentId: string,
providedDb?: ReturnType<typeof database>
): Promise<number> {
const db = providedDb || database();
const [row] = await db
.select({
count: sql<number>`count(distinct ${schema.scoringEvents.sportsSeasonId})::int`,
})
.from(schema.scoringEvents)
.where(eq(schema.scoringEvents.tournamentId, tournamentId));
return row?.count ?? 0;
}
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 scoring event for a tournament the single window where the admin
* builds the bracket/stages and scoring happens; its results fan out to siblings.
* Returns the explicitly-flagged primary, falling back to the earliest-created
* linked event so callers (league/sim loaders) always have a structure source
* even before a primary is designated.
*/
export async function getPrimaryEventForTournament(
tournamentId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
const primary = await db.query.scoringEvents.findFirst({
where: and(
eq(schema.scoringEvents.tournamentId, tournamentId),
eq(schema.scoringEvents.isPrimary, true)
),
});
if (primary) return primary;
return db.query.scoringEvents.findFirst({
where: eq(schema.scoringEvents.tournamentId, tournamentId),
orderBy: asc(schema.scoringEvents.createdAt),
});
}
/**
* A tournament-linked, non-primary event is a read-only mirror: its results are
* owned by the shared major's primary window and fan out to it. Direct scoring
* on such an event must be rejected so windows can't diverge. Single source of
* truth for that predicate, shared by the admin route guards and the loaders.
*/
export function isReadOnlySibling(event: {
tournamentId: string | null;
isPrimary: boolean;
}): boolean {
return !!event.tournamentId && !event.isPrimary;
}
/**
* Make `eventId` the single primary window for its tournament set it primary
* and clear the flag on every sibling. Used by the "Make this the primary
* window" admin action and to seed a primary when the first bracket-major event
* is created.
*/
export async function setPrimaryEvent(
eventId: string,
providedDb?: ReturnType<typeof database>
) {
const db = providedDb || database();
const event = await db.query.scoringEvents.findFirst({
where: eq(schema.scoringEvents.id, eventId),
});
if (!event?.tournamentId) {
throw new Error(`Event ${eventId} is not linked to a tournament`);
}
await db
.update(schema.scoringEvents)
.set({ isPrimary: false, updatedAt: new Date() })
.where(eq(schema.scoringEvents.tournamentId, event.tournamentId));
await db
.update(schema.scoringEvents)
.set({ isPrimary: true, updatedAt: new Date() })
.where(eq(schema.scoringEvents.id, eventId));
}
/**
* Designate `eventId` as the tournament's primary window only if none is set
* yet. Idempotent: returns the existing primary's id when one already exists, so
* creating/linking additional windows never steals primary from the first.
*/
export async function ensurePrimaryEvent(
tournamentId: string,
eventId: string,
providedDb?: ReturnType<typeof database>
): Promise<string> {
const db = providedDb || database();
const existing = await db.query.scoringEvents.findFirst({
where: and(
eq(schema.scoringEvents.tournamentId, tournamentId),
eq(schema.scoringEvents.isPrimary, true)
),
});
if (existing) return existing.id;
await db
.update(schema.scoringEvents)
.set({ isPrimary: true, updatedAt: new Date() })
.where(eq(schema.scoringEvents.id, eventId));
return eventId;
}