brackt/app/models/participant-result.ts
Claude a143df51f6
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 3m4s
🚀 Deploy / ʦ🔍 Typecheck & Lint (pull_request) Successful in 1m22s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Fix review findings in the tie-split ledger and backfill
A review of the previous two commits found five defects in the new ledger
writer and backfill, plus one pre-existing scoring bug the refactor
exposed.

season_standings ties were never split. processSeasonStandings
deliberately writes the same finalPosition to every driver in a tied group
-- its comment says "the scoring system will handle averaging" -- but no
path ever did, so two drivers tied for 3rd each banked the full 50 instead
of the published 45. This predates the tie-split work; the original
cascade had only bracket and qualifying_points arms. Introduce
usesSharedPlacementSplit as the single definition of which patterns record
ties as a repeated placement, and route both calculatePickPoints and every
caller-side gate through it. The caller gates matter as much as the
helper: a gate left hardcoded to qualifying_points silently passes a tie
count of 1, which reads as "no tie" and makes the fix inert.

The ledger anchor picked the wrong event. Ordering on completedAt with no
isComplete filter ranked never-completed events first, because drizzle's
desc() emits a bare desc and Postgres orders DESC as NULLS FIRST.
Restrict to completed events and order explicitly with NULLS LAST plus a
stable tiebreak. The anchor is also no longer load-bearing for
idempotence: stale event-level rows for the sports season are cleared
before writing, so a re-run whose anchor moved replaces rather than
duplicates.

A ledger failure could abort finalization. The call sat unguarded after
the season was already marked completed, so a throw in any of its queries
would skip the standings recalculation and the Discord notification. Guard
both call sites the way the probability refresh directly below already is.

Rows could be mislabelled permanently. The backfill passed no eventName,
and the upsert never rewrote scoringEventName. Derive the label from the
scoring pattern inside the writer so omitting it is impossible, and
refresh it on conflict so existing rows can be repaired.

The backfill damaged unrelated leagues. recalculateStandings rewrites
previousRank, so sweeping every season wiped rank-movement arrows league
wide, including leagues holding no tie at all. Scope it to seasons
drafting from a sports season that actually contains a tied placement, and
correct the docblock that called it a pure recompute.

Also drops the inert Number.EPSILON guard from calculateAveragedPoints
(EPSILON is below the ULP for any value >= 2, and integer averages landing
on .5 are exactly representable) and extracts countSharedPlacements so the
ledger writer stops re-querying rows it already holds.

Every fix is covered by a test confirmed to fail when that fix alone is
reverted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019LZLF1PAfeKdpYog3NKtyz
2026-08-08 07:32:14 +00:00

212 lines
6.4 KiB
TypeScript

import { eq, and, inArray } from "drizzle-orm";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
export type ParticipantResult = typeof schema.seasonParticipantResults.$inferSelect;
export type ParticipantResultWithParticipant = ParticipantResult & {
participant: { id: string; name: string } | null;
};
export type NewParticipantResult = typeof schema.seasonParticipantResults.$inferInsert;
export async function createParticipantResult(
data: NewParticipantResult
): Promise<ParticipantResult> {
const db = database();
const [result] = await db
.insert(schema.seasonParticipantResults)
.values(data)
.returning();
return result;
}
export async function createManyParticipantResults(
data: NewParticipantResult[]
): Promise<ParticipantResult[]> {
const db = database();
return await db
.insert(schema.seasonParticipantResults)
.values(data)
.returning();
}
export async function findParticipantResultById(
id: string
): Promise<ParticipantResult | undefined> {
const db = database();
return await db.query.seasonParticipantResults.findFirst({
where: eq(schema.seasonParticipantResults.id, id),
with: {
participant: true,
sportsSeason: {
with: {
sport: true,
},
},
},
});
}
export async function findParticipantResultByParticipantId(
participantId: string
): Promise<ParticipantResult | undefined> {
const db = database();
return await db.query.seasonParticipantResults.findFirst({
where: eq(schema.seasonParticipantResults.participantId, participantId),
with: {
participant: true,
sportsSeason: {
with: {
sport: true,
},
},
},
});
}
export async function findParticipantResultsBySportsSeasonId(
sportsSeasonId: string
): Promise<ParticipantResultWithParticipant[]> {
const db = database();
return await db.query.seasonParticipantResults.findMany({
where: eq(schema.seasonParticipantResults.sportsSeasonId, sportsSeasonId),
orderBy: (results, { asc }) => [asc(results.finalPosition)],
with: {
participant: true,
},
});
}
/**
* Tallies how many participants share each scoring placement, per sports season.
*
* Pure counterpart to getSharedPlacementCounts, for callers that already hold the
* result rows. Split out so there is exactly one definition of what "tied" means
* — the whole point of this module is that every screen counts ties identically.
*
* Positions <= 0 (no scoring placement) are excluded.
*/
export function countSharedPlacements(
rows: Array<{ sportsSeasonId: string; finalPosition: number | null }>
): Map<string, Map<number, number>> {
const counts = new Map<string, Map<number, number>>();
for (const row of rows) {
if (row.finalPosition === null || row.finalPosition <= 0) continue;
let bySeason = counts.get(row.sportsSeasonId);
if (!bySeason) {
bySeason = new Map<number, number>();
counts.set(row.sportsSeasonId, bySeason);
}
bySeason.set(row.finalPosition, (bySeason.get(row.finalPosition) ?? 0) + 1);
}
return counts;
}
/**
* How many participants share each scoring placement, per sports season.
*
* Returns sportsSeasonId → (finalPosition → count). Used to split a tied
* placement's points across the tied participants (see calculatePickPoints).
*
* The count spans EVERY result in the sports season, not just drafted ones — a
* golfer tied for 8th with an undrafted player still only earns half the 8th
* place points, so narrowing this query to drafted participants would silently
* over-award.
*
* Callers that look up a position with no entry should treat it as 1 (no tie).
*/
export async function getSharedPlacementCounts(
sportsSeasonIds: string[],
providedDb?: ReturnType<typeof database>
): Promise<Map<string, Map<number, number>>> {
if (sportsSeasonIds.length === 0) return new Map();
const db = providedDb || database();
const rows = await db.query.seasonParticipantResults.findMany({
where: inArray(schema.seasonParticipantResults.sportsSeasonId, sportsSeasonIds),
columns: { sportsSeasonId: true, finalPosition: true },
});
return countSharedPlacements(rows);
}
/**
* Convenience lookup over getSharedPlacementCounts' result. Missing entries mean
* no other participant shares the placement, so the tie count is 1.
*/
export function lookupSharedPlacementCount(
counts: Map<string, Map<number, number>>,
sportsSeasonId: string,
finalPosition: number
): number {
return counts.get(sportsSeasonId)?.get(finalPosition) ?? 1;
}
export async function updateParticipantResult(
id: string,
data: Partial<NewParticipantResult>
): Promise<ParticipantResult> {
const db = database();
const [result] = await db
.update(schema.seasonParticipantResults)
.set({ ...data, updatedAt: new Date() })
.where(eq(schema.seasonParticipantResults.id, id))
.returning();
return result;
}
export async function deleteParticipantResult(id: string): Promise<void> {
const db = database();
await db.delete(schema.seasonParticipantResults).where(eq(schema.seasonParticipantResults.id, id));
}
export async function deleteParticipantResultsBySportsSeasonId(
sportsSeasonId: string,
providedDb?: ReturnType<typeof database>
): Promise<void> {
const db = providedDb || database();
await db
.delete(schema.seasonParticipantResults)
.where(eq(schema.seasonParticipantResults.sportsSeasonId, sportsSeasonId));
}
/**
* Set result for a participant in a sports season
* Points are calculated on-demand based on each fantasy league's scoring rules
*/
export async function setParticipantResult(
participantId: string,
sportsSeasonId: string,
finalPosition: number,
qualifyingPoints?: number,
notes?: string
): Promise<ParticipantResult> {
const db = database();
// Check if result already exists
const existing = await db.query.seasonParticipantResults.findFirst({
where: and(
eq(schema.seasonParticipantResults.participantId, participantId),
eq(schema.seasonParticipantResults.sportsSeasonId, sportsSeasonId)
),
});
if (existing) {
// Update existing result
return await updateParticipantResult(existing.id, {
finalPosition,
qualifyingPoints: qualifyingPoints?.toString(),
notes,
});
} else {
// Create new result
return await createParticipantResult({
participantId,
sportsSeasonId,
finalPosition,
qualifyingPoints: qualifyingPoints?.toString(),
notes,
});
}
}