brackt/app/models/participant-result.ts
Claude 430526104c Unify tie-split point math across every screen
A participant tied for a scoring placement splits the combined points of
the tied positions. Four code paths computed a pick's points, each
re-implementing the same bracket/qualifying_points/default cascade, and
two of them omitted the qualifying_points arm entirely. A golfer tied for
8th was therefore worth the full 15 points on the team page and draft
board but the split 7.5 in the standings, so a team read 225 on one
screen and 218 on another.

Collapse the cascade into a single calculatePickPoints helper and route
all six call sites through it, backed by one shared getSharedPlacementCounts
loader replacing the two separate tie-count queries. Tie counts span every
participant in the sports season, not just drafted ones, since an
undrafted tie partner still halves the award.

Also round split awards to the nearest whole point in
calculateAveragedPoints. The /rules page states ties are "combined and
split equally among them, rounded to the nearest whole point", and its own
worked example rounds 18.33 down to 18, so this is nearest rather than
ceiling. Season point values are integer columns, making this averaging
the only source of fractional points; rounding here means the standings'
218 is now correct by construction rather than a display artifact, and
per-pick values visibly sum to the team total.

Existing assertions encoding the unrounded results are updated, and the
rules page's two published examples are asserted directly so the code and
the published rule cannot drift apart.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019LZLF1PAfeKdpYog3NKtyz
2026-08-23 01:57:54 +00:00

196 lines
5.9 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,
},
});
}
/**
* 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. Positions <= 0 (no scoring placement) are excluded.
*
* 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>>> {
const counts = new Map<string, Map<number, number>>();
if (sportsSeasonIds.length === 0) return counts;
const db = providedDb || database();
const rows = await db.query.seasonParticipantResults.findMany({
where: inArray(schema.seasonParticipantResults.sportsSeasonId, sportsSeasonIds),
columns: { sportsSeasonId: true, finalPosition: true },
});
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;
}
/**
* 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,
});
}
}