From abaee4fa50cfa5a086f2c58816d7732305d9f5cf Mon Sep 17 00:00:00 2001 From: Diego Arenas Date: Mon, 16 Nov 2026 18:25:50 -0300 Subject: [PATCH] feat(persistence): audit tie-break resolutions --- .../sqlite-monthly-league-repository.test.ts | 232 ++++++++++++++++- .../sqlite-monthly-league-repository.ts | 241 +++++++++++++++++- 2 files changed, 471 insertions(+), 2 deletions(-) diff --git a/src/modules/persistence/sqlite-monthly-league-repository.test.ts b/src/modules/persistence/sqlite-monthly-league-repository.test.ts index bade9f3..c14792b 100644 --- a/src/modules/persistence/sqlite-monthly-league-repository.test.ts +++ b/src/modules/persistence/sqlite-monthly-league-repository.test.ts @@ -1,4 +1,5 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -7,6 +8,12 @@ import { afterEach, describe, expect, it } from "vitest"; import { createSqliteMonthlyLeagueRepository } from "./sqlite-monthly-league-repository"; import { createSqliteStoreMembershipRepository } from "./sqlite-store-membership-repository"; +async function hashFile(path: string): Promise { + const contents = await readFile(path); + + return createHash("sha256").update(contents).digest("hex"); +} + describe("createSqliteMonthlyLeagueRepository", () => { const temporaryDirectories: string[] = []; @@ -55,6 +62,229 @@ describe("createSqliteMonthlyLeagueRepository", () => { reopenedLeagueRepository.close(); }); + it("persists an auditable tie-break resolution after reopening", async () => { + const directory = await mkdtemp(join(tmpdir(), "league-points-")); + temporaryDirectories.push(directory); + const databasePath = join(directory, "league-points.sqlite"); + const storeRepository = + createSqliteStoreMembershipRepository(databasePath); + + storeRepository.createStore({ id: "STORE-1", name: "Local League" }); + storeRepository.addOrganizerMembership({ + storeId: "STORE-1", + organizerId: "ORGANIZER-1", + }); + storeRepository.close(); + + const firstLeagueRepository = + createSqliteMonthlyLeagueRepository(databasePath); + + firstLeagueRepository.createMonthlyLeague({ + storeId: "STORE-1", + leagueMonth: "2026-11", + tieBreakPolicy: "PLAYOFF_MATCH", + }); + firstLeagueRepository.recordTieBreakResolution({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0001", "P0002"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }); + firstLeagueRepository.close(); + + const reopenedLeagueRepository = + createSqliteMonthlyLeagueRepository(databasePath); + + expect( + reopenedLeagueRepository.findTieBreakResolutionHistory( + "STORE-1", + "2026-11", + ), + ).toEqual([ + { + revision: 1, + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0001", "P0002"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }, + ]); + + reopenedLeagueRepository.close(); + }); + + it("retains the original resolution when an organizer records a correction", async () => { + const directory = await mkdtemp(join(tmpdir(), "league-points-")); + temporaryDirectories.push(directory); + const databasePath = join(directory, "league-points.sqlite"); + const storeRepository = + createSqliteStoreMembershipRepository(databasePath); + + storeRepository.createStore({ id: "STORE-1", name: "Local League" }); + storeRepository.addOrganizerMembership({ + storeId: "STORE-1", + organizerId: "ORGANIZER-1", + }); + storeRepository.close(); + + const leagueRepository = + createSqliteMonthlyLeagueRepository(databasePath); + + leagueRepository.createMonthlyLeague({ + storeId: "STORE-1", + leagueMonth: "2026-11", + tieBreakPolicy: "PLAYOFF_MATCH", + }); + leagueRepository.recordTieBreakResolution({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0001", "P0002"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }); + leagueRepository.recordTieBreakResolution({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "PLAYOFF_MATCH", + orderedPlayerIds: ["P0002", "P0001"], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T21:00:00.000Z", + }); + + expect( + leagueRepository.findTieBreakResolutionHistory( + "STORE-1", + "2026-11", + ), + ).toEqual([ + { + revision: 1, + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0001", "P0002"], + fallbackReason: "One player could not attend the playoff.", + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }, + { + revision: 2, + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "PLAYOFF_MATCH", + resolutionMethod: "PLAYOFF_MATCH", + orderedPlayerIds: ["P0002", "P0001"], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T21:00:00.000Z", + }, + ]); + + leagueRepository.close(); + }); + + it("rejects a resolution whose configured policy differs from the league", async () => { + const directory = await mkdtemp(join(tmpdir(), "league-points-")); + temporaryDirectories.push(directory); + const databasePath = join(directory, "league-points.sqlite"); + const storeRepository = + createSqliteStoreMembershipRepository(databasePath); + + storeRepository.createStore({ id: "STORE-1", name: "Local League" }); + storeRepository.addOrganizerMembership({ + storeId: "STORE-1", + organizerId: "ORGANIZER-1", + }); + storeRepository.close(); + + const leagueRepository = + createSqliteMonthlyLeagueRepository(databasePath); + + leagueRepository.createMonthlyLeague({ + storeId: "STORE-1", + leagueMonth: "2026-11", + tieBreakPolicy: "PLAYOFF_MATCH", + }); + + expect(() => + leagueRepository.recordTieBreakResolution({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: ["P0001", "P0002"], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }), + ).toThrow(); + expect( + leagueRepository.findTieBreakResolutionHistory( + "STORE-1", + "2026-11", + ), + ).toEqual([]); + + leagueRepository.close(); + }); + + it("rejects an empty audited final order atomically", async () => { + const directory = await mkdtemp(join(tmpdir(), "league-points-")); + temporaryDirectories.push(directory); + const databasePath = join(directory, "league-points.sqlite"); + const storeRepository = + createSqliteStoreMembershipRepository(databasePath); + + storeRepository.createStore({ id: "STORE-1", name: "Local League" }); + storeRepository.addOrganizerMembership({ + storeId: "STORE-1", + organizerId: "ORGANIZER-1", + }); + storeRepository.close(); + + const leagueRepository = + createSqliteMonthlyLeagueRepository(databasePath); + + leagueRepository.createMonthlyLeague({ + storeId: "STORE-1", + leagueMonth: "2026-11", + tieBreakPolicy: "MANUAL_ORDER", + }); + const hashBeforeRejection = await hashFile(databasePath); + + expect(() => + leagueRepository.recordTieBreakResolution({ + storeId: "STORE-1", + leagueMonth: "2026-11", + configuredPolicy: "MANUAL_ORDER", + resolutionMethod: "MANUAL_ORDER", + orderedPlayerIds: [], + recordedByOrganizerId: "ORGANIZER-1", + recordedAt: "2026-11-30T20:00:00.000Z", + }), + ).toThrow("INVALID_TIE_BREAK_ORDER"); + expect( + leagueRepository.findTieBreakResolutionHistory( + "STORE-1", + "2026-11", + ), + ).toEqual([]); + expect(await hashFile(databasePath)).toBe(hashBeforeRejection); + + leagueRepository.close(); + }); + it("persists a tournament's original and effective dates after reopening", async () => { const directory = await mkdtemp(join(tmpdir(), "league-points-")); temporaryDirectories.push(directory); diff --git a/src/modules/persistence/sqlite-monthly-league-repository.ts b/src/modules/persistence/sqlite-monthly-league-repository.ts index 47864d1..7fb9343 100644 --- a/src/modules/persistence/sqlite-monthly-league-repository.ts +++ b/src/modules/persistence/sqlite-monthly-league-repository.ts @@ -29,6 +29,22 @@ export type PlayerTournamentHistoryQuery = Readonly<{ originalScheduledDate: string; }>; +export type TieBreakResolutionRecord = Readonly<{ + storeId: string; + leagueMonth: string; + configuredPolicy: TieBreakPolicy; + resolutionMethod: TieBreakPolicy; + orderedPlayerIds: ReadonlyArray; + fallbackReason?: string; + recordedByOrganizerId: string; + recordedAt: string; +}>; + +export type TieBreakResolutionRevision = TieBreakResolutionRecord & + Readonly<{ + revision: number; + }>; + type CreateMonthlyLeagueResult = | Readonly<{ ok: true }> | Readonly<{ @@ -67,6 +83,11 @@ export interface MonthlyLeagueRepository { leagueMonth: string, ): ReadonlyArray; countPlayerTournamentsBefore(query: PlayerTournamentHistoryQuery): number; + recordTieBreakResolution(resolution: TieBreakResolutionRecord): void; + findTieBreakResolutionHistory( + storeId: string, + leagueMonth: string, + ): ReadonlyArray; close(): void; } @@ -129,9 +150,73 @@ export function createSqliteMonthlyLeagueRepository( PRIMARY KEY (tournament_id, player_id), FOREIGN KEY (tournament_id, invited_by_player_id) REFERENCES tournament_participants (tournament_id, player_id) - DEFERRABLE INITIALLY DEFERRED + DEFERRABLE INITIALLY DEFERRED + ) STRICT; + + CREATE TABLE IF NOT EXISTS tie_break_resolution_revisions ( + store_id TEXT NOT NULL, + league_month TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision > 0), + configured_policy TEXT NOT NULL CHECK ( + configured_policy IN ('MANUAL_ORDER', 'PLAYOFF_MATCH') + ), + resolution_method TEXT NOT NULL CHECK ( + resolution_method IN ('MANUAL_ORDER', 'PLAYOFF_MATCH') + ), + fallback_reason TEXT, + recorded_by_organizer_id TEXT NOT NULL, + recorded_at TEXT NOT NULL, + PRIMARY KEY (store_id, league_month, revision), + FOREIGN KEY (store_id, league_month) + REFERENCES monthly_leagues (store_id, league_month) + ON DELETE CASCADE, + FOREIGN KEY (store_id, recorded_by_organizer_id) + REFERENCES organizer_memberships (store_id, organizer_id), + CHECK ( + ( + configured_policy = 'MANUAL_ORDER' + AND resolution_method = 'MANUAL_ORDER' + AND fallback_reason IS NULL + ) OR ( + configured_policy = 'PLAYOFF_MATCH' + AND resolution_method = 'PLAYOFF_MATCH' + AND fallback_reason IS NULL + ) OR ( + configured_policy = 'PLAYOFF_MATCH' + AND resolution_method = 'MANUAL_ORDER' + AND length(trim(fallback_reason)) > 0 + ) + ) + ) STRICT; + + CREATE TABLE IF NOT EXISTS tie_break_resolution_players ( + store_id TEXT NOT NULL, + league_month TEXT NOT NULL, + revision INTEGER NOT NULL, + order_index INTEGER NOT NULL CHECK (order_index >= 0), + player_id TEXT NOT NULL, + PRIMARY KEY (store_id, league_month, revision, order_index), + UNIQUE (store_id, league_month, revision, player_id), + FOREIGN KEY (store_id, league_month, revision) + REFERENCES tie_break_resolution_revisions ( + store_id, + league_month, + revision + ) ON DELETE CASCADE ) STRICT; + CREATE TRIGGER IF NOT EXISTS validate_tie_break_resolution_policy + BEFORE INSERT ON tie_break_resolution_revisions + WHEN NEW.configured_policy <> ( + SELECT tie_break_policy + FROM monthly_leagues + WHERE store_id = NEW.store_id + AND league_month = NEW.league_month + ) + BEGIN + SELECT RAISE(ABORT, 'TIE_BREAK_POLICY_MISMATCH'); + END; + CREATE TRIGGER IF NOT EXISTS validate_tournament_original_month BEFORE INSERT ON tournament_details WHEN substr(NEW.original_scheduled_date, 1, 7) <> ( @@ -304,6 +389,81 @@ export function createSqliteMonthlyLeagueRepository( }); } + function findTieBreakResolutionHistory( + storeId: string, + leagueMonth: string, + ): ReadonlyArray { + return database + .prepare(` + SELECT + revision, + configured_policy AS configuredPolicy, + resolution_method AS resolutionMethod, + fallback_reason AS fallbackReason, + recorded_by_organizer_id AS recordedByOrganizerId, + recorded_at AS recordedAt + FROM tie_break_resolution_revisions + WHERE store_id = ? AND league_month = ? + ORDER BY revision ASC + `) + .all(storeId, leagueMonth) + .map((row): TieBreakResolutionRevision => { + if ( + typeof row.revision !== "number" || + !Number.isSafeInteger(row.revision) || + (row.configuredPolicy !== "MANUAL_ORDER" && + row.configuredPolicy !== "PLAYOFF_MATCH") || + (row.resolutionMethod !== "MANUAL_ORDER" && + row.resolutionMethod !== "PLAYOFF_MATCH") || + (row.fallbackReason !== null && + typeof row.fallbackReason !== "string") || + typeof row.recordedByOrganizerId !== "string" || + typeof row.recordedAt !== "string" + ) { + throw new Error("INVALID_TIE_BREAK_RESOLUTION_ROW"); + } + + const orderedPlayerIds = database + .prepare(` + SELECT player_id AS playerId + FROM tie_break_resolution_players + WHERE store_id = ? + AND league_month = ? + AND revision = ? + ORDER BY order_index ASC + `) + .all(storeId, leagueMonth, row.revision) + .map((playerRow) => { + if (typeof playerRow.playerId !== "string") { + throw new Error("INVALID_TIE_BREAK_RESOLUTION_PLAYER_ROW"); + } + + return playerRow.playerId; + }); + + const resolution: Omit< + TieBreakResolutionRevision, + "fallbackReason" + > = { + revision: row.revision, + storeId, + leagueMonth, + configuredPolicy: row.configuredPolicy, + resolutionMethod: row.resolutionMethod, + orderedPlayerIds, + recordedByOrganizerId: row.recordedByOrganizerId, + recordedAt: row.recordedAt, + }; + + return row.fallbackReason === null + ? resolution + : { + ...resolution, + fallbackReason: row.fallbackReason, + }; + }); + } + return { createMonthlyLeague(league: MonthlyLeague) { const result = database @@ -457,6 +617,85 @@ export function createSqliteMonthlyLeagueRepository( return row.tournamentCount; }, + recordTieBreakResolution(resolution: TieBreakResolutionRecord) { + if (resolution.orderedPlayerIds.length === 0) { + throw new Error("INVALID_TIE_BREAK_ORDER"); + } + + database.exec("BEGIN IMMEDIATE"); + + try { + const row = database + .prepare(` + SELECT COALESCE(MAX(revision), 0) AS latestRevision + FROM tie_break_resolution_revisions + WHERE store_id = ? AND league_month = ? + `) + .get(resolution.storeId, resolution.leagueMonth); + + if ( + row === undefined || + typeof row.latestRevision !== "number" || + !Number.isSafeInteger(row.latestRevision) + ) { + throw new Error("INVALID_TIE_BREAK_RESOLUTION_REVISION"); + } + + const revision = row.latestRevision + 1; + + database + .prepare(` + INSERT INTO tie_break_resolution_revisions ( + store_id, + league_month, + revision, + configured_policy, + resolution_method, + fallback_reason, + recorded_by_organizer_id, + recorded_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `) + .run( + resolution.storeId, + resolution.leagueMonth, + revision, + resolution.configuredPolicy, + resolution.resolutionMethod, + resolution.fallbackReason ?? null, + resolution.recordedByOrganizerId, + resolution.recordedAt, + ); + + const insertPlayer = database.prepare(` + INSERT INTO tie_break_resolution_players ( + store_id, + league_month, + revision, + order_index, + player_id + ) VALUES (?, ?, ?, ?, ?) + `); + + resolution.orderedPlayerIds.forEach((playerId, orderIndex) => { + insertPlayer.run( + resolution.storeId, + resolution.leagueMonth, + revision, + orderIndex, + playerId, + ); + }); + + database.exec("COMMIT"); + } catch (error) { + database.exec("ROLLBACK"); + throw error; + } + }, + + findTieBreakResolutionHistory, + close() { database.close(); },