diff --git a/apps/api/package.json b/apps/api/package.json index d6936101..38609455 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -9,6 +9,7 @@ "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts", + "competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts", "auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts", "seed:dev": "ts-node src/seed.ts", "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts index 27d30e4c..b3ac98e8 100644 --- a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts +++ b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts @@ -5,6 +5,7 @@ import { CompetitionBootstrapService, type CompetitionBootstrapMatch, } from './competition-bootstrap.service'; +import type { SeriesDefinition } from './domain/series-graph'; describe('CompetitionBootstrapService', () => { it('creates a deterministic paired-Series Competition and immutable snapshots', async () => { @@ -210,6 +211,40 @@ describe('CompetitionBootstrapService', () => { expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled(); }); + it('gives a configured BO3 grand final three slots without changing the other stage rules', async () => { + const harness = createHarness(); + const service = new CompetitionBootstrapService(harness.connectionService); + const match = matchSnapshot({ + gameMode: 'double-elimination', + teamCount: 4, + gameCount: 5, + }); + match.doubleElimination = { + teamCount: 4, + resetFinalEnabled: true, + grandFinalGameCount: 3, + seeds: [1, 2, 3, 4].map((teamIndex) => ({ + seedNumber: teamIndex, + teamIndex, + })), + }; + + await service.bootstrap(match); + + const { format, seriesGraph } = harness.insertedPayloads[0]; + expect(format).toMatchObject({ + rules: { + upper: { maxGames: 5, winsRequired: 3 }, + lower: { maxGames: 1, winsRequired: 1 }, + grandFinal: { maxGames: 3, winsRequired: 2 }, + resetFinal: { maxGames: 1, winsRequired: 1 }, + }, + }); + expect( + seriesGraph.find(({ code }) => code === 'GF')?.gameSlots, + ).toHaveLength(3); + }); + it('rejects incomplete and duplicate team assignments before opening a transaction', async () => { const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [ [ @@ -451,7 +486,7 @@ interface InsertPayload { legacyTeamIndex: number; seedNumber: number; }>; - seriesGraph: Array<{ code?: string; rule: unknown }>; + seriesGraph: SeriesDefinition[]; [key: string]: any; } diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.ts b/apps/api/src/modules/competition/competition-bootstrap.service.ts index 3304b8b3..4eb1b435 100644 --- a/apps/api/src/modules/competition/competition-bootstrap.service.ts +++ b/apps/api/src/modules/competition/competition-bootstrap.service.ts @@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch { doubleElimination?: { teamCount: 4 | 8; resetFinalEnabled: boolean; + grandFinalGameCount?: 1 | 3 | 5; seeds: Array<{ seedNumber: number; teamIndex: number }>; }; } @@ -514,6 +515,8 @@ function mapMatchFormat( winsRequired: 1, maxGames: 1, }; + const grandFinalGameCount = + match.doubleElimination?.grandFinalGameCount ?? 1; return { type: 'double-elimination', teamCount: teams.length, @@ -525,7 +528,11 @@ function mapMatchFormat( maxGames: match.gameCount, }, lower: { ...bestOfOne }, - grandFinal: { ...bestOfOne }, + grandFinal: { + type: 'first-to', + winsRequired: Math.floor(grandFinalGameCount / 2) + 1, + maxGames: grandFinalGameCount, + }, resetFinal: { ...bestOfOne }, }, }; diff --git a/apps/api/src/modules/competition/competition-command.service.ts b/apps/api/src/modules/competition/competition-command.service.ts index 9a7c86fc..f1c7b8c5 100644 --- a/apps/api/src/modules/competition/competition-command.service.ts +++ b/apps/api/src/modules/competition/competition-command.service.ts @@ -821,7 +821,7 @@ function buildOutbox( }; } -function factForProjection( +export function factForProjection( fact: Readonly>, ): Readonly> { const plain = toPlain(fact) as Readonly>; diff --git a/apps/api/src/modules/competition/competition.schema.ts b/apps/api/src/modules/competition/competition.schema.ts index f7cad25f..7b79fc3d 100644 --- a/apps/api/src/modules/competition/competition.schema.ts +++ b/apps/api/src/modules/competition/competition.schema.ts @@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [ 'game-voided', 'series-adjudicated', 'adjudication-reversed', + 'grand-final-rule-corrected', ] as const; export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number]; @@ -200,6 +201,7 @@ export interface CompetitionFact { adjudicationFactId?: mongoose.Types.ObjectId; decision?: Record; reason?: string; + ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 }; createdAt: Date; updatedAt: Date; } @@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema( adjudicationFactId: { type: Schema.Types.ObjectId }, decision: { type: Schema.Types.Mixed }, reason: { type: String }, + ruleCorrection: { type: Schema.Types.Mixed }, }, { timestamps: true, collection: 'competition_fact' }, ); diff --git a/apps/api/src/modules/competition/domain/competition-projector.ts b/apps/api/src/modules/competition/domain/competition-projector.ts index 4e431d3a..e80ee3a7 100644 --- a/apps/api/src/modules/competition/domain/competition-projector.ts +++ b/apps/api/src/modules/competition/domain/competition-projector.ts @@ -131,7 +131,12 @@ export interface CompetitionProjection { export function projectCompetition( input: ProjectCompetitionInput, ): CompetitionProjection { - assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts); + // The repair commits the corrected graph and its audit fact together. The + // audit fact occupies a revision but is not a game or adjudication. + const resultFacts = input.facts.filter( + (fact) => !isRecord(fact) || fact.type !== 'grand-final-rule-corrected', + ); + assertPrimaryFactTargetsGraph(input.seriesGraph, resultFacts); const teamBySeed = new Map(); const knownTeams = new Set(); for (const team of input.teams) { @@ -169,7 +174,7 @@ export function projectCompetition( teamBySeed, projectedById, ), - facts: input.facts, + facts: resultFacts, active: false, }), ); @@ -188,7 +193,7 @@ export function projectCompetition( projectSeries({ definition: asProjectorDefinition(definition), participants, - facts: input.facts, + facts: resultFacts, }), ); remaining.delete(seriesId); @@ -211,7 +216,7 @@ export function projectCompetition( projectSeries({ definition: asProjectorDefinition(definition), participants, - facts: input.facts, + facts: resultFacts, ...(definition.activation ? { active: false } : {}), }), ); @@ -221,7 +226,7 @@ export function projectCompetition( const gameProjection = projectGamesAndSlots( input.seriesGraph, series, - input.facts, + resultFacts, ); const common = { competitionId: input.competitionId, diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.ts b/apps/api/src/modules/double-elimination/double-elimination.util.ts index fe807410..2e942ab7 100644 --- a/apps/api/src/modules/double-elimination/double-elimination.util.ts +++ b/apps/api/src/modules/double-elimination/double-elimination.util.ts @@ -88,6 +88,7 @@ export interface DoubleEliminationEvent { export interface DoubleEliminationBracket { teamCount: 4 | 8; resetFinalEnabled: boolean; + grandFinalGameCount?: 1 | 3 | 5; resetFinalCreated: boolean; seeds: DoubleEliminationSeed[]; bracketMatches: DoubleEliminationBracketMatch[]; @@ -98,6 +99,7 @@ export interface DoubleEliminationBracket { export interface BuildDoubleEliminationBracketOptions { resetFinalEnabled: boolean; winnerBracketGameCount?: number; + grandFinalGameCount?: 1 | 3 | 5; } export interface DoubleEliminationSeriesRule { @@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket( const bracket: DoubleEliminationBracket = { teamCount: seededTeamIndexes.length, resetFinalEnabled: options.resetFinalEnabled, + ...(options.grandFinalGameCount === undefined + ? {} + : { grandFinalGameCount: options.grandFinalGameCount }), resetFinalCreated: false, seeds, bracketMatches: @@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule( bracketMatchId: string; roundNumber: number; }, - options: { winnerBracketGameCount?: number } = {}, + options: Pick< + BuildDoubleEliminationBracketOptions, + 'winnerBracketGameCount' | 'grandFinalGameCount' + > = {}, ): DoubleEliminationSeriesRule { if (params.bracketSide === 'winner') { return seriesRule(options.winnerBracketGameCount ?? 3); } + if (params.bracketSide === 'grand-final') { + return seriesRule(options.grandFinalGameCount ?? 1); + } return seriesRule(1); } @@ -431,6 +442,7 @@ function rebuildWithSeeds( ): DoubleEliminationBracket { const next = buildDoubleEliminationBracket(teamIndexes, { resetFinalEnabled: bracket.resetFinalEnabled, + grandFinalGameCount: bracket.grandFinalGameCount, }); next.events = [ ...bracket.events, diff --git a/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.spec.ts b/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.spec.ts new file mode 100644 index 00000000..a050f6fd --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.spec.ts @@ -0,0 +1,293 @@ +import mongoose from 'mongoose'; +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { generateSeriesGraph } from '../../../competition/domain/series-graph'; +import { + parseGrandFinalRepairOptions, + planGrandFinalBo3Repair, + repairGrandFinalBo3, +} from './repair-grand-final-bo3'; + +describe('grand final BO3 repair', () => { + it.each([false, true])( + 'keeps game 28 and finishes only after two wins (split: %s)', + (split) => { + const input = finishedTournament(); + const plan = planGrandFinalBo3Repair(input); + + expect(plan.before.phase).toBe('completed'); + expect(plan.preservedGame).toBe(28); + expect(plan.newGameNumbers).toEqual([29, 30]); + expect(plan.projection.games).toEqual(plan.before.games); + expect(plan.projection).toMatchObject({ + phase: 'running', + placements: [], + }); + expect(plan.projection).not.toHaveProperty('outcome'); + expect( + plan.projection.series.find( + ({ seriesId }) => seriesId === plan.seriesId, + ), + ).toMatchObject({ + status: 'in-progress', + entries: [ + { slot: 'A', gameWins: 1 }, + { slot: 'B', gameWins: 0 }, + ], + }); + + const facts = [ + ...input.facts, + { + id: 'rule-audit', + type: 'grand-final-rule-corrected', + seriesId: plan.seriesId, + revision: plan.projection.sourceRevision, + ordinalWithinRevision: 1, + }, + ]; + const replay = () => + projectCompetition({ + ...input, + facts, + revision: facts.length, + format: plan.format, + seriesGraph: plan.seriesGraph, + }); + expect(replay()).toEqual(plan.projection); + + const second = replay().gameSlots.find( + ({ displayNumber }) => displayNumber === 29, + )!; + facts.push(acceptedGame(second, facts.length + 1, split ? 'B' : 'A')); + if (split) { + expect(replay().phase).toBe('running'); + const third = replay().gameSlots.find( + ({ displayNumber }) => displayNumber === 30, + )!; + expect(third.status).toBe('ready'); + facts.push(acceptedGame(third, facts.length + 1, 'A')); + } + const completed = replay(); + expect(completed.phase).toBe('completed'); + expect( + completed.gameSlots.find(({ displayNumber }) => displayNumber === 30) + ?.status, + ).toBe(split ? 'completed' : 'inactive'); + expect(completed.games.at(-1)?.displayNumber).toBe(split ? 30 : 29); + }, + ); + + it('refuses to reopen a bracket that enables a reset final', () => { + const input = finishedTournament(); + expect(() => + planGrandFinalBo3Repair({ + ...input, + format: { ...input.format, resetFinalEnabled: true }, + }), + ).toThrow('no reset or later series'); + }); + + it('requires a target and a reviewed revision before applying', () => { + const target = ['--match-id', '000000000000000000000001', '--env', 'prod']; + expect(parseGrandFinalRepairOptions(target)).toMatchObject({ + apply: false, + }); + expect(() => parseGrandFinalRepairOptions(['--apply', ...target])).toThrow( + '--expected-revision', + ); + expect( + parseGrandFinalRepairOptions([ + '--apply', + ...target, + '--expected-revision', + '23', + ]), + ).toMatchObject({ apply: true, expectedRevision: 23 }); + }); + + it('previews without writes and applies the graph, match status and audit in one transaction', async () => { + const input = finishedTournament(); + const competitionId = new mongoose.Types.ObjectId(input.competitionId); + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const match = { + _id: matchId, + competitionId, + communityId, + gameMode: 'double-elimination', + status: 'finished', + teamBuiltAt: new Date(), + doubleElimination: { resetFinalEnabled: false }, + resultPollState: { state: 'complete' }, + }; + const competition = { + ...input, + _id: competitionId, + schemaVersion: 1, + phase: 'completed', + teams: input.teams.map((team) => ({ + ...team, + teamId: new mongoose.Types.ObjectId(team.teamId), + })), + projection: projectCompetition(input), + }; + const query = (value: unknown) => ({ + session: jest.fn().mockReturnThis(), + lean: jest.fn().mockReturnThis(), + sort: jest.fn().mockReturnThis(), + exec: jest.fn().mockResolvedValue(value), + }); + const update = () => jest.fn(() => query({ matchedCount: 1 })); + const models = { + match: { findById: jest.fn(() => query(match)), updateOne: update() }, + competition: { + findOne: jest.fn(() => query(competition)), + updateOne: update(), + }, + competitionFact: { + find: jest.fn(() => query(input.facts)), + insertMany: jest.fn(), + }, + competitionOutbox: { insertMany: jest.fn() }, + }; + const session = { + withTransaction: jest.fn((run: () => unknown) => run()), + endSession: jest.fn(), + }; + const connections = { + getModel: jest.fn((name: keyof typeof models) => models[name]), + createSession: jest.fn().mockResolvedValue(session), + } as never; + const options = { matchId, nodeEnv: 'prod', apply: false }; + + const preview = await repairGrandFinalBo3(connections, options); + expect(preview).toMatchObject({ + mode: 'dry-run', + preservedGame: 28, + newGameNumbers: [29, 30], + }); + expect(models.match.updateOne).not.toHaveBeenCalled(); + expect(models.competition.updateOne).not.toHaveBeenCalled(); + expect(models.competitionFact.insertMany).not.toHaveBeenCalled(); + expect(models.competitionOutbox.insertMany).not.toHaveBeenCalled(); + + await expect( + repairGrandFinalBo3(connections, { + ...options, + apply: true, + expectedRevision: preview.revisionBefore, + }), + ).resolves.toMatchObject({ + mode: 'applied', + phase: 'completed -> running', + }); + expect(session.withTransaction).toHaveBeenCalledTimes(1); + expect(models.match.updateOne).toHaveBeenCalledWith( + { _id: matchId, status: 'finished', competitionId }, + { + $set: expect.objectContaining({ + status: 'in-progress', + 'resultPollState.state': 'polling', + }), + }, + { session, runValidators: true }, + ); + expect(models.competition.updateOne).toHaveBeenCalledWith( + { _id: competitionId, revision: preview.revisionBefore }, + { + $set: expect.objectContaining({ + phase: 'running', + revision: preview.revisionAfter, + }), + }, + { session, runValidators: true }, + ); + expect(models.competitionFact.insertMany).toHaveBeenCalledWith( + [ + expect.objectContaining({ + type: 'grand-final-rule-corrected', + revision: preview.revisionAfter, + }), + ], + { session }, + ); + expect(models.competitionOutbox.insertMany).toHaveBeenCalledWith( + [ + expect.objectContaining({ + type: 'competition.projection-updated', + revision: preview.revisionAfter, + }), + ], + { session }, + ); + }); +}); + +function finishedTournament() { + const competitionId = '000000000000000000000001'; + const teams = Array.from({ length: 8 }, (_, index) => ({ + teamId: (index + 1).toString(16).padStart(24, '0'), + displayOrder: index + 1, + seedNumber: index + 1, + })); + const bo1 = { type: 'first-to', maxGames: 1, winsRequired: 1 } as const; + const format = { + type: 'double-elimination' as const, + teamCount: 8 as const, + resetFinalEnabled: false, + rules: { + upper: { ...bo1, maxGames: 3, winsRequired: 2 }, + lower: bo1, + grandFinal: bo1, + resetFinal: bo1, + }, + }; + const seriesGraph = generateSeriesGraph({ competitionId, teams, format }); + const facts: Record[] = []; + const input = { + competitionId, + teams, + format, + seriesGraph, + facts, + projectorVersion: 1, + revision: 0, + }; + for (let index = 0; index < 28; index += 1) { + const slot = projectCompetition(input).gameSlots.find( + ({ status }) => status === 'ready', + ); + if (!slot) break; + facts.push(acceptedGame(slot, index + 1, 'A')); + input.revision += 1; + } + return input; +} + +function acceptedGame( + slot: ReturnType['gameSlots'][number], + revision: number, + winner: 'A' | 'B', +): Record { + const [a, b] = slot.entries; + const recordedAt = new Date(Date.UTC(2026, 6, 26, 0, revision)).toISOString(); + return { + id: `fact-${revision}`, + type: 'game-accepted', + revision, + ordinalWithinRevision: 1, + gameId: `game-${revision}`, + seriesId: slot.seriesId, + gameSlotId: slot.id, + ordinal: slot.ordinal, + recordedAt, + occurredAt: recordedAt, + evidence: { type: 'riot', riotMatchId: `KR_${revision}` }, + mapping: { + blueTeamId: a.teamId, + redTeamId: b.teamId, + winnerTeamId: winner === 'A' ? a.teamId : b.teamId, + participantAssignments: [], + }, + }; +} diff --git a/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.ts b/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.ts new file mode 100644 index 00000000..df2a36e5 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-grand-final-bo3.ts @@ -0,0 +1,410 @@ +import 'reflect-metadata'; +import { ConfigService } from '@nestjs/config'; +import mongoose from 'mongoose'; +import { createHash } from 'node:crypto'; +import { isDeepStrictEqual } from 'node:util'; +import { factForProjection } from '../../../competition/competition-command.service'; +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { + generateSeriesGraph, + type CompetitionGraphFormat, + type CompetitionGraphTeam, + type SeriesDefinition, +} from '../../../competition/domain/series-graph'; +import { SecretService } from '../../secret/secret.service'; +import { ConnectionService, resolveMongoDbName } from '../connection.service'; + +const CORRECTION_TYPE = 'grand-final-rule-corrected' as const; +const BO3 = { type: 'first-to', winsRequired: 2, maxGames: 3 } as const; + +interface RepairInput { + competitionId: string; + revision: number; + projectorVersion: number; + teams: readonly CompetitionGraphTeam[]; + format: CompetitionGraphFormat; + seriesGraph: readonly SeriesDefinition[]; + facts: readonly Record[]; +} + +export function planGrandFinalBo3Repair(input: RepairInput) { + const { format, seriesGraph, facts } = input; + const final = seriesGraph.find(({ stage }) => stage.type === 'grand-final'); + if ( + format.type !== 'double-elimination' || + format.resetFinalEnabled || + format.rules.grandFinal.type !== 'first-to' || + format.rules.grandFinal.maxGames !== 1 || + format.rules.grandFinal.winsRequired !== 1 || + !final || + !isDeepStrictEqual(final.rule, format.rules.grandFinal) || + final.gameSlots.length !== 1 || + seriesGraph.some( + ({ stage }) => stage.displayOrder > final.stage.displayOrder, + ) + ) { + throw new Error( + 'Expected a BO1 grand final with no reset or later series.', + ); + } + + const before = projectCompetition(input); + const previousFinal = before.series.find( + ({ seriesId }) => seriesId === final.id, + ); + const finalGames = before.games.filter( + ({ seriesId }) => seriesId === final.id, + ); + const firstGame = finalGames[0]; + if ( + before.phase !== 'completed' || + previousFinal?.status !== 'completed' || + previousFinal.outcome.type !== 'played' || + finalGames.length !== 1 || + firstGame.ordinal !== 1 || + firstGame.evidence.type !== 'riot' || + facts.filter((fact) => fact.seriesId === final.id).length !== 1 + ) { + throw new Error( + 'Expected exactly one Riot result and no other final facts.', + ); + } + + const correctedFormat = { + ...format, + rules: { ...format.rules, grandFinal: BO3 }, + }; + const generatedFinal = generateSeriesGraph({ + competitionId: input.competitionId, + teams: input.teams, + format: correctedFormat, + }).find(({ stage }) => stage.type === 'grand-final'); + if ( + generatedFinal?.id !== final.id || + !isDeepStrictEqual(generatedFinal.gameSlots[0], final.gameSlots[0]) + ) { + throw new Error( + 'The existing grand final does not match its stable slot identity.', + ); + } + const correctedGraph = seriesGraph.map((series) => + series.id === final.id + ? { ...series, rule: BO3, gameSlots: generatedFinal.gameSlots } + : series, + ); + const projection = projectCompetition({ + ...input, + revision: input.revision + 1, + format: correctedFormat, + seriesGraph: correctedGraph, + }); + const readySlots = projection.gameSlots.filter( + ({ status }) => status === 'ready', + ); + if ( + projection.phase !== 'running' || + !isDeepStrictEqual(projection.games, before.games) || + readySlots.length !== 2 || + readySlots.some( + (slot, index) => + slot.seriesId !== final.id || + slot.ordinal !== index + 2 || + slot.displayNumber !== firstGame.displayNumber + index + 1, + ) || + !isDeepStrictEqual( + projection.series.filter(({ seriesId }) => seriesId !== final.id), + before.series.filter(({ seriesId }) => seriesId !== final.id), + ) + ) { + throw new Error( + 'Repair would change existing results or fail to reopen the final.', + ); + } + + return { + before, + format: correctedFormat, + seriesGraph: correctedGraph, + projection, + seriesId: final.id, + preservedGame: firstGame.displayNumber, + newGameNumbers: readySlots.map(({ displayNumber }) => displayNumber), + }; +} + +interface CliOptions { + matchId: mongoose.Types.ObjectId; + nodeEnv: string; + expectedRevision?: number; + apply: boolean; +} + +export function parseGrandFinalRepairOptions(argv: string[]): CliOptions { + let matchId: mongoose.Types.ObjectId | undefined; + let nodeEnv = 'dev'; + let expectedRevision: number | undefined; + let apply = false; + for (let index = 0; index < argv.length; index += 1) { + switch (argv[index]) { + case '--': + break; + case '--apply': + apply = true; + break; + case '--match-id': { + const value = argv[++index]; + if (!/^[a-f\d]{24}$/i.test(value ?? '')) { + throw new Error('--match-id must be a 24-character ObjectId.'); + } + matchId = new mongoose.Types.ObjectId(value); + break; + } + case '--env': + nodeEnv = argv[++index]; + if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { + throw new Error('--env must be dev, staging, or prod.'); + } + break; + case '--expected-revision': { + const value = argv[++index]; + expectedRevision = Number(value); + if ( + !/^\d+$/.test(value ?? '') || + !Number.isSafeInteger(expectedRevision) + ) { + throw new Error('--expected-revision must be a nonnegative integer.'); + } + break; + } + default: + throw new Error(`Unknown argument: ${argv[index]}`); + } + } + if (!matchId || (apply && expectedRevision === undefined)) { + throw new Error( + '--match-id is required; --apply also requires --expected-revision from the dry run.', + ); + } + return { matchId, nodeEnv, expectedRevision, apply }; +} + +export async function repairGrandFinalBo3( + connectionService: ConnectionService, + options: CliOptions, +) { + if (options.apply && options.expectedRevision === undefined) { + throw new Error('An expected revision is required to apply the repair.'); + } + const [Match, Competition, Fact, Outbox] = await Promise.all([ + connectionService.getModel('match'), + connectionService.getModel('competition'), + connectionService.getModel('competitionFact'), + connectionService.getModel('competitionOutbox'), + ]); + async function run(session: mongoose.ClientSession | null) { + const match = await Match.findById(options.matchId) + .session(session) + .lean() + .exec(); + if ( + !match?.competitionId || + match.gameMode !== 'double-elimination' || + match.status !== 'finished' || + !match.teamBuiltAt || + !match.doubleElimination + ) { + throw new Error( + 'Expected a finished double-elimination Match with a linked Competition.', + ); + } + const competition = await Competition.findOne({ + _id: match.competitionId, + matchId: match._id, + communityId: match.communityId, + }) + .session(session) + .lean() + .exec(); + if (!competition || competition.phase !== 'completed') { + throw new Error('Expected a completed Competition linked to this Match.'); + } + if ( + options.expectedRevision !== undefined && + competition.revision !== options.expectedRevision + ) { + throw new Error( + `Competition revision is ${competition.revision}; run the preview again.`, + ); + } + const facts = await Fact.find({ competitionId: competition._id }) + .sort({ revision: 1, ordinalWithinRevision: 1 }) + .session(session) + .lean() + .exec(); + const plan = planGrandFinalBo3Repair({ + competitionId: competition._id.toHexString(), + revision: competition.revision, + projectorVersion: competition.projectorVersion, + teams: competition.teams.map(({ teamId, displayOrder, seedNumber }) => ({ + teamId: teamId.toHexString(), + displayOrder, + seedNumber, + })), + format: competition.format as unknown as CompetitionGraphFormat, + seriesGraph: competition.seriesGraph as unknown as SeriesDefinition[], + facts: facts.map((fact) => factForProjection({ ...fact })), + }); + if (!isDeepStrictEqual(plan.before, competition.projection)) { + throw new Error( + 'The fact ledger does not reproduce the stored projection.', + ); + } + const revision = plan.projection.sourceRevision; + if (session) { + const now = new Date(); + const idempotencyKey = `repair:grand-final-bo3:${competition._id.toHexString()}`; + const requestHash = createHash('sha256') + .update(idempotencyKey) + .digest('hex'); + const commandId = `cmpcmd_${requestHash.slice(0, 32)}`; + const receipt = { + competitionId: competition._id, + revision, + commandId, + idempotencyKey, + requestHash, + }; + const factId = new mongoose.Types.ObjectId(); + const competitionWrite = await Competition.updateOne( + { _id: competition._id, revision: competition.revision }, + { + $set: { + revision, + format: plan.format, + seriesGraph: plan.seriesGraph, + projection: plan.projection, + phase: plan.projection.phase, + }, + }, + { session, runValidators: true }, + ).exec(); + const matchWrite = await Match.updateOne( + { _id: match._id, status: 'finished', competitionId: competition._id }, + { + $set: { + status: 'in-progress', + 'doubleElimination.grandFinalGameCount': 3, + ...(match.resultPollState + ? { + 'resultPollState.state': 'polling', + 'resultPollState.matchedCount': plan.projection.games.length, + } + : {}), + }, + }, + { session, runValidators: true }, + ).exec(); + if ( + competitionWrite.matchedCount !== 1 || + matchWrite.matchedCount !== 1 + ) { + throw new Error( + 'Match or Competition changed during repair; run the preview again.', + ); + } + await Fact.insertMany( + [ + { + ...receipt, + _id: factId, + type: CORRECTION_TYPE, + ordinalWithinRevision: 1, + schemaVersion: competition.schemaVersion, + actor: { type: 'system' }, + seriesId: new mongoose.Types.ObjectId(plan.seriesId), + occurredAt: now, + recordedAt: now, + reason: + 'Restore the intended BO3 grand final without voiding the first game.', + ruleCorrection: { previousMaxGames: 1, nextMaxGames: 3 }, + }, + ], + { session }, + ); + await Outbox.insertMany( + [ + { + ...receipt, + eventId: `${commandId}:competition-projected`, + type: 'competition.projection-updated', + payload: { + competitionId: competition._id.toHexString(), + sourceRevision: revision, + factIds: [factId.toHexString()], + projection: plan.projection, + phase: plan.projection.phase, + updatedAt: now, + }, + state: 'pending', + availableAt: now, + }, + ], + { session }, + ); + } + return { + mode: session ? 'applied' : 'dry-run', + database: resolveMongoDbName(options.nodeEnv), + matchId: match._id.toHexString(), + competitionId: competition._id.toHexString(), + revisionBefore: competition.revision, + revisionAfter: revision, + phase: `${competition.phase} -> ${plan.projection.phase}`, + preservedGame: plan.preservedGame, + totalPreservedGames: plan.projection.games.length, + newGameNumbers: plan.newGameNumbers, + }; + } + + if (!options.apply) return run(null); + const session = await connectionService.createSession(); + if (!session) throw new Error('Repair requires a MongoDB transaction.'); + try { + return await session.withTransaction(() => run(session)); + } finally { + await session.endSession(); + } +} + +async function main() { + const args = process.argv.slice(2); + if (args.includes('--help')) { + process.stdout.write( + 'Usage: pnpm --filter api competition:repair-grand-final --env --match-id [--expected-revision --apply]\n', + ); + return; + } + const options = parseGrandFinalRepairOptions(args); + process.env.NODE_ENV = options.nodeEnv; + process.env.MONGODB_AUTO_INDEX = 'false'; + const connections = new ConnectionService( + new SecretService(new ConfigService()), + ); + const connection = await connections.getConnection(); + try { + process.stdout.write( + `${JSON.stringify(await repairGrandFinalBo3(connections, options), null, 2)}\n`, + ); + } finally { + await connection.close(); + } +} + +if (require.main === module) { + void main().catch((error: unknown) => { + process.stderr.write( + `${error instanceof Error ? error.message : String(error)}\n`, + ); + process.exitCode = 1; + }); +} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 867a3abb..462dd7ac 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -644,6 +644,7 @@ export interface DoubleEliminationEvent { export interface DoubleEliminationBracket { teamCount: 4 | 8; resetFinalEnabled: boolean; + grandFinalGameCount?: 1 | 3 | 5; resetFinalCreated: boolean; seeds: DoubleEliminationSeed[]; bracketMatches: DoubleEliminationBracketMatch[]; @@ -1850,6 +1851,7 @@ const DoubleEliminationBracketSubSchema = new Schema( { teamCount: { type: Number, enum: [4, 8], required: true }, resetFinalEnabled: { type: Boolean, required: true, default: false }, + grandFinalGameCount: { type: Number, enum: [1, 3, 5] }, resetFinalCreated: { type: Boolean, required: true, default: false }, seeds: { type: [DoubleEliminationSeedSubSchema], diff --git a/apps/api/src/modules/match/dto/create-match.dto.spec.ts b/apps/api/src/modules/match/dto/create-match.dto.spec.ts index 2b77dc13..21380d22 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.spec.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.spec.ts @@ -3,7 +3,7 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common'; import { plainToInstance } from 'class-transformer'; import { validateSync } from 'class-validator'; import mongoose from 'mongoose'; -import { CreateMatchDto, JoinMatchDto } from './create-match.dto'; +import { CreateMatchDto, JoinMatchDto, UpdateMatchDto } from './create-match.dto'; describe('CreateMatchDto game mode cutover', () => { it('rejects the removed live bracket mode', () => { @@ -61,3 +61,21 @@ describe('JoinMatchDto self-join boundary', () => { } }); }); + +describe('Grand final format validation', () => { + it('allows BO3 on creation and rejects an even game count on update', () => { + const create = plainToInstance(CreateMatchDto, { + title: 'Competition', + scheduledAt: '2026-07-13T10:00:00.000Z', + gameMode: 'double-elimination', + doubleEliminationGrandFinalGameCount: 3, + }); + expect(validateSync(create)).toEqual([]); + const update = plainToInstance(UpdateMatchDto, { + doubleEliminationGrandFinalGameCount: 2, + }); + expect(validateSync(update)).toEqual([ + expect.objectContaining({ property: 'doubleEliminationGrandFinalGameCount' }), + ]); + }); +}); diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 5f60725d..df2bfb0b 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -1,3 +1,4 @@ +import type { GrandFinalGameCount } from '@lolympus/contracts'; import { Type } from 'class-transformer'; import { ArrayMaxSize, @@ -119,6 +120,10 @@ export class CreateMatchDto { @IsBoolean() doubleEliminationResetFinalEnabled?: boolean; + @IsOptional() + @IsIn([1, 3, 5]) + doubleEliminationGrandFinalGameCount?: GrandFinalGameCount; + @IsOptional() @IsArray() @IsString({ each: true }) @@ -183,6 +188,10 @@ export class UpdateMatchDto { @IsBoolean() doubleEliminationResetFinalEnabled?: boolean; + @IsOptional() + @IsIn([1, 3, 5]) + doubleEliminationGrandFinalGameCount?: GrandFinalGameCount; + @IsOptional() @IsArray() @IsString({ each: true }) diff --git a/apps/api/src/modules/match/match-public.presenter.ts b/apps/api/src/modules/match/match-public.presenter.ts index 42572f7e..4da03995 100644 --- a/apps/api/src/modules/match/match-public.presenter.ts +++ b/apps/api/src/modules/match/match-public.presenter.ts @@ -21,7 +21,7 @@ interface PublicMatchSource { gameCount: number; gameMode: MatchGameMode; roundRobinMaxRounds?: number; - doubleElimination?: { resetFinalEnabled?: boolean }; + doubleElimination?: { resetFinalEnabled?: boolean; grandFinalGameCount?: 1 | 3 | 5 }; hostUserId?: IdLike; participants: Array<{ userId: IdLike; @@ -81,6 +81,8 @@ export function presentPublicMatch( ? { doubleEliminationResetFinalEnabled: source.doubleElimination?.resetFinalEnabled ?? false, + doubleEliminationGrandFinalGameCount: + source.doubleElimination?.grandFinalGameCount ?? 1, } : {}), ...(source.hostUserId diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 3e76c4c6..525eb742 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -60,6 +60,8 @@ export class MatchController { roundRobinMaxRounds: body.roundRobinMaxRounds, doubleEliminationResetFinalEnabled: body.doubleEliminationResetFinalEnabled, + doubleEliminationGrandFinalGameCount: + body.doubleEliminationGrandFinalGameCount, prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], @@ -149,7 +151,7 @@ export class MatchController { const match = await this.matchService.update({ matchId, communityId, - patch: body, + patch: mongoose.omitUndefined({ ...body }), }); return this.matchService.serialize(match, { joined: match.participants.some((participant) => diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 8627bd58..0fc4509a 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -531,6 +531,7 @@ describe('MatchService', () => { gameCount: 5, gameMode: 'double-elimination', doubleEliminationResetFinalEnabled: true, + doubleEliminationGrandFinalGameCount: 3, }, }); @@ -543,6 +544,7 @@ describe('MatchService', () => { doubleElimination: { teamCount: 4, resetFinalEnabled: true, + grandFinalGameCount: 3, resetFinalCreated: false, seeds: [], bracketMatches: [], diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index eba7184c..6300c3ca 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -37,6 +37,7 @@ const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3; interface DoubleEliminationConfigInput { doubleEliminationResetFinalEnabled?: boolean; + doubleEliminationGrandFinalGameCount?: 1 | 3 | 5; } interface CreateMatchParams { @@ -278,6 +279,14 @@ export class MatchService { 'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.', ); } + if ( + previousStatus !== 'recruiting' && + 'doubleEliminationGrandFinalGameCount' in params.patch + ) { + throw new BadRequestException( + 'Grand final game count can only be changed while recruiting.', + ); + } const patchToSet = previousStatus === 'recruiting' ? this.normalizeMatchConfig({ @@ -292,6 +301,10 @@ export class MatchService { params.patch.doubleEliminationResetFinalEnabled ?? params.patch.doubleElimination?.resetFinalEnabled ?? match.doubleElimination?.resetFinalEnabled, + doubleEliminationGrandFinalGameCount: + params.patch.doubleEliminationGrandFinalGameCount ?? + params.patch.doubleElimination?.grandFinalGameCount ?? + match.doubleElimination?.grandFinalGameCount, }) : this.stripMatchConfigInput(params.patch); match.set(patchToSet); @@ -406,6 +419,9 @@ export class MatchService { input.doubleEliminationResetFinalEnabled ?? input.doubleElimination?.resetFinalEnabled ?? false, + grandFinalGameCount: + input.doubleEliminationGrandFinalGameCount ?? + input.doubleElimination?.grandFinalGameCount, resetFinalCreated: false, seeds: [], bracketMatches: [], @@ -427,6 +443,7 @@ export class MatchService { >(input: T): Partial { const patch = { ...input }; delete patch.doubleEliminationResetFinalEnabled; + delete patch.doubleEliminationGrandFinalGameCount; return patch; } diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 6c91e931..6da5607a 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -975,6 +975,7 @@ export class TournamentCodeService { shuffledTeamIndexes, { resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false, + grandFinalGameCount: match.doubleElimination?.grandFinalGameCount, winnerBracketGameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, }, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 416e9331..bff3a27d 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -1,4 +1,5 @@ import type { + GrandFinalGameCount, MatchGameMode, MatchPosition, MatchPositionPreferenceView, @@ -282,6 +283,7 @@ export interface MatchMutationRequest { gameMode?: MatchGameMode; roundRobinMaxRounds?: number; doubleEliminationResetFinalEnabled?: boolean; + doubleEliminationGrandFinalGameCount?: GrandFinalGameCount; prizes?: string[]; notices?: string[]; schedule?: MatchScheduleItemView[]; diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx index 2d2164cb..8f9f4cff 100644 --- a/apps/web/src/pages/admin/MatchAdminPage.tsx +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -1,6 +1,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import type { + GrandFinalGameCount, MatchDetailResponse, MatchGameMode, MatchLifecycleStatus, @@ -28,6 +29,7 @@ const DEFAULT_FORM: MatchMutationRequest = { gameCount: 3, gameMode: 'pair', doubleEliminationResetFinalEnabled: true, + doubleEliminationGrandFinalGameCount: 3, prizes: [], notices: [], schedule: [], @@ -53,7 +55,9 @@ function matchModeDetail(match: MatchDetailResponse) { return `최대 ${match.roundRobinMaxRounds}라운드`; } if (match.gameMode === 'double-elimination') { - return match.doubleEliminationResetFinalEnabled ? '결승 리셋 허용' : '결승 리셋 없음'; + const finalGames = match.doubleEliminationGrandFinalGameCount ?? 1; + const finalFormat = finalGames === 1 ? '단판' : `${finalGames}전 ${Math.ceil(finalGames / 2)}선승`; + return `결승 ${finalFormat} · 리셋 ${match.doubleEliminationResetFinalEnabled ? '허용' : '없음'}`; } } @@ -152,6 +156,8 @@ function makeForm(match?: MatchDetailResponse): MatchMutationRequest & { roundRobinMaxRounds: match.roundRobinMaxRounds, doubleEliminationResetFinalEnabled: match.doubleEliminationResetFinalEnabled ?? true, + doubleEliminationGrandFinalGameCount: + match.doubleEliminationGrandFinalGameCount ?? 1, prizes: match.prizes, notices: match.notices, schedule: match.schedule, @@ -174,6 +180,7 @@ export default function MatchAdminPage() { const [editing, setEditing] = useState(null); const [showForm, setShowForm] = useState(false); const [form, setForm] = useState(makeForm()); + const isConfigLocked = editing !== null && editing.status !== 'recruiting'; const [message, setMessage] = useState(null); const formHeading = useRef(null); @@ -216,11 +223,19 @@ export default function MatchAdminPage() { } function buildPayload(): MatchMutationRequest { - return { + const details: MatchMutationRequest = { title: form.title.trim(), description: form.description?.trim() ?? '', mapId: Number(form.mapId ?? 11), scheduledAt: toIsoFromInput(form.scheduledAt), + prizes: parseLines(form.prizesText), + notices: parseLines(form.noticesText), + schedule: parseSchedule(form.scheduleText), + }; + if (isConfigLocked) return details; + + return { + ...details, maxParticipants: Number(form.maxParticipants ?? 10), gameCount: Number(form.gameCount ?? 3), gameMode: form.gameMode, @@ -228,6 +243,10 @@ export default function MatchAdminPage() { form.gameMode === 'double-elimination' ? Boolean(form.doubleEliminationResetFinalEnabled) : undefined, + doubleEliminationGrandFinalGameCount: + form.gameMode === 'double-elimination' + ? form.doubleEliminationGrandFinalGameCount + : undefined, roundRobinMaxRounds: form.gameMode === 'round-robin' ? normalizeRoundRobinMaxRounds( @@ -235,9 +254,6 @@ export default function MatchAdminPage() { form.maxParticipants, ) : undefined, - prizes: parseLines(form.prizesText), - notices: parseLines(form.noticesText), - schedule: parseSchedule(form.scheduleText), }; } @@ -384,6 +400,7 @@ export default function MatchAdminPage() { )} + {form.gameMode === 'double-elimination' && ( + + )} {form.gameMode === 'double-elimination' && ( )}