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 commit66145a9. 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 commit775b905. 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 (commits85bca8b,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>
577 lines
21 KiB
TypeScript
577 lines
21 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import type * as DrizzleOrm from "drizzle-orm";
|
|
|
|
vi.mock("~/database/context", () => ({
|
|
database: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/models/scoring-calculator", () => ({
|
|
processQualifyingEvent: vi.fn(),
|
|
}));
|
|
|
|
import { syncTournamentResults } from "../sync-tournament-results";
|
|
import { database } from "~/database/context";
|
|
import { processQualifyingEvent } from "~/models/scoring-calculator";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Mock data types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface FakeTournamentResult {
|
|
tournamentId: string;
|
|
participantId: string;
|
|
placement: number | null;
|
|
rawScore: string | null;
|
|
}
|
|
|
|
interface FakeScoringEvent {
|
|
id: string;
|
|
sportsSeasonId: string;
|
|
tournamentId: string | null;
|
|
}
|
|
|
|
interface FakeSeasonParticipant {
|
|
id: string;
|
|
sportsSeasonId: string;
|
|
participantId: string | null;
|
|
name: string;
|
|
}
|
|
|
|
interface FakeEventResult {
|
|
id: string;
|
|
scoringEventId: string;
|
|
seasonParticipantId: string;
|
|
placement: number | null;
|
|
qualifyingPointsAwarded: string | null;
|
|
rawScore: string | null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fake in-memory DB
|
|
//
|
|
// We build a single shared object with a chainable select/insert/update API
|
|
// that the service uses identically whether it's the top-level `db` or the
|
|
// `tx` inside a transaction. This lets us both observe the writes that would
|
|
// have happened and emulate idempotent upserts.
|
|
//
|
|
// Internal state holds the three tables the service queries:
|
|
// - tournament_results
|
|
// - scoring_events
|
|
// - season_participants
|
|
// - event_results
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface FakeDbState {
|
|
tournamentResults: FakeTournamentResult[];
|
|
scoringEvents: FakeScoringEvent[];
|
|
seasonParticipants: FakeSeasonParticipant[];
|
|
eventResults: FakeEventResult[];
|
|
}
|
|
|
|
/**
|
|
* A very thin fake drizzle-ish db. The service only uses:
|
|
* - db.select().from(table).where(cond) -- returns rows
|
|
* - db.insert(table).values(row[|rows]) -- insert
|
|
* - db.update(table).set(...).where(cond) -- update
|
|
* - db.transaction(fn) -- runs fn with the same db
|
|
*
|
|
* We identify the target table by reference equality to the schema objects.
|
|
* The service passes schema.tournamentResults etc., so we capture the real
|
|
* schema module and compare by ref.
|
|
*/
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function tableName(table: any): string {
|
|
// drizzle-orm PgTable exposes the table name under a symbol. Try a few.
|
|
const sym = Object.getOwnPropertySymbols(table).find(
|
|
(s) => s.toString() === "Symbol(drizzle:Name)"
|
|
);
|
|
if (sym) return table[sym];
|
|
// Fallback for our shim: read `.tableName` property if set.
|
|
return table.tableName;
|
|
}
|
|
|
|
function makeFakeDb(state: FakeDbState) {
|
|
// We mirror the shape in a lazy way: each predicate function is stored on the
|
|
// call so we can match rows. In practice the service only filters by simple
|
|
// eq() / and() combinations — we don't try to parse drizzle's SQL tree.
|
|
// Instead, we stash the filters the service applies by table.
|
|
//
|
|
// The simpler and more faithful approach: every call records enough info for
|
|
// us to return the right subset.
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function rowsFor(table: any): any[] {
|
|
// Table objects are drizzle PgTable objects; we identify them by name.
|
|
const name = tableName(table);
|
|
switch (name) {
|
|
case "tournament_results":
|
|
return state.tournamentResults;
|
|
case "scoring_events":
|
|
return state.scoringEvents;
|
|
case "season_participants":
|
|
return state.seasonParticipants;
|
|
case "event_results":
|
|
return state.eventResults;
|
|
default:
|
|
throw new Error(`Unknown table in fake db: ${name}`);
|
|
}
|
|
}
|
|
|
|
const db = {
|
|
// ---------- select ----------
|
|
select: vi.fn().mockImplementation(() => {
|
|
const chain = {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
_table: null as any,
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
from(table: any) {
|
|
chain._table = table;
|
|
return chain;
|
|
},
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
where(predicate: any) {
|
|
// The predicate is a drizzle SQL expression; we can't introspect it
|
|
// easily. The fake predicate stash sets a callback (see below). If
|
|
// the predicate is a function we apply it; otherwise we return all
|
|
// rows for the table (the caller will then filter).
|
|
const rows = rowsFor(chain._table);
|
|
if (typeof predicate === "function") {
|
|
return Promise.resolve(rows.filter(predicate));
|
|
}
|
|
// Unknown predicate: the test harness attaches `__fakeFilter` to the
|
|
// predicate value we interposed. When we can't evaluate, just return
|
|
// all rows — the fake is used only by the service and tests that
|
|
// control what rows exist.
|
|
return Promise.resolve(rows);
|
|
},
|
|
};
|
|
return chain;
|
|
}),
|
|
|
|
// ---------- insert ----------
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
insert: vi.fn().mockImplementation((table: any) => {
|
|
return {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
values(row: any) {
|
|
const rows = Array.isArray(row) ? row : [row];
|
|
const existing = rowsFor(table);
|
|
for (const r of rows) {
|
|
// Assign a fake id for event_results (others aren't re-read by ID).
|
|
existing.push({ id: `er-${existing.length + 1}`, ...r });
|
|
}
|
|
return {
|
|
returning: vi.fn().mockResolvedValue(rows),
|
|
};
|
|
},
|
|
};
|
|
}),
|
|
|
|
// ---------- update ----------
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
update: vi.fn().mockImplementation((table: any) => {
|
|
return {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
set(patch: any) {
|
|
return {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
where(predicate: any) {
|
|
const rows = rowsFor(table);
|
|
for (const r of rows) {
|
|
if (typeof predicate === "function" ? predicate(r) : true) {
|
|
Object.assign(r, patch);
|
|
}
|
|
}
|
|
return Promise.resolve();
|
|
},
|
|
};
|
|
},
|
|
};
|
|
}),
|
|
|
|
// ---------- transaction ----------
|
|
transaction: vi
|
|
.fn()
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
.mockImplementation(async (fn: (tx: any) => any) => fn(db)),
|
|
};
|
|
|
|
return db;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The service builds drizzle SQL expressions via eq() / and() from
|
|
// drizzle-orm. We can't intercept those without re-mocking the whole module.
|
|
// Instead we mock drizzle-orm's eq/and to return predicate functions directly.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
vi.mock("drizzle-orm", async () => {
|
|
const actual = await vi.importActual<typeof DrizzleOrm>("drizzle-orm");
|
|
return {
|
|
...actual,
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
eq: (col: any, val: any) => {
|
|
// Each column object (PgColumn) has a `.name` property giving the DB
|
|
// column name. Return a predicate that reads that key off the row.
|
|
const key = colKey(col);
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
return (row: any) => row[key] === val;
|
|
},
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
and: (...preds: any[]) => (row: any) => preds.every((p) => p(row)),
|
|
};
|
|
});
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function colKey(col: any): string {
|
|
// drizzle PgColumn: its .name is the snake_case DB name, but our fake state
|
|
// uses camelCase JS field names. Map common columns manually.
|
|
const n = col?.name ?? col?.config?.name ?? "";
|
|
const map: Record<string, string> = {
|
|
tournament_id: "tournamentId",
|
|
sports_season_id: "sportsSeasonId",
|
|
scoring_event_id: "scoringEventId",
|
|
season_participant_id: "seasonParticipantId",
|
|
participant_id: "participantId",
|
|
id: "id",
|
|
};
|
|
return map[n] ?? n;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Helpers for building fixture data
|
|
// ---------------------------------------------------------------------------
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
function seedBasicState(overrides: Partial<FakeDbState> = {}): FakeDbState {
|
|
return {
|
|
tournamentResults: [],
|
|
scoringEvents: [],
|
|
seasonParticipants: [],
|
|
eventResults: [],
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Test 1: Single window, full roster match
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe("syncTournamentResults", () => {
|
|
it("syncs a single window with two canonical results and fills 0-QP for unmatched", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{
|
|
tournamentId: "t-1",
|
|
participantId: "cp-A",
|
|
placement: 1,
|
|
rawScore: "280",
|
|
},
|
|
{
|
|
tournamentId: "t-1",
|
|
participantId: "cp-B",
|
|
placement: 2,
|
|
rawScore: "282",
|
|
},
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-1", sportsSeasonId: "ss-1", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
{
|
|
id: "sp-A",
|
|
sportsSeasonId: "ss-1",
|
|
participantId: "cp-A",
|
|
name: "A",
|
|
},
|
|
{
|
|
id: "sp-B",
|
|
sportsSeasonId: "ss-1",
|
|
participantId: "cp-B",
|
|
name: "B",
|
|
},
|
|
{
|
|
id: "sp-C",
|
|
sportsSeasonId: "ss-1",
|
|
participantId: "cp-C",
|
|
name: "C",
|
|
},
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
vi.mocked(processQualifyingEvent).mockResolvedValue(undefined);
|
|
|
|
const report = await syncTournamentResults("t-1");
|
|
|
|
expect(report.windowsSynced).toBe(1);
|
|
expect(report.windowsFailed).toBe(0);
|
|
expect(report.failures).toEqual([]);
|
|
|
|
const eventRows = state.eventResults.filter(
|
|
(r) => r.scoringEventId === "ev-1"
|
|
);
|
|
// sp-A: placement 1, sp-B: placement 2, sp-C: 0-QP filler
|
|
expect(eventRows).toHaveLength(3);
|
|
|
|
const a = eventRows.find((r) => r.seasonParticipantId === "sp-A");
|
|
expect(a?.placement).toBe(1);
|
|
expect(a?.rawScore).toBe("280");
|
|
|
|
const b = eventRows.find((r) => r.seasonParticipantId === "sp-B");
|
|
expect(b?.placement).toBe(2);
|
|
expect(b?.rawScore).toBe("282");
|
|
|
|
const c = eventRows.find((r) => r.seasonParticipantId === "sp-C");
|
|
expect(c?.placement).toBeNull();
|
|
expect(c?.qualifyingPointsAwarded).toBe("0");
|
|
|
|
expect(processQualifyingEvent).toHaveBeenCalledTimes(1);
|
|
expect(processQualifyingEvent).toHaveBeenCalledWith("ev-1", db);
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Test 2: Two overlapping windows — same tournament, different sports_seasons
|
|
// -------------------------------------------------------------------------
|
|
|
|
it("fans out to multiple windows, each getting only its own participants", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{ tournamentId: "t-1", participantId: "cp-X", placement: 1, rawScore: null },
|
|
{ tournamentId: "t-1", participantId: "cp-Y", placement: 2, rawScore: null },
|
|
{ tournamentId: "t-1", participantId: "cp-Z", placement: 3, rawScore: null },
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-A", sportsSeasonId: "ss-A", tournamentId: "t-1" },
|
|
{ id: "ev-B", sportsSeasonId: "ss-B", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
// Window A has X, Y
|
|
{ id: "sp-AX", sportsSeasonId: "ss-A", participantId: "cp-X", name: "X" },
|
|
{ id: "sp-AY", sportsSeasonId: "ss-A", participantId: "cp-Y", name: "Y" },
|
|
// Window B has Y, Z
|
|
{ id: "sp-BY", sportsSeasonId: "ss-B", participantId: "cp-Y", name: "Y" },
|
|
{ id: "sp-BZ", sportsSeasonId: "ss-B", participantId: "cp-Z", name: "Z" },
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
vi.mocked(processQualifyingEvent).mockResolvedValue(undefined);
|
|
|
|
const report = await syncTournamentResults("t-1");
|
|
|
|
expect(report.windowsSynced).toBe(2);
|
|
expect(report.windowsFailed).toBe(0);
|
|
|
|
const aRows = state.eventResults.filter((r) => r.scoringEventId === "ev-A");
|
|
const bRows = state.eventResults.filter((r) => r.scoringEventId === "ev-B");
|
|
|
|
// Window A: sp-AX (placement 1), sp-AY (placement 2). No 0-QP fillers
|
|
// since both roster members got results.
|
|
expect(aRows).toHaveLength(2);
|
|
expect(aRows.find((r) => r.seasonParticipantId === "sp-AX")?.placement).toBe(1);
|
|
expect(aRows.find((r) => r.seasonParticipantId === "sp-AY")?.placement).toBe(2);
|
|
|
|
// Window B: sp-BY (placement 2), sp-BZ (placement 3). Again no fillers.
|
|
expect(bRows).toHaveLength(2);
|
|
expect(bRows.find((r) => r.seasonParticipantId === "sp-BY")?.placement).toBe(2);
|
|
expect(bRows.find((r) => r.seasonParticipantId === "sp-BZ")?.placement).toBe(3);
|
|
|
|
expect(processQualifyingEvent).toHaveBeenCalledTimes(2);
|
|
expect(processQualifyingEvent).toHaveBeenNthCalledWith(1, "ev-A", db);
|
|
expect(processQualifyingEvent).toHaveBeenNthCalledWith(2, "ev-B", db);
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Test 3: Idempotent re-run
|
|
// -------------------------------------------------------------------------
|
|
|
|
it("is idempotent: a second run leaves the same end state", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{ tournamentId: "t-1", participantId: "cp-A", placement: 1, rawScore: "10" },
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-1", sportsSeasonId: "ss-1", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
{ id: "sp-A", sportsSeasonId: "ss-1", participantId: "cp-A", name: "A" },
|
|
{ id: "sp-B", sportsSeasonId: "ss-1", participantId: "cp-B", name: "B" },
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
vi.mocked(processQualifyingEvent).mockResolvedValue(undefined);
|
|
|
|
await syncTournamentResults("t-1");
|
|
const afterFirst = JSON.parse(JSON.stringify(state.eventResults));
|
|
|
|
await syncTournamentResults("t-1");
|
|
const afterSecond = state.eventResults;
|
|
|
|
// Same row count, same per-row placement / QP / participant / event.
|
|
expect(afterSecond).toHaveLength(afterFirst.length);
|
|
for (const first of afterFirst) {
|
|
const match = afterSecond.find(
|
|
(r) =>
|
|
r.scoringEventId === first.scoringEventId &&
|
|
r.seasonParticipantId === first.seasonParticipantId
|
|
);
|
|
expect(match).toBeDefined();
|
|
expect(match?.placement).toBe(first.placement);
|
|
expect(match?.qualifyingPointsAwarded).toBe(first.qualifyingPointsAwarded);
|
|
expect(match?.rawScore).toBe(first.rawScore);
|
|
}
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Test 4: Correction propagation
|
|
// -------------------------------------------------------------------------
|
|
|
|
it("propagates canonical placement corrections to all linked windows", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{ tournamentId: "t-1", participantId: "cp-A", placement: 1, rawScore: null },
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-A", sportsSeasonId: "ss-A", tournamentId: "t-1" },
|
|
{ id: "ev-B", sportsSeasonId: "ss-B", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
{ id: "sp-AA", sportsSeasonId: "ss-A", participantId: "cp-A", name: "A" },
|
|
{ id: "sp-BA", sportsSeasonId: "ss-B", participantId: "cp-A", name: "A" },
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
vi.mocked(processQualifyingEvent).mockResolvedValue(undefined);
|
|
|
|
await syncTournamentResults("t-1");
|
|
|
|
// Sanity — both windows have sp-* at placement 1.
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-AA")?.placement
|
|
).toBe(1);
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-BA")?.placement
|
|
).toBe(1);
|
|
|
|
// Correct the canonical placement from 1 to 5.
|
|
state.tournamentResults[0].placement = 5;
|
|
state.tournamentResults[0].rawScore = "99";
|
|
|
|
await syncTournamentResults("t-1");
|
|
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-AA")?.placement
|
|
).toBe(5);
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-AA")?.rawScore
|
|
).toBe("99");
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-BA")?.placement
|
|
).toBe(5);
|
|
expect(
|
|
state.eventResults.find((r) => r.seasonParticipantId === "sp-BA")?.rawScore
|
|
).toBe("99");
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Test 5: Partial failure isolation
|
|
// -------------------------------------------------------------------------
|
|
|
|
it("isolates failures: one window's error does not stop the others", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{ tournamentId: "t-1", participantId: "cp-A", placement: 1, rawScore: null },
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-A", sportsSeasonId: "ss-A", tournamentId: "t-1" },
|
|
{ id: "ev-B", sportsSeasonId: "ss-B", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
{ id: "sp-AA", sportsSeasonId: "ss-A", participantId: "cp-A", name: "A" },
|
|
{ id: "sp-BA", sportsSeasonId: "ss-B", participantId: "cp-A", name: "A" },
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
|
|
// First window throws in processQualifyingEvent; second succeeds.
|
|
vi.mocked(processQualifyingEvent)
|
|
.mockImplementationOnce(async () => {
|
|
throw new Error("QP calc failed");
|
|
})
|
|
.mockImplementationOnce(async () => undefined);
|
|
|
|
const report = await syncTournamentResults("t-1");
|
|
|
|
expect(report.windowsSynced).toBe(1);
|
|
expect(report.windowsFailed).toBe(1);
|
|
expect(report.failures).toHaveLength(1);
|
|
expect(report.failures[0].scoringEventId).toBe("ev-A");
|
|
expect(report.failures[0].sportsSeasonId).toBe("ss-A");
|
|
expect(report.failures[0].error).toContain("QP calc failed");
|
|
|
|
// Second window (ev-B) still has its row committed in our fake (we don't
|
|
// simulate rollback, but the service called through to the writes path,
|
|
// which is what we care about — the try/catch did not propagate).
|
|
expect(
|
|
state.eventResults.find(
|
|
(r) => r.scoringEventId === "ev-B" && r.seasonParticipantId === "sp-BA"
|
|
)
|
|
).toBeDefined();
|
|
|
|
expect(processQualifyingEvent).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Test 6: Participant in roster but not in canonical results → 0-QP filler
|
|
// -------------------------------------------------------------------------
|
|
|
|
it("writes 0-QP filler rows for roster participants absent from canonical results", async () => {
|
|
const state = seedBasicState({
|
|
tournamentResults: [
|
|
{ tournamentId: "t-1", participantId: "cp-A", placement: 1, rawScore: null },
|
|
],
|
|
scoringEvents: [
|
|
{ id: "ev-1", sportsSeasonId: "ss-1", tournamentId: "t-1" },
|
|
],
|
|
seasonParticipants: [
|
|
{ id: "sp-A", sportsSeasonId: "ss-1", participantId: "cp-A", name: "A" },
|
|
{ id: "sp-B", sportsSeasonId: "ss-1", participantId: "cp-B", name: "B" },
|
|
{ id: "sp-C", sportsSeasonId: "ss-1", participantId: "cp-C", name: "C" },
|
|
],
|
|
});
|
|
|
|
const db = makeFakeDb(state);
|
|
vi.mocked(database).mockReturnValue(db as never);
|
|
vi.mocked(processQualifyingEvent).mockResolvedValue(undefined);
|
|
|
|
await syncTournamentResults("t-1");
|
|
|
|
const rows = state.eventResults;
|
|
expect(rows).toHaveLength(3);
|
|
|
|
const a = rows.find((r) => r.seasonParticipantId === "sp-A");
|
|
expect(a?.placement).toBe(1);
|
|
expect(a?.qualifyingPointsAwarded).toBeUndefined(); // not set by this service
|
|
|
|
const b = rows.find((r) => r.seasonParticipantId === "sp-B");
|
|
expect(b?.placement).toBeNull();
|
|
expect(b?.qualifyingPointsAwarded).toBe("0");
|
|
|
|
const c = rows.find((r) => r.seasonParticipantId === "sp-C");
|
|
expect(c?.placement).toBeNull();
|
|
expect(c?.qualifyingPointsAwarded).toBe("0");
|
|
});
|
|
});
|