From fd942e6db6d6d34f8bf3112af575dabddf88b74f Mon Sep 17 00:00:00 2001 From: Diego Arenas Date: Mon, 16 Nov 2026 18:26:01 -0300 Subject: [PATCH] feat(ranking): build persisted monthly rankings --- .../build-store-monthly-ranking.test.ts | 284 ++++++++++++++++++ .../ranking/build-store-monthly-ranking.ts | 236 +++++++++++++++ src/modules/ranking/resolve-top-cut-tie.ts | 4 +- 3 files changed, 522 insertions(+), 2 deletions(-) create mode 100644 src/modules/ranking/build-store-monthly-ranking.test.ts create mode 100644 src/modules/ranking/build-store-monthly-ranking.ts diff --git a/src/modules/ranking/build-store-monthly-ranking.test.ts b/src/modules/ranking/build-store-monthly-ranking.test.ts new file mode 100644 index 0000000..4506285 --- /dev/null +++ b/src/modules/ranking/build-store-monthly-ranking.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildStoreMonthlyRanking } from "./build-store-monthly-ranking"; + +describe("buildStoreMonthlyRanking", () => { + it("builds a ranking from tournaments in the requested store and month", () => { + const findTournamentsByLeague = vi.fn().mockReturnValue([ + { + id: "TOURNAMENT-1", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-04", + effectiveDate: "2026-11-04", + participants: [ + { + playerId: "P0001", + placement: 1, + }, + ], + }, + ]); + + const ranking = buildStoreMonthlyRanking( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + }, + { + findTournamentsByLeague, + countPlayerTournamentsBefore: vi.fn(), + findTieBreakResolutionHistory: vi.fn().mockReturnValue([]), + }, + ); + + expect(findTournamentsByLeague).toHaveBeenCalledExactlyOnceWith( + "STORE-1", + "2026-11", + ); + expect(ranking).toEqual({ + storeId: "STORE-1", + leagueMonth: "2026-11", + entries: [ + { + playerId: "P0001", + totalPoints: 15, + position: 1, + topCutStatus: "QUALIFIED", + }, + ], + }); + }); + + it("adds invitation points when the invited participant is new at the store", () => { + const findTournamentsByLeague = vi.fn().mockReturnValue([ + { + id: "TOURNAMENT-1", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-04", + effectiveDate: "2026-11-04", + participants: [ + { + playerId: "P0001", + placement: 1, + }, + { + playerId: "P0002", + placement: 2, + invitedByPlayerId: "P0001", + }, + ], + }, + ]); + const countPlayerTournamentsBefore = vi.fn().mockReturnValue(0); + const repository = { + findTournamentsByLeague, + countPlayerTournamentsBefore, + findTieBreakResolutionHistory: vi.fn().mockReturnValue([]), + }; + + const ranking = buildStoreMonthlyRanking( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + }, + repository, + ); + + expect(countPlayerTournamentsBefore).toHaveBeenCalledExactlyOnceWith({ + storeId: "STORE-1", + playerId: "P0002", + originalScheduledDate: "2026-11-04", + }); + expect(ranking.entries).toEqual([ + { + playerId: "P0001", + totalPoints: 18, + position: 1, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0002", + totalPoints: 5, + position: 2, + topCutStatus: "QUALIFIED", + }, + ]); + }); + + it("adds continuity points for attending the original Wednesday and Friday pair", () => { + const findTournamentsByLeague = vi.fn().mockReturnValue([ + { + id: "WEDNESDAY-TOURNAMENT", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-04", + effectiveDate: "2026-11-04", + participants: [ + { + playerId: "P0001", + placement: 1, + }, + ], + }, + { + id: "FRIDAY-TOURNAMENT", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-06", + effectiveDate: "2026-11-08", + participants: [ + { + playerId: "P0001", + placement: 1, + }, + ], + }, + ]); + + const ranking = buildStoreMonthlyRanking( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + }, + { + findTournamentsByLeague, + countPlayerTournamentsBefore: vi.fn(), + findTieBreakResolutionHistory: vi.fn().mockReturnValue([]), + }, + ); + + expect(ranking.entries).toEqual([ + { + playerId: "P0001", + totalPoints: 32, + position: 1, + topCutStatus: "QUALIFIED", + }, + ]); + }); + + it("does not award continuity when Wednesday belongs to the previous month", () => { + const findTournamentsByLeague = vi.fn().mockReturnValue([ + { + id: "FRIDAY-TOURNAMENT", + storeId: "STORE-1", + leagueMonth: "2026-05", + originalScheduledDate: "2026-05-01", + effectiveDate: "2026-05-01", + participants: [ + { + playerId: "P0001", + placement: 1, + }, + ], + }, + ]); + + const ranking = buildStoreMonthlyRanking( + { + storeId: "STORE-1", + leagueMonth: "2026-05", + }, + { + findTournamentsByLeague, + countPlayerTournamentsBefore: vi.fn(), + findTieBreakResolutionHistory: vi.fn().mockReturnValue([]), + }, + ); + + expect(ranking.entries).toEqual([ + { + playerId: "P0001", + totalPoints: 15, + position: 1, + topCutStatus: "QUALIFIED", + }, + ]); + }); + + it("applies the latest audited resolution to the Top Cut boundary tie", () => { + const participants = Array.from({ length: 9 }, (_, index) => ({ + playerId: `P${String(index + 1).padStart(4, "0")}`, + placement: index + 1, + })); + const findTournamentsByLeague = vi.fn().mockReturnValue([ + { + id: "TOURNAMENT-1", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-04", + effectiveDate: "2026-11-04", + participants, + }, + ]); + const findTieBreakResolutionHistory = vi.fn().mockReturnValue([ + { + revision: 1, + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0005", "P0006", "P0007", "P0008", "P0009"], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }, + { + revision: 2, + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0009", "P0008", "P0007", "P0006", "P0005"], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T21:00:00.000Z", + }, + ]); + + const ranking = buildStoreMonthlyRanking( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + }, + { + findTournamentsByLeague, + countPlayerTournamentsBefore: vi.fn(), + findTieBreakResolutionHistory, + }, + ); + + expect(ranking.entries.slice(4)).toEqual([ + { + playerId: "P0009", + totalPoints: 5, + position: 5, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0008", + totalPoints: 5, + position: 6, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0007", + totalPoints: 5, + position: 7, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0006", + totalPoints: 5, + position: 8, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0005", + totalPoints: 5, + position: 9, + topCutStatus: "NOT_QUALIFIED", + }, + ]); + }); +}); diff --git a/src/modules/ranking/build-store-monthly-ranking.ts b/src/modules/ranking/build-store-monthly-ranking.ts new file mode 100644 index 0000000..9fcbef1 --- /dev/null +++ b/src/modules/ranking/build-store-monthly-ranking.ts @@ -0,0 +1,236 @@ +import type { + MonthlyLeagueRepository, + TieBreakResolutionRevision, +} from "../persistence/sqlite-monthly-league-repository"; +import { calculateInvitationPoints } from "../scoring/calculate-invitation-points"; +import { calculateTournamentPoints } from "../scoring/calculate-tournament-points"; +import { calculateWeeklyContinuityPoints } from "../scoring/calculate-weekly-continuity-points"; +import { + calculateMonthlyRanking, + type MonthlyRanking, +} from "./calculate-monthly-ranking"; +import { resolveTopCutTie } from "./resolve-top-cut-tie"; + +export type BuildStoreMonthlyRankingInput = Readonly<{ + storeId: string; + leagueMonth: string; +}>; + +export type StoreMonthlyRanking = MonthlyRanking & + Readonly<{ + storeId: string; + }>; + +export type ProvisionalStoreRankingRepository = Pick< + MonthlyLeagueRepository, + | "countPlayerTournamentsBefore" + | "findTournamentsByLeague" +>; + +type StoreRankingRepository = ProvisionalStoreRankingRepository & + Pick; + +export function buildStoreMonthlyRanking( + input: BuildStoreMonthlyRankingInput, + repository: StoreRankingRepository, +): StoreMonthlyRanking { + const provisionalRanking = buildProvisionalStoreMonthlyRanking( + input, + repository, + ); + const resolutionHistory = repository.findTieBreakResolutionHistory( + input.storeId, + input.leagueMonth, + ); + + return { + storeId: input.storeId, + ...applyLatestTieBreakResolution(provisionalRanking, resolutionHistory), + }; +} + +export function buildProvisionalStoreMonthlyRanking( + input: BuildStoreMonthlyRankingInput, + repository: ProvisionalStoreRankingRepository, +): StoreMonthlyRanking { + const tournaments = repository.findTournamentsByLeague( + input.storeId, + input.leagueMonth, + ); + const weeklyAttendanceByPlayer = new Map< + string, + Map< + string, + { + attendedWednesdayTournament: boolean; + attendedFridayTournament: boolean; + } + > + >(); + + const tournamentPoints = tournaments.flatMap((tournament) => { + const playerCount = tournament.participants.length; + const scheduledDay = getUtcDay(tournament.originalScheduledDate); + const schedulePairKey = getSchedulePairKey( + tournament.originalScheduledDate, + scheduledDay, + ); + + return tournament.participants.map((participant) => { + const playerAttendance = + weeklyAttendanceByPlayer.get(participant.playerId) ?? new Map(); + const weeklyAttendance = playerAttendance.get(schedulePairKey) ?? { + attendedWednesdayTournament: false, + attendedFridayTournament: false, + }; + + if (scheduledDay === 3) { + weeklyAttendance.attendedWednesdayTournament = true; + } + + if (scheduledDay === 5) { + weeklyAttendance.attendedFridayTournament = true; + } + + playerAttendance.set(schedulePairKey, weeklyAttendance); + weeklyAttendanceByPlayer.set(participant.playerId, playerAttendance); + + const basePoints = calculateTournamentPoints({ + placement: participant.placement, + playerCount, + }).total; + const invitedPlayers = tournament.participants + .filter( + (candidate) => + candidate.invitedByPlayerId === participant.playerId, + ) + .map((invitedPlayer) => ({ + playerId: invitedPlayer.playerId, + previousTournamentCountAtStore: + repository.countPlayerTournamentsBefore({ + storeId: input.storeId, + playerId: invitedPlayer.playerId, + originalScheduledDate: tournament.originalScheduledDate, + }), + })); + const invitationPoints = calculateInvitationPoints({ + inviterPlayerId: participant.playerId, + invitedPlayers, + }); + + return { + playerId: participant.playerId, + originalScheduledDate: tournament.originalScheduledDate, + points: basePoints + invitationPoints, + }; + }); + }); + const continuityPoints = Array.from( + weeklyAttendanceByPlayer.entries(), + ).flatMap(([playerId, attendanceBySchedulePair]) => + Array.from(attendanceBySchedulePair.entries()).map( + ([originalScheduledDate, attendance]) => ({ + playerId, + originalScheduledDate, + points: calculateWeeklyContinuityPoints(attendance), + }), + ), + ); + const provisionalRanking = calculateMonthlyRanking({ + leagueMonth: input.leagueMonth, + tournamentPoints: [...tournamentPoints, ...continuityPoints], + }); + + return { + storeId: input.storeId, + ...provisionalRanking, + }; +} + +function applyLatestTieBreakResolution( + ranking: MonthlyRanking, + resolutionHistory: ReadonlyArray, +): MonthlyRanking { + const latestResolution = resolutionHistory.at(-1); + const tiedEntries = ranking.entries.filter( + (entry) => entry.topCutStatus === "TIE_BREAK_PENDING", + ); + const firstTiedEntry = tiedEntries[0]; + + if (latestResolution === undefined || firstTiedEntry === undefined) { + return ranking; + } + + const tie = { + tiedPlayerIds: tiedEntries.map((entry) => entry.playerId), + startingPosition: firstTiedEntry.position, + }; + const resolutionInput = + latestResolution.resolutionMethod === "PLAYOFF_MATCH" + ? { + ...tie, + configuredPolicy: "PLAYOFF_MATCH" as const, + resolutionMethod: "PLAYOFF_MATCH" as const, + playoffOrder: latestResolution.orderedPlayerIds, + } + : latestResolution.configuredPolicy === "PLAYOFF_MATCH" + ? { + ...tie, + configuredPolicy: "PLAYOFF_MATCH" as const, + resolutionMethod: "MANUAL_ORDER" as const, + manualOrder: latestResolution.orderedPlayerIds, + fallbackReason: latestResolution.fallbackReason ?? "", + } + : { + ...tie, + configuredPolicy: "MANUAL_ORDER" as const, + resolutionMethod: "MANUAL_ORDER" as const, + manualOrder: latestResolution.orderedPlayerIds, + }; + const resolution = resolveTopCutTie(resolutionInput); + + if (!resolution.ok) { + throw new Error( + `INVALID_PERSISTED_TIE_BREAK_RESOLUTION: ${resolution.error}`, + ); + } + + const resolvedPlayerById = new Map( + resolution.resolvedPlayers.map((player) => [player.playerId, player]), + ); + const entries = ranking.entries + .map((entry) => { + const resolvedPlayer = resolvedPlayerById.get(entry.playerId); + + return resolvedPlayer === undefined + ? entry + : { + ...entry, + position: resolvedPlayer.finalPosition, + topCutStatus: resolvedPlayer.topCutStatus, + }; + }) + .sort((firstEntry, secondEntry) => + firstEntry.position - secondEntry.position, + ); + + return { + ...ranking, + entries, + }; +} + +function getUtcDay(date: string): number { + return new Date(`${date}T00:00:00Z`).getUTCDay(); +} + +function getSchedulePairKey(date: string, scheduledDay: number): string { + if (scheduledDay !== 5) { + return date; + } + + const wednesday = new Date(`${date}T00:00:00Z`); + wednesday.setUTCDate(wednesday.getUTCDate() - 2); + + return wednesday.toISOString().slice(0, 10); +} diff --git a/src/modules/ranking/resolve-top-cut-tie.ts b/src/modules/ranking/resolve-top-cut-tie.ts index af68dd1..f43065b 100644 --- a/src/modules/ranking/resolve-top-cut-tie.ts +++ b/src/modules/ranking/resolve-top-cut-tie.ts @@ -33,7 +33,7 @@ type ManualFallbackInput = fallbackReason: string; }>; -type ResolveTopCutTieInput = +export type ResolveTopCutTieInput = | PlayoffMatchInput | ManualOrderInput | ManualFallbackInput; @@ -44,7 +44,7 @@ type ResolvedPlayer = Readonly<{ topCutStatus: TopCutStatus; }>; -type ResolveTopCutTieResult = +export type ResolveTopCutTieResult = | Readonly<{ ok: true; resolvedPlayers: ReadonlyArray;