From 46c4975f79983093e2d83007304b21e2b132a3e7 Mon Sep 17 00:00:00 2001 From: Diego Arenas Date: Mon, 16 Nov 2026 18:26:13 -0300 Subject: [PATCH] feat(ranking): record audited tie resolutions --- README.md | 10 +- .../record-store-tie-break-resolution.test.ts | 151 ++++++++++++++++++ .../record-store-tie-break-resolution.ts | 116 ++++++++++++++ 3 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 src/modules/ranking/record-store-tie-break-resolution.test.ts create mode 100644 src/modules/ranking/record-store-tie-break-resolution.ts diff --git a/README.md b/README.md index 712c185..8a96090 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,10 @@ League Points busca convertir estas reglas en una aplicación verificable y mant - La fecha programada original determina el mes de liga, incluso cuando la fecha efectiva corresponde a una reprogramación posterior. - Las consultas de torneos e historial de jugadores siempre están limitadas a una tienda. - Las asignaciones de invitación exigen que ambos jugadores participen en el mismo torneo y prohíben la autoinvitación. +- La clasificación protegida se construye desde los torneos persistidos de una tienda y combina puntos base, invitaciones y continuidad. +- Una pareja miércoles-viernes que cruza el límite del mes no concede puntos de continuidad. +- Las resoluciones de desempate se conservan como revisiones auditadas con orden completo, método, motivo de fallback, organizador y fecha controlada por la aplicación. +- Una corrección agrega una revisión sin sobrescribir las anteriores; la última revisión válida determina el orden final del Top 8. ## Tecnologías @@ -89,17 +93,19 @@ La suite actual cubre: - Persistencia atómica de torneos, fechas, participantes, posiciones e invitaciones. - Aislamiento de torneos e historial de jugadores por tienda y mes de liga. - Validación durable de fechas, posiciones y relaciones entre invitado e invitador. +- Construcción de la clasificación protegida desde torneos persistidos. +- Historial auditable de resoluciones y correcciones de desempate. +- Aplicación de la última resolución válida al empate del límite del Top 8. ## Próximos pasos - Importar resultados de torneos. -- Construir la clasificación mensual desde los torneos persistidos. - Implementar sesiones e invitaciones de acceso para organizadores. - Construir la interfaz pública de clasificación. ## Estado del proyecto -Actualmente, el repositorio contiene la lógica de puntuación, la clasificación mensual, la resolución de desempates y persistencia SQLite para tiendas, membresías, ligas mensuales, torneos, participantes e invitaciones. El flujo que construye la clasificación desde estos datos persistidos y la interfaz web se incorporarán incrementalmente. +Actualmente, el repositorio contiene la lógica de puntuación, la clasificación mensual, la resolución auditable de desempates y persistencia SQLite para tiendas, membresías, ligas mensuales, torneos, participantes e invitaciones. La clasificación protegida ya se construye desde estos datos persistidos; las sesiones, la importación de resultados y la interfaz web se incorporarán incrementalmente. ## Aviso diff --git a/src/modules/ranking/record-store-tie-break-resolution.test.ts b/src/modules/ranking/record-store-tie-break-resolution.test.ts new file mode 100644 index 0000000..27301c1 --- /dev/null +++ b/src/modules/ranking/record-store-tie-break-resolution.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it, vi } from "vitest"; + +import { recordStoreTieBreakResolution } from "./record-store-tie-break-resolution"; + +function createBoundaryTieTournament() { + return { + id: "TOURNAMENT-1", + storeId: "STORE-1", + leagueMonth: "2026-11", + originalScheduledDate: "2026-11-04", + effectiveDate: "2026-11-04", + participants: Array.from({ length: 9 }, (_, index) => ({ + playerId: `P${String(index + 1).padStart(4, "0")}`, + placement: index + 1, + })), + }; +} + +describe("recordStoreTieBreakResolution", () => { + it("resolves and records a justified manual fallback for one store league", () => { + const recordTieBreakResolution = vi.fn(); + const repository = { + recordTieBreakResolution, + now: vi.fn().mockReturnValue("2026-11-30T20:00:00.000Z"), + findTournamentsByLeague: vi + .fn() + .mockReturnValue([createBoundaryTieTournament()]), + countPlayerTournamentsBefore: vi.fn(), + findTieBreakResolutionHistory: vi.fn().mockReturnValue([]), + }; + + const result = recordStoreTieBreakResolution( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + manualOrder: ["P0009", "P0008", "P0007", "P0006", "P0005"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + }, + repository, + ); + + expect(result).toEqual({ + ok: true, + resolvedPlayers: [ + { + playerId: "P0009", + finalPosition: 5, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0008", + finalPosition: 6, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0007", + finalPosition: 7, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0006", + finalPosition: 8, + topCutStatus: "QUALIFIED", + }, + { + playerId: "P0005", + finalPosition: 9, + topCutStatus: "NOT_QUALIFIED", + }, + ], + }); + expect(recordTieBreakResolution).toHaveBeenCalledExactlyOnceWith({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0009", "P0008", "P0007", "P0006", "P0005"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }); + }); + + it("does not persist an incomplete order for the derived tied group", () => { + const recordTieBreakResolution = vi.fn(); + const now = vi.fn().mockReturnValue("2026-11-30T20:00:00.000Z"); + + const result = recordStoreTieBreakResolution( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + manualOrder: ["P0009", "P0008", "P0007", "P0006"], + recordedByOrganizerId: "ORGANIZER-1", + }, + { + recordTieBreakResolution, + now, + findTournamentsByLeague: vi + .fn() + .mockReturnValue([createBoundaryTieTournament()]), + countPlayerTournamentsBefore: vi.fn(), + }, + ); + + expect(result).toEqual({ + ok: false, + error: "INVALID_TIE_BREAK_ORDER", + }); + expect(recordTieBreakResolution).not.toHaveBeenCalled(); + expect(now).not.toHaveBeenCalled(); + }); + + it("does not persist a resolution when no Top Cut tie is pending", () => { + const recordTieBreakResolution = vi.fn(); + const now = vi.fn().mockReturnValue("2026-11-30T20:00:00.000Z"); + + const result = recordStoreTieBreakResolution( + { + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + manualOrder: ["P0001"], + recordedByOrganizerId: "ORGANIZER-1", + }, + { + recordTieBreakResolution, + now, + findTournamentsByLeague: vi.fn().mockReturnValue([ + { + ...createBoundaryTieTournament(), + participants: [{ playerId: "P0001", placement: 1 }], + }, + ]), + countPlayerTournamentsBefore: vi.fn(), + }, + ); + + expect(result).toEqual({ + ok: false, + error: "TIE_BREAK_NOT_PENDING", + }); + expect(recordTieBreakResolution).not.toHaveBeenCalled(); + expect(now).not.toHaveBeenCalled(); + }); +}); diff --git a/src/modules/ranking/record-store-tie-break-resolution.ts b/src/modules/ranking/record-store-tie-break-resolution.ts new file mode 100644 index 0000000..c7780b8 --- /dev/null +++ b/src/modules/ranking/record-store-tie-break-resolution.ts @@ -0,0 +1,116 @@ +import type { MonthlyLeagueRepository } from "../persistence/sqlite-monthly-league-repository"; +import { + buildProvisionalStoreMonthlyRanking, + type ProvisionalStoreRankingRepository, +} from "./build-store-monthly-ranking"; +import { + resolveTopCutTie, + type ResolveTopCutTieInput, + type ResolveTopCutTieResult, +} from "./resolve-top-cut-tie"; + +type AuditMetadata = Readonly<{ + storeId: string; + leagueMonth: string; + recordedByOrganizerId: string; +}>; + +type WithoutDerivedTie = T extends ResolveTopCutTieInput + ? Omit + : never; + +export type RecordStoreTieBreakResolutionInput = WithoutDerivedTie< + ResolveTopCutTieInput +> & + AuditMetadata; + +type TieBreakResolutionRepository = ProvisionalStoreRankingRepository & + Pick & + Readonly<{ + now(): string; + }>; + +export type RecordStoreTieBreakResolutionResult = + | ResolveTopCutTieResult + | Readonly<{ + ok: false; + error: "TIE_BREAK_NOT_PENDING"; + }>; + +export function recordStoreTieBreakResolution( + input: RecordStoreTieBreakResolutionInput, + repository: TieBreakResolutionRepository, +): RecordStoreTieBreakResolutionResult { + const ranking = buildProvisionalStoreMonthlyRanking(input, repository); + const tiedEntries = ranking.entries.filter( + (entry) => entry.topCutStatus === "TIE_BREAK_PENDING", + ); + const firstTiedEntry = tiedEntries[0]; + + if (firstTiedEntry === undefined) { + return { + ok: false, + error: "TIE_BREAK_NOT_PENDING", + }; + } + + const tie = { + tiedPlayerIds: tiedEntries.map((entry) => entry.playerId), + startingPosition: firstTiedEntry.position, + }; + const resolutionInput = + input.resolutionMethod === "PLAYOFF_MATCH" + ? { + ...tie, + configuredPolicy: "PLAYOFF_MATCH" as const, + resolutionMethod: "PLAYOFF_MATCH" as const, + playoffOrder: input.playoffOrder, + } + : input.configuredPolicy === "PLAYOFF_MATCH" + ? { + ...tie, + configuredPolicy: "PLAYOFF_MATCH" as const, + resolutionMethod: "MANUAL_ORDER" as const, + manualOrder: input.manualOrder, + fallbackReason: input.fallbackReason, + } + : { + ...tie, + configuredPolicy: "MANUAL_ORDER" as const, + resolutionMethod: "MANUAL_ORDER" as const, + manualOrder: input.manualOrder, + }; + const result = resolveTopCutTie(resolutionInput); + + if (!result.ok) { + return result; + } + + const orderedPlayerIds = + input.resolutionMethod === "PLAYOFF_MATCH" + ? input.playoffOrder + : input.manualOrder; + const auditRecord = { + storeId: input.storeId, + leagueMonth: input.leagueMonth, + configuredPolicy: input.configuredPolicy, + resolutionMethod: input.resolutionMethod, + orderedPlayerIds, + recordedByOrganizerId: input.recordedByOrganizerId, + recordedAt: repository.now(), + }; + + if ( + input.configuredPolicy === "PLAYOFF_MATCH" && + input.resolutionMethod === "MANUAL_ORDER" + ) { + repository.recordTieBreakResolution({ + ...auditRecord, + fallbackReason: input.fallbackReason, + }); + } else { + repository.recordTieBreakResolution(auditRecord); + } + + return result; +}