2025-10-28 23:50:50 -07:00
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
2026-03-25 20:46:54 -07:00
|
|
|
import { eq, and, desc, asc, gte, lte, or, inArray, isNotNull, sql } from "drizzle-orm";
|
2026-03-15 21:52:47 -07:00
|
|
|
import type { BracketRegion } from "~/lib/bracket-templates";
|
2026-03-10 21:47:47 -07:00
|
|
|
import { recalculateAffectedLeagues } from "./scoring-calculator";
|
2026-05-17 21:58:53 -07:00
|
|
|
import { hasProcessedQualifyingPlacement, recalculateParticipantQP } from "./qualifying-points";
|
2026-06-16 22:11:01 +00:00
|
|
|
import { findParticipantNamesByIds } from "./season-participant";
|
2026-07-02 05:17:37 +00:00
|
|
|
import { deleteTournament } from "./tournament";
|
2026-07-01 22:36:25 +00:00
|
|
|
import type { EventType } from "./scoring-event-types";
|
|
|
|
|
export { type EventType, getEventTypeLabel } from "./scoring-event-types";
|
2025-10-28 23:50:50 -07:00
|
|
|
|
|
|
|
|
export interface CreateScoringEventData {
|
|
|
|
|
sportsSeasonId: string;
|
|
|
|
|
name: string;
|
|
|
|
|
eventDate?: Date;
|
2026-03-15 10:22:42 -07:00
|
|
|
eventStartsAt?: Date;
|
2025-10-28 23:50:50 -07:00
|
|
|
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;
|
2025-11-03 13:16:37 -08:00
|
|
|
// Template system fields (Phase 2.6)
|
|
|
|
|
bracketTemplateId?: string;
|
|
|
|
|
scoringStartsAtRound?: string;
|
2025-10-28 23:50:50 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface UpdateScoringEventData {
|
|
|
|
|
name?: string;
|
2026-03-15 10:22:42 -07:00
|
|
|
eventDate?: Date | null;
|
|
|
|
|
eventStartsAt?: Date | null;
|
2025-10-28 23:50:50 -07:00
|
|
|
isComplete?: boolean;
|
|
|
|
|
completedAt?: Date;
|
2025-11-03 13:16:37 -08:00
|
|
|
bracketTemplateId?: string;
|
|
|
|
|
scoringStartsAtRound?: string;
|
2026-03-15 21:52:47 -07:00
|
|
|
/** 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;
|
2025-10-28 23:50:50 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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,
|
2026-03-15 10:22:42 -07:00
|
|
|
eventStartsAt: data.eventStartsAt,
|
2025-10-28 23:50:50 -07:00
|
|
|
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,
|
2025-11-03 13:16:37 -08:00
|
|
|
bracketTemplateId: data.bracketTemplateId,
|
|
|
|
|
scoringStartsAtRound: data.scoringStartsAtRound,
|
2025-10-28 23:50:50 -07:00
|
|
|
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),
|
2026-03-15 10:22:42 -07:00
|
|
|
orderBy: [desc(schema.scoringEvents.eventDate), desc(schema.scoringEvents.eventStartsAt), desc(schema.scoringEvents.createdAt)],
|
2025-10-28 23:50:50 -07:00
|
|
|
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,
|
2025-10-28 23:50:50 -07:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Update a scoring event
|
|
|
|
|
*/
|
|
|
|
|
export async function updateScoringEvent(
|
|
|
|
|
eventId: string,
|
|
|
|
|
data: UpdateScoringEventData,
|
|
|
|
|
providedDb?: ReturnType<typeof database>
|
|
|
|
|
) {
|
|
|
|
|
const db = providedDb || database();
|
|
|
|
|
|
2026-03-21 09:44:05 -07:00
|
|
|
const updateData: Partial<typeof schema.scoringEvents.$inferInsert> = { updatedAt: new Date() };
|
2025-10-28 23:50:50 -07:00
|
|
|
|
|
|
|
|
if (data.name !== undefined) updateData.name = data.name;
|
|
|
|
|
if (data.eventDate !== undefined) {
|
2026-03-15 10:22:42 -07:00
|
|
|
updateData.eventDate = data.eventDate ? data.eventDate.toISOString().split('T')[0] : null;
|
2025-10-28 23:50:50 -07:00
|
|
|
}
|
2026-03-15 10:22:42 -07:00
|
|
|
if (data.eventStartsAt !== undefined) updateData.eventStartsAt = data.eventStartsAt;
|
2025-10-28 23:50:50 -07:00
|
|
|
if (data.isComplete !== undefined) updateData.isComplete = data.isComplete;
|
|
|
|
|
if (data.completedAt !== undefined) updateData.completedAt = data.completedAt;
|
2025-11-03 13:16:37 -08:00
|
|
|
if (data.bracketTemplateId !== undefined) updateData.bracketTemplateId = data.bracketTemplateId;
|
|
|
|
|
if (data.scoringStartsAtRound !== undefined) updateData.scoringStartsAtRound = data.scoringStartsAtRound;
|
2026-03-15 21:52:47 -07:00
|
|
|
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;
|
2025-10-28 23:50:50 -07:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-03-10 21:47:47 -07:00
|
|
|
* 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.
|
2025-10-28 23:50:50 -07:00
|
|
|
*/
|
2026-07-02 05:17:37 +00:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-28 23:50:50 -07:00
|
|
|
export async function deleteScoringEvent(
|
|
|
|
|
eventId: string,
|
2026-07-02 05:17:37 +00:00
|
|
|
providedDb?: ReturnType<typeof database>,
|
|
|
|
|
opts?: DeleteScoringEventOptions
|
|
|
|
|
): Promise<DeleteScoringEventResult> {
|
2025-10-28 23:50:50 -07:00
|
|
|
const db = providedDb || database();
|
|
|
|
|
|
2026-03-10 21:47:47 -07:00
|
|
|
const event = await db.query.scoringEvents.findFirst({
|
|
|
|
|
where: eq(schema.scoringEvents.id, eventId),
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-02 05:17:37 +00:00
|
|
|
if (!event) {
|
|
|
|
|
return {
|
|
|
|
|
tournamentId: null,
|
|
|
|
|
remainingWindows: 0,
|
|
|
|
|
promotedPrimaryId: null,
|
|
|
|
|
deletedTournament: false,
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-03-10 21:47:47 -07:00
|
|
|
|
|
|
|
|
// 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[] = [];
|
|
|
|
|
let wasQPProcessed = false;
|
|
|
|
|
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);
|
2026-05-17 21:58:53 -07:00
|
|
|
wasQPProcessed = hasProcessedQualifyingPlacement(results);
|
2026-03-10 21:47:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await db.transaction(async (tx) => {
|
2026-06-15 22:05:25 +00:00
|
|
|
if (event.eventType === "playoff_game" || event.eventType === "major_tournament") {
|
2026-03-10 21:47:47 -07:00
|
|
|
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));
|
2026-03-10 21:47:47 -07:00
|
|
|
}
|
|
|
|
|
// Cascades: playoffMatches, eventResults, tournamentGroups/Members
|
|
|
|
|
await tx.delete(schema.scoringEvents).where(eq(schema.scoringEvents.id, eventId));
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-15 22:05:25 +00:00
|
|
|
if (event.eventType === "playoff_game" || event.eventType === "major_tournament") {
|
2026-03-10 21:47:47 -07:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Decrement majorsCompleted if this event had already been processed
|
|
|
|
|
if (wasQPProcessed) {
|
|
|
|
|
const sportsSeason = await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasons.id, event.sportsSeasonId),
|
|
|
|
|
});
|
|
|
|
|
if (sportsSeason && (sportsSeason.majorsCompleted ?? 0) > 0) {
|
|
|
|
|
await db
|
|
|
|
|
.update(schema.sportsSeasons)
|
|
|
|
|
.set({ majorsCompleted: (sportsSeason.majorsCompleted ?? 1) - 1, updatedAt: new Date() })
|
|
|
|
|
.where(eq(schema.sportsSeasons.id, event.sportsSeasonId));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await recalculateAffectedLeagues(event.sportsSeasonId, db);
|
|
|
|
|
}
|
2026-07-02 05:17:37 +00:00
|
|
|
|
|
|
|
|
// 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 (or no sibling is
|
|
|
|
|
// flagged primary anymore), promote the earliest remaining window so the
|
|
|
|
|
// shared major stays scorable and fan-out stays deterministic.
|
|
|
|
|
const hasPrimary = remaining.some((e) => e.isPrimary);
|
|
|
|
|
if (event.isPrimary || !hasPrimary) {
|
|
|
|
|
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,
|
|
|
|
|
};
|
2025-10-28 23:50:50 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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;
|
|
|
|
|
}
|
2026-03-07 21:59:29 -08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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.
|
2026-03-07 21:59:29 -08:00
|
|
|
*/
|
|
|
|
|
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({
|
2026-03-07 21:59:29 -08:00
|
|
|
where: and(
|
|
|
|
|
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
|
|
|
|
|
eq(schema.scoringEvents.isComplete, false)
|
|
|
|
|
),
|
2026-03-15 10:22:42 -07:00
|
|
|
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-03-07 21:59:29 -08:00
|
|
|
});
|
2026-06-16 14:11:51 +00:00
|
|
|
|
|
|
|
|
if (events.length === 0) return [];
|
|
|
|
|
|
2026-06-17 19:46:58 +00:00
|
|
|
// 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();
|
2026-06-17 19:46:58 +00:00
|
|
|
|
|
|
|
|
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
|
|
|
)
|
2026-06-17 19:46:58 +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>();
|
2026-06-17 19:46:58 +00:00
|
|
|
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;
|
|
|
|
|
};
|
|
|
|
|
|
2026-06-17 19:46:58 +00:00
|
|
|
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,
|
|
|
|
|
}));
|
2026-03-07 21:59:29 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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;
|
2026-06-15 22:05:25 +00:00
|
|
|
/** 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 }>,
|
2026-03-27 00:49:16 -07:00
|
|
|
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,
|
2026-04-16 14:19:59 -07:00
|
|
|
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),
|
2026-03-31 10:08:25 -07:00
|
|
|
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
|
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 =
|
2026-04-16 14:19:59 -07:00
|
|
|
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
|
|
|
}
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
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,
|
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;
|
2026-03-25 20:46:54 -07:00
|
|
|
/** 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.
|
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");
|
|
|
|
|
|
2026-03-25 20:46:54 -07:00
|
|
|
// 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
|
2026-03-25 20:46:54 -07:00
|
|
|
.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 [];
|
|
|
|
|
|
2026-04-01 13:39:03 -07:00
|
|
|
// 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>>();
|
2026-03-25 20:46:54 -07:00
|
|
|
for (const row of rows) {
|
2026-04-01 13:39:03 -07:00
|
|
|
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);
|
2026-03-25 20:46:54 -07:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-01 13:39:03 -07:00
|
|
|
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,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-01 13:39:03 -07:00
|
|
|
// 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
|
|
|
}
|
|
|
|
|
|
2026-03-07 21:59:29 -08: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 }>,
|
2026-03-07 21:59:29 -08:00
|
|
|
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,
|
2026-03-15 10:22:42 -07:00
|
|
|
eventStartsAt: e.eventStartsAt,
|
2026-03-07 21:59:29 -08:00
|
|
|
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,
|
2026-03-07 21:59:29 -08:00
|
|
|
isComplete: false,
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
return db.insert(schema.scoringEvents).values(rows).returning();
|
|
|
|
|
}
|
2026-05-02 22:19:59 -07:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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;
|
|
|
|
|
}
|