2025-10-31 22:13:12 -07:00
|
|
|
import type { Route } from "./+types/admin.sports-seasons.$id.events.$eventId";
|
2026-03-21 13:41:39 -07:00
|
|
|
import { logger } from "~/lib/logger";
|
2025-10-31 22:13:12 -07:00
|
|
|
import { findSportsSeasonById } from "~/models/sports-season";
|
Canonical tournament layer: schema + backfill (1/2) (#365)
* refactor(schema): rename per-window tables to season_* prefix
Renames participants, participant_expected_values, participant_qualifying_totals,
participant_results, participant_surface_elos to season_* prefixed names.
Renames event_results.participant_id to season_participant_id.
Phase 1a of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor: rename participant.ts model file to season-participant.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(models): update model layer to use renamed schema exports
Updated all model files to use the renamed schema exports from Task 1:
- participants → seasonParticipants
- participantExpectedValues → seasonParticipantExpectedValues
- participantQualifyingTotals → seasonParticipantQualifyingTotals
- participantResults → seasonParticipantResults
- participantSurfaceElos → seasonParticipantSurfaceElos
- eventResults.participantId → eventResults.seasonParticipantId
- db.query relation accessors updated
- Relation field .participant → .seasonParticipant where applicable
- Import paths updated: ./participant → ./season-participant
Files updated (14 model files + 3 test files):
- draft-pick.ts
- draft-utils.ts
- event-result.ts
- group-stage-match.ts
- participant-result.ts
- qualifying-points.ts
- scoring-calculator.ts
- scoring-event.ts
- sports-season.ts
- surface-elo.ts
- team-score-events.ts
- cs2-major-stage.ts
- golf-skills.ts
- participant-expected-value.ts
- __tests__/sports-season.clone.test.ts
- __tests__/auto-pick.test.ts
- __tests__/executeAutoPick.timer.test.ts
Typecheck errors decreased: 779 → 499 (280 fewer)
All model file errors related to renamed schemas resolved.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(routes): update route layer to use renamed schema exports
- Update model import from ~/models/participant to ~/models/season-participant
- Rename schema.participants to schema.seasonParticipants
- Rename schema.participantResults to schema.seasonParticipantResults
- Rename db.query.participants to db.query.seasonParticipants
- Update 9 route files and 1 test file
Affected files:
- admin.sports-seasons.$id.events.$eventId.bracket.server.ts
- admin.sports-seasons.$id.participants.tsx
- api/draft.force-manual-pick.ts
- api/draft.make-pick.ts
- api/draft.replace-pick.ts
- api/seasons.$seasonId.draft.ts
- leagues/$leagueId.draft-board.$seasonId.tsx
- leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts
- admin/__tests__/sports-seasons-participants.test.ts
Error count reduced from 499 to 453 (46 errors fixed).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(routes): update route files for schema rename
Update route imports from ~/models/participant to ~/models/season-participant
and fix references to .participant/.participantId on event results to use
.seasonParticipant/.seasonParticipantId after schema rename.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(services): update simulators and services for renamed schema
Update all simulators, services, and server files to use renamed schema tables:
- participants → seasonParticipants
- participantExpectedValues → seasonParticipantExpectedValues
- participantResults → seasonParticipantResults
- eventResults.participantId → eventResults.seasonParticipantId
Files updated:
- 20 sport simulators (NBA, NHL, NFL, MLB, etc.)
- probability-updater.ts
- standings-sync/index.ts
- sports-data-sync.server.ts
- server/socket.ts
Typecheck errors reduced from 365 to 0.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* migration: rename per-window tables to season_* prefix
* fix(tests): update mock query keys after participants table rename
Change mock db.query.participants to db.query.seasonParticipants in test
files to match the schema rename from commit 66145a9. This fixes
"Cannot read properties of undefined (reading 'findFirst'/'findMany')"
errors that occurred when production code queries db.query.seasonParticipants
but test mocks only defined the old participants key.
Files updated:
- app/services/simulations/__tests__/world-cup-simulator.test.ts
- app/routes/api/__tests__/draft.force-manual-pick.test.ts
- app/routes/api/__tests__/draft.force-manual-pick.timer-mode.test.ts
- app/routes/api/__tests__/draft.make-pick.timer-mode.test.ts
- server/__tests__/timer-autodraft.test.ts
- app/models/__tests__/team-score-events.test.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(tests): update remaining mock paths and keys after schema rename
* fix(tests): final two mock stragglers after schema rename
- draft-pick.test.ts: assertion on db.query.participantQualifyingTotals
- process-match-result.test.ts: mock key participants → seasonParticipants
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* chore: add post-phase1a baseline capture (temp, for diff verification)
* chore: capture pre-migration baselines
* chore: remove post-phase1a capture helper after verification
* schema: add canonical tournament & participant tables
Adds tournaments, participants (canonical), tournament_results, and
participant_surface_elos (canonical). Adds nullable tournament_id to
scoring_events and nullable participant_id to season_participants.
Phase 1b of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(models): add canonical tournament, participant, result, surface-elo models
Adds CRUD modules for the canonical tables created in commit 775b905.
Each module mirrors existing app/models conventions (database() from
~/database/context, schema from ~/database/schema, mock-based tests).
Key implementation notes:
- participant.ts exports use "Canonical" prefix (CanonicalParticipant,
createCanonicalParticipant, etc.) to avoid collision with existing
season-participant.ts exports
- All four models include comprehensive unit tests following the
audit-log.test.ts pattern
- Tests use mocked db responses (no real database access)
- Upsert functions use onConflictDoUpdate for appropriate unique constraints
Part of Phase 1b of canonical tournament layer migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* migration: create canonical tables, add nullable FKs
* scripts: add extractTournamentIdentity helper for backfill
Pure function that derives canonical (name, year) identity from a
scoring_events row, stripping trailing 4-digit years from the name or
falling back to eventDate. Used by the Phase 2 backfill to group
per-window events into canonical tournaments.
* scripts: add backfill orchestrator for canonical layer
Populates canonical tournaments, participants, tournament_results, and
participant_surface_elos from per-window data for qualifying-points
sports. Skips already-linked rows, is idempotent, and supports dry-run
mode.
Critical invariants enforced by the implementation:
- qualifying_points_awarded is never copied to tournament_results
- season_participant_qualifying_totals is never touched
- conflicting surface-Elo values between windows raise a loud error
(recorded in report.errors) rather than overwriting
* scripts: add backfill CLI with dry-run default
Wires backfill-canonical-layer.ts to a CLI entry point exposed as
`npm run backfill:canonical`. Defaults to --dry-run; requires --apply
to actually write. Supports --sport=<uuid> to limit to a single sport.
Exits 2 if the backfill reports errors (e.g., surface-Elo conflicts).
* fix(backfill-cli): wrap runBackfill in DatabaseContext.run
The orchestrator uses database() from ~/database/context, which requires
AsyncLocalStorage to be populated. Wrap the CLI invocation with
DatabaseContext.run(db, ...) using server/db's cached connection pool.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(backfill-cli): exit 0 on success so pg pool doesn't block
The cached postgres connection pool keeps the Node event loop open after
main() returns. Explicit process.exit(0) on success mirrors the pattern
in scripts/capture-baseline.ts.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Chris Parsons <chrisp@extrahop.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:13:18 -07:00
|
|
|
import { findParticipantsBySportsSeasonId, createParticipant } from "~/models/season-participant";
|
2025-10-31 22:13:12 -07:00
|
|
|
import {
|
|
|
|
|
getScoringEventById,
|
|
|
|
|
completeScoringEvent,
|
2026-03-07 21:59:29 -08:00
|
|
|
updateScoringEvent,
|
2025-10-31 22:13:12 -07:00
|
|
|
} from "~/models/scoring-event";
|
|
|
|
|
import {
|
|
|
|
|
getEventResults,
|
|
|
|
|
createEventResult,
|
2026-04-12 17:52:22 -04:00
|
|
|
createEventResultsBulk,
|
2025-10-31 22:13:12 -07:00
|
|
|
updateEventResult,
|
|
|
|
|
deleteEventResult,
|
|
|
|
|
type CreateEventResultData,
|
|
|
|
|
type UpdateEventResultData,
|
|
|
|
|
} from "~/models/event-result";
|
2026-04-12 17:52:22 -04:00
|
|
|
import { filterNewResults, findParticipantsWithoutResults } from "./admin.sports-seasons.$id.events.$eventId.helpers";
|
2025-11-04 22:09:44 -08:00
|
|
|
import { findParticipantResultsBySportsSeasonId } from "~/models/participant-result";
|
2025-11-08 22:35:07 -08:00
|
|
|
import {
|
|
|
|
|
upsertParticipantSeasonResult,
|
|
|
|
|
getSeasonResults,
|
|
|
|
|
} from "~/models/participant-season-result";
|
2025-11-11 10:08:25 -08:00
|
|
|
import { processSeasonStandings, processQualifyingEvent } from "~/models/scoring-calculator";
|
|
|
|
|
import { getQPStandings, getQPConfig } from "~/models/qualifying-points";
|
|
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
|
|
|
|
import { eq } from "drizzle-orm";
|
2025-10-31 22:13:12 -07:00
|
|
|
|
|
|
|
|
export async function loader({ params }: Route.LoaderArgs) {
|
|
|
|
|
const sportsSeason = await findSportsSeasonById(params.id);
|
|
|
|
|
|
|
|
|
|
if (!sportsSeason) {
|
|
|
|
|
throw new Response("Sports season not found", { status: 404 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const event = await getScoringEventById(params.eventId);
|
|
|
|
|
|
|
|
|
|
if (!event) {
|
|
|
|
|
throw new Response("Event not found", { status: 404 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const participants = await findParticipantsBySportsSeasonId(params.id);
|
|
|
|
|
const results = await getEventResults(params.eventId);
|
2025-11-04 22:09:44 -08:00
|
|
|
const participantResults = await findParticipantResultsBySportsSeasonId(params.id);
|
2025-10-31 22:13:12 -07:00
|
|
|
|
2025-11-08 22:35:07 -08:00
|
|
|
// For final_standings events, also get season results
|
|
|
|
|
let seasonResults = null;
|
|
|
|
|
if (event.eventType === "final_standings") {
|
|
|
|
|
seasonResults = await getSeasonResults(params.id);
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-11 10:08:25 -08:00
|
|
|
// For qualifying events, get QP config
|
|
|
|
|
let qpConfig = null;
|
|
|
|
|
if (event.isQualifyingEvent) {
|
|
|
|
|
qpConfig = await getQPConfig(params.id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For qualifying sports seasons, get QP standings
|
|
|
|
|
let qpStandings = null;
|
|
|
|
|
if (sportsSeason.scoringPattern === "qualifying_points") {
|
|
|
|
|
qpStandings = await getQPStandings(params.id);
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
return {
|
|
|
|
|
sportsSeason: sportsSeason as typeof sportsSeason & {
|
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 13:40:05 -07:00
|
|
|
sport: { id: string; name: string; type: string; slug: string; simulatorType: string | null };
|
2025-10-31 22:13:12 -07:00
|
|
|
},
|
|
|
|
|
event,
|
|
|
|
|
participants,
|
|
|
|
|
results,
|
2025-11-04 22:09:44 -08:00
|
|
|
participantResults,
|
2025-11-08 22:35:07 -08:00
|
|
|
seasonResults,
|
2025-11-11 10:08:25 -08:00
|
|
|
qpConfig,
|
|
|
|
|
qpStandings,
|
2025-10-31 22:13:12 -07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function action({ request, params }: Route.ActionArgs) {
|
|
|
|
|
const formData = await request.formData();
|
|
|
|
|
const intent = formData.get("intent");
|
|
|
|
|
|
2025-11-11 10:08:25 -08:00
|
|
|
if (intent === "mark-qualifying") {
|
|
|
|
|
try {
|
|
|
|
|
const event = await getScoringEventById(params.eventId);
|
|
|
|
|
if (!event) {
|
|
|
|
|
return { error: "Event not found" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update the event to mark it as a qualifying event
|
|
|
|
|
const db = database();
|
|
|
|
|
await db.update(schema.scoringEvents)
|
|
|
|
|
.set({ isQualifyingEvent: true })
|
|
|
|
|
.where(eq(schema.scoringEvents.id, params.eventId));
|
|
|
|
|
|
|
|
|
|
return { success: "Event marked as qualifying event!" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error marking event as qualifying:", error);
|
2025-11-11 10:08:25 -08:00
|
|
|
return { error: "Failed to mark event as qualifying" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "process-qp") {
|
|
|
|
|
try {
|
|
|
|
|
await processQualifyingEvent(params.eventId);
|
|
|
|
|
return { success: "Qualifying points processed and awarded!" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error processing qualifying points:", error);
|
2025-11-11 10:08:25 -08:00
|
|
|
return { error: error instanceof Error ? error.message : "Failed to process qualifying points" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
if (intent === "complete") {
|
|
|
|
|
try {
|
2025-11-08 22:35:07 -08:00
|
|
|
const event = await getScoringEventById(params.eventId);
|
|
|
|
|
if (!event) {
|
|
|
|
|
return { error: "Event not found" };
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
await completeScoringEvent(params.eventId);
|
2025-11-08 22:35:07 -08:00
|
|
|
|
|
|
|
|
// If this is a final_standings event, process season standings
|
|
|
|
|
if (event.eventType === "final_standings") {
|
|
|
|
|
await processSeasonStandings(params.id);
|
|
|
|
|
return { success: "Event completed and fantasy placements assigned to top 8!" };
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-12 17:52:22 -04:00
|
|
|
// If this is a qualifying event, process qualifying points then fill 0-QP rows
|
2025-11-11 10:08:25 -08:00
|
|
|
if (event.isQualifyingEvent) {
|
|
|
|
|
await processQualifyingEvent(params.eventId);
|
2026-04-12 17:52:22 -04:00
|
|
|
|
|
|
|
|
// Write 0-QP rows for all season participants who have no result for this event.
|
|
|
|
|
// This marks them as "competed, earned nothing" so simulations skip this event.
|
|
|
|
|
const allParticipants = await findParticipantsBySportsSeasonId(params.id);
|
|
|
|
|
const existingResults = await getEventResults(params.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
|
|
|
const existingIds = new Set(existingResults.map((r) => r.seasonParticipantId));
|
2026-04-12 17:52:22 -04:00
|
|
|
const missingIds = findParticipantsWithoutResults(
|
|
|
|
|
allParticipants.map((p) => p.id),
|
|
|
|
|
existingIds
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (missingIds.length > 0) {
|
|
|
|
|
await createEventResultsBulk(
|
|
|
|
|
missingIds.map((participantId) => ({
|
|
|
|
|
scoringEventId: params.eventId,
|
|
|
|
|
participantId,
|
|
|
|
|
qualifyingPointsAwarded: 0,
|
|
|
|
|
}))
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-11 10:08:25 -08:00
|
|
|
return { success: "Event completed and qualifying points awarded!" };
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
return { success: "Event marked as completed" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error completing event:", error);
|
2025-10-31 22:13:12 -07:00
|
|
|
return { error: "Failed to complete event" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
if (intent === "uncomplete") {
|
|
|
|
|
try {
|
|
|
|
|
await updateScoringEvent(params.eventId, { isComplete: false });
|
|
|
|
|
return { success: "Event marked as not updated" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error uncompleting event:", error);
|
2026-03-07 21:59:29 -08:00
|
|
|
return { error: "Failed to update event" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "update-event") {
|
|
|
|
|
const name = formData.get("name");
|
2026-03-15 10:22:42 -07:00
|
|
|
const eventStartsAtRaw = formData.get("eventStartsAt");
|
2026-03-07 21:59:29 -08:00
|
|
|
|
|
|
|
|
if (typeof name !== "string" || !name.trim()) {
|
|
|
|
|
return { error: "Event name is required" };
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-15 10:22:42 -07:00
|
|
|
// eventStartsAt is a UTC ISO string from the client; empty string means "clear it"
|
|
|
|
|
const eventStartsAt: Date | null | undefined =
|
|
|
|
|
typeof eventStartsAtRaw === "string"
|
|
|
|
|
? eventStartsAtRaw
|
|
|
|
|
? new Date(eventStartsAtRaw)
|
|
|
|
|
: null
|
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
|
|
// Derive eventDate from eventStartsAt; null when cleared
|
|
|
|
|
const eventDate: Date | null | undefined =
|
|
|
|
|
eventStartsAt !== undefined
|
|
|
|
|
? eventStartsAt
|
|
|
|
|
? new Date(eventStartsAt.toISOString().split("T")[0])
|
|
|
|
|
: null
|
|
|
|
|
: undefined;
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
try {
|
|
|
|
|
await updateScoringEvent(params.eventId, {
|
|
|
|
|
name: name.trim(),
|
2026-03-15 10:22:42 -07:00
|
|
|
eventDate,
|
|
|
|
|
eventStartsAt,
|
2026-03-07 21:59:29 -08:00
|
|
|
});
|
|
|
|
|
return { success: "Event updated" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error updating event:", error);
|
2026-03-07 21:59:29 -08:00
|
|
|
return { error: "Failed to update event" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
if (intent === "add-result") {
|
|
|
|
|
const participantId = formData.get("participantId");
|
|
|
|
|
const placement = formData.get("placement");
|
|
|
|
|
|
|
|
|
|
if (typeof participantId !== "string" || !participantId) {
|
|
|
|
|
return { error: "Participant is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (typeof placement !== "string" || !placement) {
|
|
|
|
|
return { error: "Placement is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const placementNum = parseInt(placement, 10);
|
|
|
|
|
if (isNaN(placementNum) || placementNum < 1 || placementNum > 100) {
|
|
|
|
|
return { error: "Placement must be between 1 and 100" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const resultData: CreateEventResultData = {
|
|
|
|
|
scoringEventId: params.eventId,
|
|
|
|
|
participantId,
|
|
|
|
|
placement: placementNum,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await createEventResult(resultData);
|
|
|
|
|
return { success: "Result added successfully" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error adding result:", error);
|
2025-10-31 22:13:12 -07:00
|
|
|
return { error: "Failed to add result" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "update-result") {
|
|
|
|
|
const resultId = formData.get("resultId");
|
|
|
|
|
const placement = formData.get("placement");
|
|
|
|
|
|
|
|
|
|
if (typeof resultId !== "string" || !resultId) {
|
|
|
|
|
return { error: "Result ID is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (typeof placement !== "string" || !placement) {
|
|
|
|
|
return { error: "Placement is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const placementNum = parseInt(placement, 10);
|
|
|
|
|
if (isNaN(placementNum) || placementNum < 1 || placementNum > 100) {
|
|
|
|
|
return { error: "Placement must be between 1 and 100" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const updateData: UpdateEventResultData = {
|
|
|
|
|
placement: placementNum,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await updateEventResult(resultId, updateData);
|
|
|
|
|
return { success: "Result updated successfully" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error updating result:", error);
|
2025-10-31 22:13:12 -07:00
|
|
|
return { error: "Failed to update result" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "delete-result") {
|
|
|
|
|
const resultId = formData.get("resultId");
|
|
|
|
|
|
|
|
|
|
if (typeof resultId !== "string" || !resultId) {
|
|
|
|
|
return { error: "Result ID is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await deleteEventResult(resultId);
|
|
|
|
|
return { success: "Result deleted successfully" };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error deleting result:", error);
|
2025-10-31 22:13:12 -07:00
|
|
|
return { error: "Failed to delete result" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-08 22:35:07 -08:00
|
|
|
if (intent === "update-standings") {
|
|
|
|
|
// Bulk update season standings for final_standings events
|
|
|
|
|
try {
|
|
|
|
|
// Parse all form fields and collect participants with points
|
|
|
|
|
const participantPoints: Array<{ participantId: string; points: number }> = [];
|
|
|
|
|
|
|
|
|
|
for (const [key, value] of formData.entries()) {
|
|
|
|
|
if (key.startsWith("points-")) {
|
|
|
|
|
const participantId = key.replace("points-", "");
|
|
|
|
|
const points = value ? parseFloat(value as string) : 0;
|
|
|
|
|
|
|
|
|
|
if (points > 0) {
|
|
|
|
|
participantPoints.push({ participantId, points });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Sort by points descending to determine positions
|
|
|
|
|
participantPoints.sort((a, b) => b.points - a.points);
|
|
|
|
|
|
|
|
|
|
// Assign positions based on sorted order and update
|
|
|
|
|
for (let i = 0; i < participantPoints.length; i++) {
|
|
|
|
|
const { participantId, points } = participantPoints[i];
|
|
|
|
|
const position = i + 1; // Position is 1-based
|
|
|
|
|
|
|
|
|
|
await upsertParticipantSeasonResult(
|
|
|
|
|
{
|
|
|
|
|
participantId,
|
|
|
|
|
sportsSeasonId: params.id,
|
|
|
|
|
currentPoints: points,
|
|
|
|
|
currentPosition: position,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Also update participants with 0 or no points (they don't have a position)
|
|
|
|
|
for (const [key, value] of formData.entries()) {
|
|
|
|
|
if (key.startsWith("points-")) {
|
|
|
|
|
const participantId = key.replace("points-", "");
|
|
|
|
|
const points = value ? parseFloat(value as string) : 0;
|
|
|
|
|
|
|
|
|
|
if (points === 0) {
|
|
|
|
|
await upsertParticipantSeasonResult(
|
|
|
|
|
{
|
|
|
|
|
participantId,
|
|
|
|
|
sportsSeasonId: params.id,
|
|
|
|
|
currentPoints: 0,
|
|
|
|
|
currentPosition: undefined,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { success: `Updated standings for ${participantPoints.length} participants (positions auto-calculated from points)` };
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Error updating season standings:", error);
|
2025-11-08 22:35:07 -08:00
|
|
|
return { error: "Failed to update season standings" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-12 17:52:22 -04:00
|
|
|
if (intent === "batch-add-results") {
|
|
|
|
|
const resultsJson = formData.get("results");
|
|
|
|
|
if (typeof resultsJson !== "string" || !resultsJson) {
|
|
|
|
|
return { error: "Results data is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let incoming: { participantId: string; placement: number }[];
|
|
|
|
|
try {
|
|
|
|
|
incoming = JSON.parse(resultsJson);
|
|
|
|
|
} catch {
|
|
|
|
|
return { error: "Invalid results format" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!Array.isArray(incoming) || incoming.length === 0) {
|
|
|
|
|
return { error: "No results provided" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate that all participant IDs belong to this sports season
|
|
|
|
|
const allSeasonParticipants = await findParticipantsBySportsSeasonId(params.id);
|
|
|
|
|
const validParticipantIds = new Set(allSeasonParticipants.map((p) => p.id));
|
|
|
|
|
const invalidEntries = incoming.filter((r) => !validParticipantIds.has(r.participantId));
|
|
|
|
|
if (invalidEntries.length > 0) {
|
|
|
|
|
return { error: "Some participant IDs do not belong to this sports season" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const existingResults = await getEventResults(params.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
|
|
|
const existingIds = new Set(existingResults.map((r) => r.seasonParticipantId));
|
2026-04-12 17:52:22 -04:00
|
|
|
const newResults = filterNewResults(incoming, existingIds);
|
|
|
|
|
|
|
|
|
|
if (newResults.length > 0) {
|
|
|
|
|
await createEventResultsBulk(
|
|
|
|
|
newResults.map((r) => ({
|
|
|
|
|
scoringEventId: params.eventId,
|
|
|
|
|
participantId: r.participantId,
|
|
|
|
|
placement: r.placement,
|
|
|
|
|
}))
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
success: `${newResults.length} result${newResults.length === 1 ? "" : "s"} saved${incoming.length - newResults.length > 0 ? ` (${incoming.length - newResults.length} duplicate${incoming.length - newResults.length === 1 ? "" : "s"} skipped)` : ""}.`,
|
|
|
|
|
};
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logger.error("Error saving batch results:", error);
|
|
|
|
|
return { error: "Failed to save results" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "create-participant") {
|
|
|
|
|
const name = formData.get("name");
|
|
|
|
|
|
|
|
|
|
if (typeof name !== "string" || !name.trim()) {
|
|
|
|
|
return { error: "Participant name is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const participant = await createParticipant({
|
|
|
|
|
name: name.trim(),
|
|
|
|
|
sportsSeasonId: params.id,
|
|
|
|
|
});
|
|
|
|
|
return {
|
|
|
|
|
success: `Participant "${participant.name}" created.`,
|
|
|
|
|
newParticipant: { id: participant.id, name: participant.name },
|
|
|
|
|
};
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logger.error("Error creating participant:", error);
|
|
|
|
|
if (error instanceof Error && error.message.includes("participants_sports_season_name_unique")) {
|
|
|
|
|
return { error: `A participant named "${name.trim()}" already exists in this sports season.` };
|
|
|
|
|
}
|
|
|
|
|
return { error: "Failed to create participant" };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-31 22:13:12 -07:00
|
|
|
return { error: "Invalid action" };
|
|
|
|
|
}
|