brackt/app/lib/__tests__/corona-states.test.ts

136 lines
4 KiB
TypeScript
Raw Normal View History

Record final-placement points in the score-events ledger qualifying_points (golf, tennis, CS2) and season_standings (F1) award all of their points in one step at finalization, so they produce no per-match deltas. recordMatchScoreEvents is bracket-only and fires from match processing, which meant these sports were never written to team_score_events at all and silently never appeared in Recent Scores. Add recordFinalPlacementScoreEvents, called from finalizeQualifyingPoints and processSeasonStandings. It writes one row per team at the ledger's event-level grain, carrying that team's summed award and every contributing participant, with points from calculatePickPoints so a tied golfer contributes the same split award the standings show. The row is anchored to a real scoring event rather than a null one: the event-level unique index is (teamId, seasonId, scoringEventId) and Postgres treats NULLs as distinct, so a null anchor would duplicate rows on every re-finalization instead of upserting. When no anchor can be resolved the ledger write is skipped, which leaves standings unaffected. Adds regression coverage for the two screens that had diverged — getTeamScoreBreakdown and computeCoronaStates — including an assertion that the team page's actualPoints equals calculateTeamScore's totalPoints for the same roster, and cases proving undrafted participants still count toward a tie span. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019LZLF1PAfeKdpYog3NKtyz
2026-08-07 07:38:26 +00:00
import { describe, it, expect } from "vitest";
import { computeCoronaStates } from "../corona-states";
const RULES = {
pointsFor1st: 100, pointsFor2nd: 70, pointsFor3rd: 50, pointsFor4th: 40,
pointsFor5th: 25, pointsFor6th: 25, pointsFor7th: 15, pointsFor8th: 15,
};
function pick(id: string, scoringPattern: string | null, sportsSeasonId = "ss-1") {
return { participant: { id, sportsSeasonId }, scoringPattern };
}
function results(
rows: Array<{ participantId: string; finalPosition: number | null; isPartialScore?: boolean }>
) {
return new Map(
rows.map((r) => [r.participantId, { isPartialScore: false, ...r }])
);
}
describe("computeCoronaStates", () => {
const noTies = new Map<string, Map<number, number>>();
it("splits points for a tied qualifying_points pick", () => {
// Rahm tied for 8th. 9th is outside the scoring range and contributes 0,
// so (15 + 0) / 2 = 7.5 → 8. Before the shared helper this path awarded the
// full 15 while the standings awarded the split — the reported bug.
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 8 }]),
new Map(),
RULES,
RULES.pointsFor1st,
new Map([["ss-1", new Map([[8, 2]])]])
);
expect(states.rahm).toEqual({
type: "scored",
points: 8,
brightness: 8 / 100,
});
});
it("awards the full value when the placement is untied", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 8 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toMatchObject({ type: "scored", points: 15 });
});
it("still averages bracket tiers via the bracket template", () => {
const states = computeCoronaStates(
[pick("team-a", "playoff_bracket")],
results([{ participantId: "team-a", finalPosition: 5 }]),
new Map([["ss-1", null]]),
RULES,
RULES.pointsFor1st,
noTies
);
// Four QF losers share 5th-8th: (25 + 25 + 15 + 15) / 4 = 20
expect(states["team-a"]).toMatchObject({ type: "scored", points: 20 });
});
it("scores other patterns straight off the placement", () => {
const states = computeCoronaStates(
[pick("driver", "season_standings")],
results([{ participantId: "driver", finalPosition: 2 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.driver).toMatchObject({ type: "scored", points: 70 });
});
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
it("splits a tied season_standings placement", () => {
const states = computeCoronaStates(
[pick("driver", "season_standings")],
results([{ participantId: "driver", finalPosition: 3 }]),
new Map(),
RULES,
RULES.pointsFor1st,
new Map([["ss-1", new Map([[3, 2]])]])
);
expect(states.driver).toMatchObject({ type: "scored", points: 45 });
});
Record final-placement points in the score-events ledger qualifying_points (golf, tennis, CS2) and season_standings (F1) award all of their points in one step at finalization, so they produce no per-match deltas. recordMatchScoreEvents is bracket-only and fires from match processing, which meant these sports were never written to team_score_events at all and silently never appeared in Recent Scores. Add recordFinalPlacementScoreEvents, called from finalizeQualifyingPoints and processSeasonStandings. It writes one row per team at the ledger's event-level grain, carrying that team's summed award and every contributing participant, with points from calculatePickPoints so a tied golfer contributes the same split award the standings show. The row is anchored to a real scoring event rather than a null one: the event-level unique index is (teamId, seasonId, scoringEventId) and Postgres treats NULLs as distinct, so a null anchor would duplicate rows on every re-finalization instead of upserting. When no anchor can be resolved the ledger write is skipped, which leaves standings unaffected. Adds regression coverage for the two screens that had diverged — getTeamScoreBreakdown and computeCoronaStates — including an assertion that the team page's actualPoints equals calculateTeamScore's totalPoints for the same roster, and cases proving undrafted participants still count toward a tie span. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019LZLF1PAfeKdpYog3NKtyz
2026-08-07 07:38:26 +00:00
it("marks picks with no result as pending", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toEqual({ type: "pending" });
});
it("marks a finalized zero placement as eliminated", () => {
const states = computeCoronaStates(
[pick("rahm", "qualifying_points")],
results([{ participantId: "rahm", finalPosition: 0 }]),
new Map(),
RULES,
RULES.pointsFor1st,
noTies
);
expect(states.rahm).toEqual({ type: "eliminated", points: 0 });
});
it("keeps brightness within range when a tier exceeds maxPoints", () => {
const states = computeCoronaStates(
[pick("champ", "season_standings")],
results([{ participantId: "champ", finalPosition: 1 }]),
new Map(),
RULES,
10, // deliberately below the 1st-place award
noTies
);
expect(states.champ).toMatchObject({ brightness: 1 });
});
});