2026-05-04 20:31:44 -07:00
|
|
|
import { eq, inArray, isNull, sql, lte, gte } from "drizzle-orm";
|
2025-10-12 21:16:00 -07:00
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
2026-04-12 01:03:37 -04:00
|
|
|
import { getQPConfig, updateQPConfig } from "~/models/qualifying-points";
|
2026-05-04 20:31:44 -07:00
|
|
|
import { maybeResolveCompletedBracktForSportsSeason } from "~/services/brackt.server";
|
2025-10-12 21:16:00 -07:00
|
|
|
|
2026-03-25 20:46:54 -07:00
|
|
|
export async function countSportsSeasons(): Promise<number> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const [{ count }] = await db
|
|
|
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
|
|
|
.from(schema.sportsSeasons);
|
|
|
|
|
return count;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
export type SportsSeason = typeof schema.sportsSeasons.$inferSelect;
|
|
|
|
|
export type NewSportsSeason = typeof schema.sportsSeasons.$inferInsert;
|
2026-03-09 15:34:31 -07:00
|
|
|
export type SportsSeasonWithSport = SportsSeason & {
|
|
|
|
|
sport: typeof schema.sports.$inferSelect;
|
|
|
|
|
};
|
2026-04-09 10:07:18 -04:00
|
|
|
export type SportsSeasonListItem = SportsSeasonWithSport & {
|
|
|
|
|
participants: Array<{ id: string }>;
|
|
|
|
|
};
|
2025-10-12 21:16:00 -07:00
|
|
|
export type SportsSeasonStatus = "upcoming" | "active" | "completed";
|
|
|
|
|
export type ScoringType = "playoffs" | "regular_season" | "majors";
|
|
|
|
|
|
|
|
|
|
export async function createSportsSeason(data: NewSportsSeason): Promise<SportsSeason> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const [sportsSeason] = await db
|
|
|
|
|
.insert(schema.sportsSeasons)
|
|
|
|
|
.values(data)
|
|
|
|
|
.returning();
|
|
|
|
|
return sportsSeason;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 15:34:31 -07:00
|
|
|
export async function findSportsSeasonById(id: string): Promise<SportsSeasonWithSport | undefined> {
|
2025-10-12 21:16:00 -07:00
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasons.id, id),
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
2026-03-09 15:34:31 -07:00
|
|
|
}) as SportsSeasonWithSport | undefined;
|
2025-10-12 21:16:00 -07:00
|
|
|
}
|
|
|
|
|
|
2026-04-14 21:41:05 -07:00
|
|
|
export async function findSportsSeasonsByIds(ids: string[]): Promise<SportsSeasonWithSport[]> {
|
|
|
|
|
if (ids.length === 0) return [];
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findMany({
|
|
|
|
|
where: inArray(schema.sportsSeasons.id, ids),
|
|
|
|
|
with: { sport: true },
|
|
|
|
|
}) as SportsSeasonWithSport[];
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-02 12:45:53 -07:00
|
|
|
export async function findSportsSeasonsBySportId(sportId: string): Promise<SportsSeasonWithSport[]> {
|
2025-10-12 21:16:00 -07:00
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findMany({
|
|
|
|
|
where: eq(schema.sportsSeasons.sportId, sportId),
|
|
|
|
|
orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
2026-05-02 12:45:53 -07:00
|
|
|
}) as SportsSeasonWithSport[];
|
2025-10-12 21:16:00 -07:00
|
|
|
}
|
|
|
|
|
|
2025-10-13 10:30:47 -07:00
|
|
|
export async function findActiveSportsSeasonsBySportId(sportId: string): Promise<SportsSeason[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findMany({
|
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
|
|
|
where: (ss, { and }) =>
|
2025-10-13 10:30:47 -07:00
|
|
|
and(
|
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
|
|
|
eq(ss.sportId, sportId),
|
|
|
|
|
eq(ss.status, "active")
|
2025-10-13 10:30:47 -07:00
|
|
|
),
|
|
|
|
|
orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
export async function findSportsSeasonsByYear(year: number): Promise<SportsSeason[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findMany({
|
|
|
|
|
where: eq(schema.sportsSeasons.year, year),
|
|
|
|
|
orderBy: (sportsSeasons, { asc }) => [asc(sportsSeasons.name)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function findSportsSeasonsByStatus(status: SportsSeasonStatus): Promise<SportsSeason[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.sportsSeasons.findMany({
|
|
|
|
|
where: eq(schema.sportsSeasons.status, status),
|
|
|
|
|
orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-09 10:07:18 -04:00
|
|
|
export async function findAllSportsSeasons(): Promise<SportsSeasonListItem[]> {
|
2025-10-12 21:16:00 -07:00
|
|
|
const db = database();
|
2026-04-09 10:07:18 -04:00
|
|
|
const results = await db.query.sportsSeasons.findMany({
|
2025-10-12 21:16:00 -07:00
|
|
|
with: {
|
|
|
|
|
sport: true,
|
2025-10-15 21:21:33 -07:00
|
|
|
participants: {
|
|
|
|
|
columns: {
|
|
|
|
|
id: true,
|
|
|
|
|
},
|
|
|
|
|
},
|
2025-10-12 21:16:00 -07:00
|
|
|
},
|
|
|
|
|
});
|
2026-04-09 10:07:18 -04:00
|
|
|
|
|
|
|
|
const statusOrder: Record<SportsSeasonStatus, number> = { active: 0, upcoming: 1, completed: 2 };
|
|
|
|
|
|
2026-04-12 01:03:37 -04:00
|
|
|
return results.toSorted((a, b) => {
|
2026-04-09 10:07:18 -04:00
|
|
|
const statusDiff = statusOrder[a.status] - statusOrder[b.status];
|
|
|
|
|
if (statusDiff !== 0) return statusDiff;
|
|
|
|
|
const sportNameDiff = a.sport.name.localeCompare(b.sport.name);
|
|
|
|
|
if (sportNameDiff !== 0) return sportNameDiff;
|
|
|
|
|
return a.year - b.year;
|
|
|
|
|
});
|
2025-10-12 21:16:00 -07:00
|
|
|
}
|
|
|
|
|
|
2026-05-04 20:31:44 -07:00
|
|
|
export async function findAllAdminSportsSeasons(): Promise<SportsSeasonListItem[]> {
|
|
|
|
|
const seasons = await findAllSportsSeasons();
|
|
|
|
|
// Hide per-league private copies (fantasySeasonId IS NOT NULL); show the global template
|
|
|
|
|
return seasons.filter((season) => season.fantasySeasonId === null);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-28 22:24:13 -07:00
|
|
|
export async function findDraftableSportsSeasons() {
|
2026-03-18 22:40:19 -07:00
|
|
|
const db = database();
|
2026-04-05 19:09:52 -07:00
|
|
|
const today = sql`CURRENT_DATE`;
|
2026-04-28 22:24:13 -07:00
|
|
|
const seasons = await db.query.sportsSeasons.findMany({
|
2026-04-05 19:09:52 -07:00
|
|
|
where: (ss, { and }) =>
|
|
|
|
|
and(
|
|
|
|
|
lte(ss.draftOn, today),
|
2026-05-04 20:31:44 -07:00
|
|
|
gte(ss.draftOff, today),
|
|
|
|
|
isNull(ss.fantasySeasonId)
|
2026-04-05 19:09:52 -07:00
|
|
|
),
|
2026-03-18 22:40:19 -07:00
|
|
|
orderBy: (sportsSeasons, { desc, asc }) => [desc(sportsSeasons.year), asc(sportsSeasons.name)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
2026-04-28 22:24:13 -07:00
|
|
|
participants: { columns: { id: true } },
|
2026-03-18 22:40:19 -07:00
|
|
|
},
|
|
|
|
|
});
|
2026-04-28 22:24:13 -07:00
|
|
|
return seasons.map(({ participants, ...s }) => ({
|
|
|
|
|
...s,
|
|
|
|
|
participantCount: participants.length,
|
|
|
|
|
}));
|
2026-03-18 22:40:19 -07:00
|
|
|
}
|
|
|
|
|
|
2026-06-04 21:31:49 +00:00
|
|
|
export async function findDraftableSportsSeasonBySportId(sportId: string) {
|
|
|
|
|
const db = database();
|
|
|
|
|
const today = sql`CURRENT_DATE`;
|
|
|
|
|
return await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: (ss, ops) =>
|
|
|
|
|
ops.and(
|
|
|
|
|
ops.eq(ss.sportId, sportId),
|
|
|
|
|
lte(ss.draftOn, today),
|
|
|
|
|
gte(ss.draftOff, today),
|
|
|
|
|
isNull(ss.fantasySeasonId)
|
|
|
|
|
),
|
|
|
|
|
orderBy: (ss, { desc }) => [desc(ss.year), desc(ss.draftOn)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-02 00:44:23 +00:00
|
|
|
export type DraftScheduleWindow = {
|
|
|
|
|
id: string;
|
|
|
|
|
name: string;
|
|
|
|
|
year: number;
|
|
|
|
|
status: SportsSeasonStatus;
|
|
|
|
|
draftOn: string;
|
|
|
|
|
draftOff: string;
|
|
|
|
|
sport: {
|
|
|
|
|
id: string;
|
|
|
|
|
name: string;
|
|
|
|
|
slug: string;
|
|
|
|
|
iconUrl: string | null;
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns admin sport-seasons (fantasySeasonId IS NULL) whose draft window
|
|
|
|
|
* [draftOn, draftOff] overlaps the horizon [today, today + monthsAhead]. Uses an
|
|
|
|
|
* overlap test (not containment) so windows already open, or spanning the horizon
|
|
|
|
|
* edges, are still included. Powers the admin draft-schedule Gantt chart.
|
|
|
|
|
*/
|
|
|
|
|
export async function findDraftScheduleForHorizon(
|
|
|
|
|
monthsAhead: number
|
|
|
|
|
): Promise<DraftScheduleWindow[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const horizonEnd = sql`CURRENT_DATE + (${monthsAhead} * interval '1 month')`;
|
|
|
|
|
const seasons = await db.query.sportsSeasons.findMany({
|
|
|
|
|
where: (ss, { and }) =>
|
|
|
|
|
and(
|
|
|
|
|
isNull(ss.fantasySeasonId),
|
|
|
|
|
gte(ss.draftOff, sql`CURRENT_DATE`),
|
|
|
|
|
lte(ss.draftOn, horizonEnd)
|
|
|
|
|
),
|
|
|
|
|
orderBy: (sportsSeasons, { asc }) => [asc(sportsSeasons.draftOn)],
|
|
|
|
|
with: {
|
|
|
|
|
sport: {
|
|
|
|
|
columns: { id: true, name: true, slug: true, iconUrl: true },
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return seasons.map((s) => ({
|
|
|
|
|
id: s.id,
|
|
|
|
|
name: s.name,
|
|
|
|
|
year: s.year,
|
|
|
|
|
status: s.status,
|
|
|
|
|
draftOn: s.draftOn,
|
|
|
|
|
draftOff: s.draftOff,
|
|
|
|
|
sport: s.sport,
|
|
|
|
|
})) as DraftScheduleWindow[];
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
export async function updateSportsSeason(
|
|
|
|
|
id: string,
|
|
|
|
|
data: Partial<NewSportsSeason>
|
|
|
|
|
): Promise<SportsSeason> {
|
|
|
|
|
const db = database();
|
2026-05-04 20:31:44 -07:00
|
|
|
const previous = await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasons.id, id),
|
|
|
|
|
columns: { status: true },
|
|
|
|
|
});
|
2025-10-12 21:16:00 -07:00
|
|
|
const [sportsSeason] = await db
|
|
|
|
|
.update(schema.sportsSeasons)
|
|
|
|
|
.set({ ...data, updatedAt: new Date() })
|
|
|
|
|
.where(eq(schema.sportsSeasons.id, id))
|
|
|
|
|
.returning();
|
2026-05-04 20:31:44 -07:00
|
|
|
|
|
|
|
|
if (previous && previous.status !== "completed" && sportsSeason.status === "completed") {
|
|
|
|
|
await maybeResolveCompletedBracktForSportsSeason(sportsSeason.id, db);
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-12 21:16:00 -07:00
|
|
|
return sportsSeason;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function updateSportsSeasonStatus(
|
|
|
|
|
id: string,
|
|
|
|
|
status: SportsSeasonStatus
|
|
|
|
|
): Promise<SportsSeason> {
|
|
|
|
|
return await updateSportsSeason(id, { status });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function deleteSportsSeason(id: string): Promise<void> {
|
|
|
|
|
const db = database();
|
|
|
|
|
await db.delete(schema.sportsSeasons).where(eq(schema.sportsSeasons.id, id));
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-12 01:03:37 -04:00
|
|
|
export function shiftDateByYears(dateStr: string, years: number): string {
|
|
|
|
|
const d = new Date(dateStr + "T12:00:00Z");
|
|
|
|
|
d.setUTCFullYear(d.getUTCFullYear() + years);
|
|
|
|
|
return d.toISOString().split("T")[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function shiftTimestampByYears(date: Date, years: number): Date {
|
|
|
|
|
const d = new Date(date);
|
|
|
|
|
d.setUTCFullYear(d.getUTCFullYear() + years);
|
|
|
|
|
return d;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Clone a sports season: creates a new season from newData, then copies
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
* participants (name/shortName/externalId only), simulator structure/config,
|
|
|
|
|
* scoring events (dates shifted by yearDelta), and QP config. Volatile simulator
|
|
|
|
|
* inputs such as futures odds and Elo ratings are copied only when explicitly
|
|
|
|
|
* requested.
|
2026-04-12 01:03:37 -04:00
|
|
|
*/
|
|
|
|
|
export async function cloneSportsSeason(
|
|
|
|
|
sourceId: string,
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
newData: NewSportsSeason,
|
|
|
|
|
options: { copySimulatorInputs?: boolean } = {}
|
2026-04-12 01:03:37 -04:00
|
|
|
): Promise<SportsSeason> {
|
2025-10-12 21:16:00 -07:00
|
|
|
const db = database();
|
2026-04-12 01:03:37 -04:00
|
|
|
|
|
|
|
|
const sourceSeason = await db.query.sportsSeasons.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasons.id, sourceId),
|
2025-10-12 21:16:00 -07:00
|
|
|
});
|
|
|
|
|
|
2026-04-12 01:03:37 -04:00
|
|
|
if (!sourceSeason) {
|
|
|
|
|
throw new Error(`Source season ${sourceId} not found`);
|
2025-10-12 21:16:00 -07:00
|
|
|
}
|
2026-04-12 01:03:37 -04:00
|
|
|
|
|
|
|
|
const yearDelta = newData.year - sourceSeason.year;
|
|
|
|
|
|
|
|
|
|
// Merge ELO calibration fields from source (form doesn't expose them)
|
|
|
|
|
const mergedData: NewSportsSeason = {
|
|
|
|
|
eloCalibrationExponent: sourceSeason.eloCalibrationExponent,
|
|
|
|
|
eloMinRating: sourceSeason.eloMinRating,
|
|
|
|
|
eloMaxRating: sourceSeason.eloMaxRating,
|
|
|
|
|
...newData,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Read all source data before writing anything
|
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 sourceParticipants = await db.query.seasonParticipants.findMany({
|
|
|
|
|
where: eq(schema.seasonParticipants.sportsSeasonId, sourceId),
|
2026-04-12 01:03:37 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const sourceEvents = await db.query.scoringEvents.findMany({
|
|
|
|
|
where: eq(schema.scoringEvents.sportsSeasonId, sourceId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const sourceQPConfig =
|
|
|
|
|
newData.scoringPattern === "qualifying_points"
|
|
|
|
|
? await getQPConfig(sourceId, db)
|
|
|
|
|
: null;
|
|
|
|
|
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
const sourceSimulatorConfig = await db.query.sportsSeasonSimulatorConfigs.findFirst({
|
|
|
|
|
where: eq(schema.sportsSeasonSimulatorConfigs.sportsSeasonId, sourceId),
|
2026-04-12 01:03:37 -04:00
|
|
|
});
|
|
|
|
|
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
const sourceEvRows = options.copySimulatorInputs
|
|
|
|
|
? await db.query.seasonParticipantExpectedValues.findMany({
|
|
|
|
|
where: eq(schema.seasonParticipantExpectedValues.sportsSeasonId, sourceId),
|
|
|
|
|
})
|
|
|
|
|
: [];
|
|
|
|
|
|
|
|
|
|
const sourceSimulatorInputs = options.copySimulatorInputs
|
|
|
|
|
? await db.query.seasonParticipantSimulatorInputs.findMany({
|
|
|
|
|
where: eq(schema.seasonParticipantSimulatorInputs.sportsSeasonId, sourceId),
|
|
|
|
|
})
|
|
|
|
|
: [];
|
|
|
|
|
|
2026-04-12 01:03:37 -04:00
|
|
|
// Build lookup: (externalId ?? name) → source EV, only for rows that have
|
|
|
|
|
// actual input data (odds or Elo) worth carrying forward
|
|
|
|
|
type SourceEv = typeof sourceEvRows[number];
|
|
|
|
|
const sourceEvById = new Map(sourceEvRows.map((r) => [r.participantId, r]));
|
|
|
|
|
const sourceEvByKey = new Map<string, SourceEv>();
|
|
|
|
|
for (const p of sourceParticipants) {
|
|
|
|
|
const ev = sourceEvById.get(p.id);
|
|
|
|
|
if (ev && (ev.sourceOdds !== null || ev.sourceElo !== null)) {
|
|
|
|
|
sourceEvByKey.set(p.externalId ?? p.name, ev);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// All writes in a single transaction — partial clone is never committed
|
|
|
|
|
return await db.transaction(async (tx: typeof db) => {
|
|
|
|
|
const [newSeason] = await tx
|
|
|
|
|
.insert(schema.sportsSeasons)
|
|
|
|
|
.values(mergedData)
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
const newParticipants =
|
|
|
|
|
sourceParticipants.length > 0
|
|
|
|
|
? 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
|
|
|
.insert(schema.seasonParticipants)
|
2026-04-12 01:03:37 -04:00
|
|
|
.values(
|
|
|
|
|
sourceParticipants.map((p: typeof sourceParticipants[number]) => ({
|
|
|
|
|
sportsSeasonId: newSeason.id,
|
|
|
|
|
name: p.name,
|
|
|
|
|
shortName: p.shortName,
|
|
|
|
|
externalId: p.externalId,
|
2026-05-02 10:29:28 -07:00
|
|
|
participantId: p.participantId,
|
2026-04-12 01:03:37 -04:00
|
|
|
}))
|
|
|
|
|
)
|
|
|
|
|
.returning()
|
|
|
|
|
: [];
|
|
|
|
|
|
|
|
|
|
// Copy futures odds / Elo stubs matched by externalId then name
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
if (sourceSimulatorConfig) {
|
|
|
|
|
await tx.insert(schema.sportsSeasonSimulatorConfigs).values({
|
|
|
|
|
sportsSeasonId: newSeason.id,
|
|
|
|
|
simulatorType: sourceSimulatorConfig.simulatorType,
|
|
|
|
|
config: sourceSimulatorConfig.config,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (options.copySimulatorInputs && sourceEvByKey.size > 0 && newParticipants.length > 0) {
|
2026-04-12 01:03:37 -04:00
|
|
|
const now = new Date();
|
|
|
|
|
const evRows = newParticipants
|
|
|
|
|
.map((newP: typeof newParticipants[number]) => {
|
|
|
|
|
const key = newP.externalId ?? newP.name;
|
|
|
|
|
const sourceEv = sourceEvByKey.get(key);
|
|
|
|
|
if (!sourceEv) return null;
|
|
|
|
|
return {
|
|
|
|
|
participantId: newP.id,
|
|
|
|
|
sportsSeasonId: newSeason.id,
|
|
|
|
|
probFirst: "0", probSecond: "0", probThird: "0", probFourth: "0",
|
|
|
|
|
probFifth: "0", probSixth: "0", probSeventh: "0", probEighth: "0",
|
|
|
|
|
expectedValue: "0",
|
|
|
|
|
source: sourceEv.source,
|
|
|
|
|
sourceOdds: sourceEv.sourceOdds,
|
|
|
|
|
sourceElo: sourceEv.sourceElo,
|
|
|
|
|
worldRanking: sourceEv.worldRanking,
|
|
|
|
|
calculatedAt: now,
|
|
|
|
|
updatedAt: now,
|
|
|
|
|
};
|
|
|
|
|
})
|
|
|
|
|
.filter((r): r is NonNullable<typeof r> => r !== null);
|
|
|
|
|
|
|
|
|
|
if (evRows.length > 0) {
|
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
|
|
|
await tx.insert(schema.seasonParticipantExpectedValues).values(evRows);
|
2026-04-12 01:03:37 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
Formalize simulator system with manifest, input-policy, runner, and admin UI (#409)
Introduces three new schema tables (simulator_profiles,
sports_season_simulator_configs, season_participant_simulator_inputs),
a central model layer (app/models/simulator.ts), and a single runner
entry point so every simulator run follows the same prepare → simulate
→ persist → snapshot → recalculate flow.
Key additions:
- manifest.ts: per-simulator display names, default configs, required/
optional inputs, derivable-input declarations, and setup sections
- input-policy.ts: resolves sourceElo from projectedWins,
projectedTablePoints, or sourceOdds; resolves ratings from sourceOdds;
supports block / fallbackElo / averageKnown / worstKnownMinus strategies
- runner.ts: single entry point for admin simulation runs; materialises
derived inputs, normalises result columns, zeroes omitted participants,
snapshots EVs, and recalculates linked fantasy standings
- /admin/simulators: inventory page with per-season readiness and bulk run
- /admin/sports-seasons/:id/simulator: per-season setup page with readiness
summary, input-policy editor, raw JSON config override, and CSV bulk input
- NCAAM/NCAAW simulators now read ratings from season_participant_simulator_inputs,
falling back to the hardcoded name-keyed maps while DB data is being populated
- Clone flow copies simulator config by default; volatile inputs (odds, Elo)
only copied when explicitly requested
Code-review fixes included in this commit:
- source field in compatibility bridge checked with !== null instead of !== undefined
- sourceEloRequirementLabel no longer appends "configured fallback" when the
participant is already excluded from all resolved sources
- Duplicate inline label maps in input-policy.ts replaced with simulatorInputLabel
- save-config preserves existing inputPolicy when the submitted JSON omits it
- Input table truncation label added (Showing 20 of N)
- CSV description notes values must not contain commas
- N+1 comment added to listSportsSeasonSimulatorSummaries
- assertRegistrySchemaDriftFree called in manifest tests
- Runner test suite added covering happy path, already-running guard,
readiness failure, empty results, and error recovery with status reset
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:09:53 -07:00
|
|
|
if (options.copySimulatorInputs && sourceSimulatorInputs.length > 0 && newParticipants.length > 0) {
|
|
|
|
|
const sourceParticipantById = new Map(sourceParticipants.map((p) => [p.id, p]));
|
|
|
|
|
const sourceInputByKey = new Map(
|
|
|
|
|
sourceSimulatorInputs.flatMap((input) => {
|
|
|
|
|
const sourceParticipant = sourceParticipantById.get(input.participantId);
|
|
|
|
|
return sourceParticipant ? [[sourceParticipant.externalId ?? sourceParticipant.name, input] as const] : [];
|
|
|
|
|
})
|
|
|
|
|
);
|
|
|
|
|
const simulatorInputRows = newParticipants
|
|
|
|
|
.map((newP: typeof newParticipants[number]) => {
|
|
|
|
|
const sourceInput = sourceInputByKey.get(newP.externalId ?? newP.name);
|
|
|
|
|
if (!sourceInput) return null;
|
|
|
|
|
return {
|
|
|
|
|
participantId: newP.id,
|
|
|
|
|
sportsSeasonId: newSeason.id,
|
|
|
|
|
sourceOdds: sourceInput.sourceOdds,
|
|
|
|
|
sourceElo: sourceInput.sourceElo,
|
|
|
|
|
worldRanking: sourceInput.worldRanking,
|
|
|
|
|
rating: sourceInput.rating,
|
|
|
|
|
projectedWins: sourceInput.projectedWins,
|
|
|
|
|
projectedTablePoints: sourceInput.projectedTablePoints,
|
|
|
|
|
seed: sourceInput.seed,
|
|
|
|
|
region: sourceInput.region,
|
|
|
|
|
metadata: sourceInput.metadata,
|
|
|
|
|
};
|
|
|
|
|
})
|
|
|
|
|
.filter((row): row is NonNullable<typeof row> => row !== null);
|
|
|
|
|
|
|
|
|
|
if (simulatorInputRows.length > 0) {
|
|
|
|
|
await tx.insert(schema.seasonParticipantSimulatorInputs).values(simulatorInputRows);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-12 01:03:37 -04:00
|
|
|
if (sourceEvents.length > 0) {
|
|
|
|
|
await tx.insert(schema.scoringEvents).values(
|
|
|
|
|
sourceEvents.map((e: typeof sourceEvents[number]) => ({
|
|
|
|
|
sportsSeasonId: newSeason.id,
|
|
|
|
|
name: e.name,
|
|
|
|
|
eventType: e.eventType,
|
|
|
|
|
isQualifyingEvent: e.isQualifyingEvent,
|
2026-05-02 22:19:59 -07:00
|
|
|
// Carries over the source season's tournament IDs. For qualifying_points seasons
|
|
|
|
|
// cloned into a new year, qualifying events will still point to the old year's
|
|
|
|
|
// canonical tournaments — admin should delete and recreate them once the new
|
|
|
|
|
// year's tournaments exist.
|
|
|
|
|
tournamentId: e.tournamentId ?? null,
|
2026-04-12 01:03:37 -04:00
|
|
|
bracketTemplateId: e.bracketTemplateId,
|
|
|
|
|
scoringStartsAtRound: e.scoringStartsAtRound,
|
|
|
|
|
isComplete: false,
|
|
|
|
|
eventDate: e.eventDate ? shiftDateByYears(e.eventDate, yearDelta) : null,
|
|
|
|
|
eventStartsAt: e.eventStartsAt ? shiftTimestampByYears(e.eventStartsAt, yearDelta) : null,
|
|
|
|
|
}))
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sourceQPConfig) {
|
|
|
|
|
await updateQPConfig(
|
|
|
|
|
newSeason.id,
|
|
|
|
|
sourceQPConfig.map((qp: typeof sourceQPConfig[number]) => ({
|
|
|
|
|
placement: qp.placement,
|
|
|
|
|
points: parseFloat(qp.points),
|
|
|
|
|
})),
|
|
|
|
|
tx as ReturnType<typeof database>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return newSeason;
|
|
|
|
|
});
|
2025-10-12 21:16:00 -07:00
|
|
|
}
|