fix: keep best-of-three grand finals open for results
Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
This commit is contained in:
1 parent
38a89b5374
commit
7e0cd7cb19
21 files changed
+914
-23
No files matched your search
@@ -9,6 +9,7 @@
|
|||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.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",
|
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
|
||||||
"seed:dev": "ts-node src/seed.ts",
|
"seed:dev": "ts-node src/seed.ts",
|
||||||
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
CompetitionBootstrapService,
|
CompetitionBootstrapService,
|
||||||
type CompetitionBootstrapMatch,
|
type CompetitionBootstrapMatch,
|
||||||
} from './competition-bootstrap.service';
|
} from './competition-bootstrap.service';
|
||||||
|
import type { SeriesDefinition } from './domain/series-graph';
|
||||||
|
|
||||||
describe('CompetitionBootstrapService', () => {
|
describe('CompetitionBootstrapService', () => {
|
||||||
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
|
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
|
||||||
@@ -210,6 +211,40 @@ describe('CompetitionBootstrapService', () => {
|
|||||||
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
|
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 () => {
|
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
|
||||||
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
|
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
|
||||||
[
|
[
|
||||||
@@ -451,7 +486,7 @@ interface InsertPayload {
|
|||||||
legacyTeamIndex: number;
|
legacyTeamIndex: number;
|
||||||
seedNumber: number;
|
seedNumber: number;
|
||||||
}>;
|
}>;
|
||||||
seriesGraph: Array<{ code?: string; rule: unknown }>;
|
seriesGraph: SeriesDefinition[];
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch {
|
|||||||
doubleElimination?: {
|
doubleElimination?: {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
seeds: Array<{ seedNumber: number; teamIndex: number }>;
|
seeds: Array<{ seedNumber: number; teamIndex: number }>;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -514,6 +515,8 @@ function mapMatchFormat(
|
|||||||
winsRequired: 1,
|
winsRequired: 1,
|
||||||
maxGames: 1,
|
maxGames: 1,
|
||||||
};
|
};
|
||||||
|
const grandFinalGameCount =
|
||||||
|
match.doubleElimination?.grandFinalGameCount ?? 1;
|
||||||
return {
|
return {
|
||||||
type: 'double-elimination',
|
type: 'double-elimination',
|
||||||
teamCount: teams.length,
|
teamCount: teams.length,
|
||||||
@@ -525,7 +528,11 @@ function mapMatchFormat(
|
|||||||
maxGames: match.gameCount,
|
maxGames: match.gameCount,
|
||||||
},
|
},
|
||||||
lower: { ...bestOfOne },
|
lower: { ...bestOfOne },
|
||||||
grandFinal: { ...bestOfOne },
|
grandFinal: {
|
||||||
|
type: 'first-to',
|
||||||
|
winsRequired: Math.floor(grandFinalGameCount / 2) + 1,
|
||||||
|
maxGames: grandFinalGameCount,
|
||||||
|
},
|
||||||
resetFinal: { ...bestOfOne },
|
resetFinal: { ...bestOfOne },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -821,7 +821,7 @@ function buildOutbox(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function factForProjection(
|
export function factForProjection(
|
||||||
fact: Readonly<Record<string, unknown>>,
|
fact: Readonly<Record<string, unknown>>,
|
||||||
): Readonly<Record<string, unknown>> {
|
): Readonly<Record<string, unknown>> {
|
||||||
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
|
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [
|
|||||||
'game-voided',
|
'game-voided',
|
||||||
'series-adjudicated',
|
'series-adjudicated',
|
||||||
'adjudication-reversed',
|
'adjudication-reversed',
|
||||||
|
'grand-final-rule-corrected',
|
||||||
] as const;
|
] as const;
|
||||||
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
|
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
|
||||||
|
|
||||||
@@ -200,6 +201,7 @@ export interface CompetitionFact {
|
|||||||
adjudicationFactId?: mongoose.Types.ObjectId;
|
adjudicationFactId?: mongoose.Types.ObjectId;
|
||||||
decision?: Record<string, unknown>;
|
decision?: Record<string, unknown>;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
|
ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 };
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
@@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
|
|||||||
adjudicationFactId: { type: Schema.Types.ObjectId },
|
adjudicationFactId: { type: Schema.Types.ObjectId },
|
||||||
decision: { type: Schema.Types.Mixed },
|
decision: { type: Schema.Types.Mixed },
|
||||||
reason: { type: String },
|
reason: { type: String },
|
||||||
|
ruleCorrection: { type: Schema.Types.Mixed },
|
||||||
},
|
},
|
||||||
{ timestamps: true, collection: 'competition_fact' },
|
{ timestamps: true, collection: 'competition_fact' },
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -131,7 +131,12 @@ export interface CompetitionProjection {
|
|||||||
export function projectCompetition(
|
export function projectCompetition(
|
||||||
input: ProjectCompetitionInput,
|
input: ProjectCompetitionInput,
|
||||||
): CompetitionProjection {
|
): 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<number, string>();
|
const teamBySeed = new Map<number, string>();
|
||||||
const knownTeams = new Set<string>();
|
const knownTeams = new Set<string>();
|
||||||
for (const team of input.teams) {
|
for (const team of input.teams) {
|
||||||
@@ -169,7 +174,7 @@ export function projectCompetition(
|
|||||||
teamBySeed,
|
teamBySeed,
|
||||||
projectedById,
|
projectedById,
|
||||||
),
|
),
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
active: false,
|
active: false,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -188,7 +193,7 @@ export function projectCompetition(
|
|||||||
projectSeries({
|
projectSeries({
|
||||||
definition: asProjectorDefinition(definition),
|
definition: asProjectorDefinition(definition),
|
||||||
participants,
|
participants,
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
remaining.delete(seriesId);
|
remaining.delete(seriesId);
|
||||||
@@ -211,7 +216,7 @@ export function projectCompetition(
|
|||||||
projectSeries({
|
projectSeries({
|
||||||
definition: asProjectorDefinition(definition),
|
definition: asProjectorDefinition(definition),
|
||||||
participants,
|
participants,
|
||||||
facts: input.facts,
|
facts: resultFacts,
|
||||||
...(definition.activation ? { active: false } : {}),
|
...(definition.activation ? { active: false } : {}),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -221,7 +226,7 @@ export function projectCompetition(
|
|||||||
const gameProjection = projectGamesAndSlots(
|
const gameProjection = projectGamesAndSlots(
|
||||||
input.seriesGraph,
|
input.seriesGraph,
|
||||||
series,
|
series,
|
||||||
input.facts,
|
resultFacts,
|
||||||
);
|
);
|
||||||
const common = {
|
const common = {
|
||||||
competitionId: input.competitionId,
|
competitionId: input.competitionId,
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ export interface DoubleEliminationEvent {
|
|||||||
export interface DoubleEliminationBracket {
|
export interface DoubleEliminationBracket {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
resetFinalCreated: boolean;
|
resetFinalCreated: boolean;
|
||||||
seeds: DoubleEliminationSeed[];
|
seeds: DoubleEliminationSeed[];
|
||||||
bracketMatches: DoubleEliminationBracketMatch[];
|
bracketMatches: DoubleEliminationBracketMatch[];
|
||||||
@@ -98,6 +99,7 @@ export interface DoubleEliminationBracket {
|
|||||||
export interface BuildDoubleEliminationBracketOptions {
|
export interface BuildDoubleEliminationBracketOptions {
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
winnerBracketGameCount?: number;
|
winnerBracketGameCount?: number;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DoubleEliminationSeriesRule {
|
export interface DoubleEliminationSeriesRule {
|
||||||
@@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket(
|
|||||||
const bracket: DoubleEliminationBracket = {
|
const bracket: DoubleEliminationBracket = {
|
||||||
teamCount: seededTeamIndexes.length,
|
teamCount: seededTeamIndexes.length,
|
||||||
resetFinalEnabled: options.resetFinalEnabled,
|
resetFinalEnabled: options.resetFinalEnabled,
|
||||||
|
...(options.grandFinalGameCount === undefined
|
||||||
|
? {}
|
||||||
|
: { grandFinalGameCount: options.grandFinalGameCount }),
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds,
|
seeds,
|
||||||
bracketMatches:
|
bracketMatches:
|
||||||
@@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule(
|
|||||||
bracketMatchId: string;
|
bracketMatchId: string;
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
},
|
},
|
||||||
options: { winnerBracketGameCount?: number } = {},
|
options: Pick<
|
||||||
|
BuildDoubleEliminationBracketOptions,
|
||||||
|
'winnerBracketGameCount' | 'grandFinalGameCount'
|
||||||
|
> = {},
|
||||||
): DoubleEliminationSeriesRule {
|
): DoubleEliminationSeriesRule {
|
||||||
if (params.bracketSide === 'winner') {
|
if (params.bracketSide === 'winner') {
|
||||||
return seriesRule(options.winnerBracketGameCount ?? 3);
|
return seriesRule(options.winnerBracketGameCount ?? 3);
|
||||||
}
|
}
|
||||||
|
if (params.bracketSide === 'grand-final') {
|
||||||
|
return seriesRule(options.grandFinalGameCount ?? 1);
|
||||||
|
}
|
||||||
return seriesRule(1);
|
return seriesRule(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,6 +442,7 @@ function rebuildWithSeeds(
|
|||||||
): DoubleEliminationBracket {
|
): DoubleEliminationBracket {
|
||||||
const next = buildDoubleEliminationBracket(teamIndexes, {
|
const next = buildDoubleEliminationBracket(teamIndexes, {
|
||||||
resetFinalEnabled: bracket.resetFinalEnabled,
|
resetFinalEnabled: bracket.resetFinalEnabled,
|
||||||
|
grandFinalGameCount: bracket.grandFinalGameCount,
|
||||||
});
|
});
|
||||||
next.events = [
|
next.events = [
|
||||||
...bracket.events,
|
...bracket.events,
|
||||||
|
|||||||
@@ -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<string, unknown>[] = [];
|
||||||
|
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<typeof projectCompetition>['gameSlots'][number],
|
||||||
|
revision: number,
|
||||||
|
winner: 'A' | 'B',
|
||||||
|
): Record<string, unknown> {
|
||||||
|
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: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
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 <dev|staging|prod> --match-id <id> [--expected-revision <n> --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;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -644,6 +644,7 @@ export interface DoubleEliminationEvent {
|
|||||||
export interface DoubleEliminationBracket {
|
export interface DoubleEliminationBracket {
|
||||||
teamCount: 4 | 8;
|
teamCount: 4 | 8;
|
||||||
resetFinalEnabled: boolean;
|
resetFinalEnabled: boolean;
|
||||||
|
grandFinalGameCount?: 1 | 3 | 5;
|
||||||
resetFinalCreated: boolean;
|
resetFinalCreated: boolean;
|
||||||
seeds: DoubleEliminationSeed[];
|
seeds: DoubleEliminationSeed[];
|
||||||
bracketMatches: DoubleEliminationBracketMatch[];
|
bracketMatches: DoubleEliminationBracketMatch[];
|
||||||
@@ -1850,6 +1851,7 @@ const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
|
|||||||
{
|
{
|
||||||
teamCount: { type: Number, enum: [4, 8], required: true },
|
teamCount: { type: Number, enum: [4, 8], required: true },
|
||||||
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
||||||
|
grandFinalGameCount: { type: Number, enum: [1, 3, 5] },
|
||||||
resetFinalCreated: { type: Boolean, required: true, default: false },
|
resetFinalCreated: { type: Boolean, required: true, default: false },
|
||||||
seeds: {
|
seeds: {
|
||||||
type: [DoubleEliminationSeedSubSchema],
|
type: [DoubleEliminationSeedSubSchema],
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
|||||||
import { plainToInstance } from 'class-transformer';
|
import { plainToInstance } from 'class-transformer';
|
||||||
import { validateSync } from 'class-validator';
|
import { validateSync } from 'class-validator';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
|
import { CreateMatchDto, JoinMatchDto, UpdateMatchDto } from './create-match.dto';
|
||||||
|
|
||||||
describe('CreateMatchDto game mode cutover', () => {
|
describe('CreateMatchDto game mode cutover', () => {
|
||||||
it('rejects the removed live bracket mode', () => {
|
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' }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { GrandFinalGameCount } from '@lolympus/contracts';
|
||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
ArrayMaxSize,
|
ArrayMaxSize,
|
||||||
@@ -119,6 +120,10 @@ export class CreateMatchDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn([1, 3, 5])
|
||||||
|
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
@@ -183,6 +188,10 @@ export class UpdateMatchDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn([1, 3, 5])
|
||||||
|
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ interface PublicMatchSource {
|
|||||||
gameCount: number;
|
gameCount: number;
|
||||||
gameMode: MatchGameMode;
|
gameMode: MatchGameMode;
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
doubleElimination?: { resetFinalEnabled?: boolean };
|
doubleElimination?: { resetFinalEnabled?: boolean; grandFinalGameCount?: 1 | 3 | 5 };
|
||||||
hostUserId?: IdLike;
|
hostUserId?: IdLike;
|
||||||
participants: Array<{
|
participants: Array<{
|
||||||
userId: IdLike;
|
userId: IdLike;
|
||||||
@@ -81,6 +81,8 @@ export function presentPublicMatch(
|
|||||||
? {
|
? {
|
||||||
doubleEliminationResetFinalEnabled:
|
doubleEliminationResetFinalEnabled:
|
||||||
source.doubleElimination?.resetFinalEnabled ?? false,
|
source.doubleElimination?.resetFinalEnabled ?? false,
|
||||||
|
doubleEliminationGrandFinalGameCount:
|
||||||
|
source.doubleElimination?.grandFinalGameCount ?? 1,
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
...(source.hostUserId
|
...(source.hostUserId
|
||||||
|
|||||||
@@ -60,6 +60,8 @@ export class MatchController {
|
|||||||
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
||||||
doubleEliminationResetFinalEnabled:
|
doubleEliminationResetFinalEnabled:
|
||||||
body.doubleEliminationResetFinalEnabled,
|
body.doubleEliminationResetFinalEnabled,
|
||||||
|
doubleEliminationGrandFinalGameCount:
|
||||||
|
body.doubleEliminationGrandFinalGameCount,
|
||||||
prizes: body.prizes ?? [],
|
prizes: body.prizes ?? [],
|
||||||
notices: body.notices ?? [],
|
notices: body.notices ?? [],
|
||||||
schedule: body.schedule ?? [],
|
schedule: body.schedule ?? [],
|
||||||
@@ -149,7 +151,7 @@ export class MatchController {
|
|||||||
const match = await this.matchService.update({
|
const match = await this.matchService.update({
|
||||||
matchId,
|
matchId,
|
||||||
communityId,
|
communityId,
|
||||||
patch: body,
|
patch: mongoose.omitUndefined({ ...body }),
|
||||||
});
|
});
|
||||||
return this.matchService.serialize(match, {
|
return this.matchService.serialize(match, {
|
||||||
joined: match.participants.some((participant) =>
|
joined: match.participants.some((participant) =>
|
||||||
|
|||||||
@@ -531,6 +531,7 @@ describe('MatchService', () => {
|
|||||||
gameCount: 5,
|
gameCount: 5,
|
||||||
gameMode: 'double-elimination',
|
gameMode: 'double-elimination',
|
||||||
doubleEliminationResetFinalEnabled: true,
|
doubleEliminationResetFinalEnabled: true,
|
||||||
|
doubleEliminationGrandFinalGameCount: 3,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -543,6 +544,7 @@ describe('MatchService', () => {
|
|||||||
doubleElimination: {
|
doubleElimination: {
|
||||||
teamCount: 4,
|
teamCount: 4,
|
||||||
resetFinalEnabled: true,
|
resetFinalEnabled: true,
|
||||||
|
grandFinalGameCount: 3,
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds: [],
|
seeds: [],
|
||||||
bracketMatches: [],
|
bracketMatches: [],
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
|
|||||||
|
|
||||||
interface DoubleEliminationConfigInput {
|
interface DoubleEliminationConfigInput {
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
doubleEliminationGrandFinalGameCount?: 1 | 3 | 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CreateMatchParams {
|
interface CreateMatchParams {
|
||||||
@@ -278,6 +279,14 @@ export class MatchService {
|
|||||||
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
'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 =
|
const patchToSet =
|
||||||
previousStatus === 'recruiting'
|
previousStatus === 'recruiting'
|
||||||
? this.normalizeMatchConfig({
|
? this.normalizeMatchConfig({
|
||||||
@@ -292,6 +301,10 @@ export class MatchService {
|
|||||||
params.patch.doubleEliminationResetFinalEnabled ??
|
params.patch.doubleEliminationResetFinalEnabled ??
|
||||||
params.patch.doubleElimination?.resetFinalEnabled ??
|
params.patch.doubleElimination?.resetFinalEnabled ??
|
||||||
match.doubleElimination?.resetFinalEnabled,
|
match.doubleElimination?.resetFinalEnabled,
|
||||||
|
doubleEliminationGrandFinalGameCount:
|
||||||
|
params.patch.doubleEliminationGrandFinalGameCount ??
|
||||||
|
params.patch.doubleElimination?.grandFinalGameCount ??
|
||||||
|
match.doubleElimination?.grandFinalGameCount,
|
||||||
})
|
})
|
||||||
: this.stripMatchConfigInput(params.patch);
|
: this.stripMatchConfigInput(params.patch);
|
||||||
match.set(patchToSet);
|
match.set(patchToSet);
|
||||||
@@ -406,6 +419,9 @@ export class MatchService {
|
|||||||
input.doubleEliminationResetFinalEnabled ??
|
input.doubleEliminationResetFinalEnabled ??
|
||||||
input.doubleElimination?.resetFinalEnabled ??
|
input.doubleElimination?.resetFinalEnabled ??
|
||||||
false,
|
false,
|
||||||
|
grandFinalGameCount:
|
||||||
|
input.doubleEliminationGrandFinalGameCount ??
|
||||||
|
input.doubleElimination?.grandFinalGameCount,
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds: [],
|
seeds: [],
|
||||||
bracketMatches: [],
|
bracketMatches: [],
|
||||||
@@ -427,6 +443,7 @@ export class MatchService {
|
|||||||
>(input: T): Partial<Match> {
|
>(input: T): Partial<Match> {
|
||||||
const patch = { ...input };
|
const patch = { ...input };
|
||||||
delete patch.doubleEliminationResetFinalEnabled;
|
delete patch.doubleEliminationResetFinalEnabled;
|
||||||
|
delete patch.doubleEliminationGrandFinalGameCount;
|
||||||
return patch;
|
return patch;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -975,6 +975,7 @@ export class TournamentCodeService {
|
|||||||
shuffledTeamIndexes,
|
shuffledTeamIndexes,
|
||||||
{
|
{
|
||||||
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
||||||
|
grandFinalGameCount: match.doubleElimination?.grandFinalGameCount,
|
||||||
winnerBracketGameCount:
|
winnerBracketGameCount:
|
||||||
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
|
GrandFinalGameCount,
|
||||||
MatchGameMode,
|
MatchGameMode,
|
||||||
MatchPosition,
|
MatchPosition,
|
||||||
MatchPositionPreferenceView,
|
MatchPositionPreferenceView,
|
||||||
@@ -282,6 +283,7 @@ export interface MatchMutationRequest {
|
|||||||
gameMode?: MatchGameMode;
|
gameMode?: MatchGameMode;
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
|
||||||
prizes?: string[];
|
prizes?: string[];
|
||||||
notices?: string[];
|
notices?: string[];
|
||||||
schedule?: MatchScheduleItemView[];
|
schedule?: MatchScheduleItemView[];
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import type {
|
import type {
|
||||||
|
GrandFinalGameCount,
|
||||||
MatchDetailResponse,
|
MatchDetailResponse,
|
||||||
MatchGameMode,
|
MatchGameMode,
|
||||||
MatchLifecycleStatus,
|
MatchLifecycleStatus,
|
||||||
@@ -28,6 +29,7 @@ const DEFAULT_FORM: MatchMutationRequest = {
|
|||||||
gameCount: 3,
|
gameCount: 3,
|
||||||
gameMode: 'pair',
|
gameMode: 'pair',
|
||||||
doubleEliminationResetFinalEnabled: true,
|
doubleEliminationResetFinalEnabled: true,
|
||||||
|
doubleEliminationGrandFinalGameCount: 3,
|
||||||
prizes: [],
|
prizes: [],
|
||||||
notices: [],
|
notices: [],
|
||||||
schedule: [],
|
schedule: [],
|
||||||
@@ -53,7 +55,9 @@ function matchModeDetail(match: MatchDetailResponse) {
|
|||||||
return `최대 ${match.roundRobinMaxRounds}라운드`;
|
return `최대 ${match.roundRobinMaxRounds}라운드`;
|
||||||
}
|
}
|
||||||
if (match.gameMode === 'double-elimination') {
|
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,
|
roundRobinMaxRounds: match.roundRobinMaxRounds,
|
||||||
doubleEliminationResetFinalEnabled:
|
doubleEliminationResetFinalEnabled:
|
||||||
match.doubleEliminationResetFinalEnabled ?? true,
|
match.doubleEliminationResetFinalEnabled ?? true,
|
||||||
|
doubleEliminationGrandFinalGameCount:
|
||||||
|
match.doubleEliminationGrandFinalGameCount ?? 1,
|
||||||
prizes: match.prizes,
|
prizes: match.prizes,
|
||||||
notices: match.notices,
|
notices: match.notices,
|
||||||
schedule: match.schedule,
|
schedule: match.schedule,
|
||||||
@@ -174,6 +180,7 @@ export default function MatchAdminPage() {
|
|||||||
const [editing, setEditing] = useState<MatchDetailResponse | null>(null);
|
const [editing, setEditing] = useState<MatchDetailResponse | null>(null);
|
||||||
const [showForm, setShowForm] = useState(false);
|
const [showForm, setShowForm] = useState(false);
|
||||||
const [form, setForm] = useState(makeForm());
|
const [form, setForm] = useState(makeForm());
|
||||||
|
const isConfigLocked = editing !== null && editing.status !== 'recruiting';
|
||||||
const [message, setMessage] = useState<string | null>(null);
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
const formHeading = useRef<HTMLHeadingElement>(null);
|
const formHeading = useRef<HTMLHeadingElement>(null);
|
||||||
|
|
||||||
@@ -216,11 +223,19 @@ export default function MatchAdminPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildPayload(): MatchMutationRequest {
|
function buildPayload(): MatchMutationRequest {
|
||||||
return {
|
const details: MatchMutationRequest = {
|
||||||
title: form.title.trim(),
|
title: form.title.trim(),
|
||||||
description: form.description?.trim() ?? '',
|
description: form.description?.trim() ?? '',
|
||||||
mapId: Number(form.mapId ?? 11),
|
mapId: Number(form.mapId ?? 11),
|
||||||
scheduledAt: toIsoFromInput(form.scheduledAt),
|
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),
|
maxParticipants: Number(form.maxParticipants ?? 10),
|
||||||
gameCount: Number(form.gameCount ?? 3),
|
gameCount: Number(form.gameCount ?? 3),
|
||||||
gameMode: form.gameMode,
|
gameMode: form.gameMode,
|
||||||
@@ -228,6 +243,10 @@ export default function MatchAdminPage() {
|
|||||||
form.gameMode === 'double-elimination'
|
form.gameMode === 'double-elimination'
|
||||||
? Boolean(form.doubleEliminationResetFinalEnabled)
|
? Boolean(form.doubleEliminationResetFinalEnabled)
|
||||||
: undefined,
|
: undefined,
|
||||||
|
doubleEliminationGrandFinalGameCount:
|
||||||
|
form.gameMode === 'double-elimination'
|
||||||
|
? form.doubleEliminationGrandFinalGameCount
|
||||||
|
: undefined,
|
||||||
roundRobinMaxRounds:
|
roundRobinMaxRounds:
|
||||||
form.gameMode === 'round-robin'
|
form.gameMode === 'round-robin'
|
||||||
? normalizeRoundRobinMaxRounds(
|
? normalizeRoundRobinMaxRounds(
|
||||||
@@ -235,9 +254,6 @@ export default function MatchAdminPage() {
|
|||||||
form.maxParticipants,
|
form.maxParticipants,
|
||||||
)
|
)
|
||||||
: undefined,
|
: undefined,
|
||||||
prizes: parseLines(form.prizesText),
|
|
||||||
notices: parseLines(form.noticesText),
|
|
||||||
schedule: parseSchedule(form.scheduleText),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,6 +400,7 @@ export default function MatchAdminPage() {
|
|||||||
<label className="text-xs text-base-content/45">
|
<label className="text-xs text-base-content/45">
|
||||||
정원
|
정원
|
||||||
<select
|
<select
|
||||||
|
disabled={isConfigLocked}
|
||||||
value={form.maxParticipants}
|
value={form.maxParticipants}
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
const maxParticipants = Number(event.target.value);
|
const maxParticipants = Number(event.target.value);
|
||||||
@@ -407,9 +424,10 @@ export default function MatchAdminPage() {
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label className="text-xs text-base-content/45">
|
<label className="text-xs text-base-content/45">
|
||||||
게임 수
|
{form.gameMode === 'double-elimination' ? '승자조 게임 수' : '게임 수'}
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
|
disabled={isConfigLocked}
|
||||||
min={1}
|
min={1}
|
||||||
step={form.gameMode === 'double-elimination' ? 2 : 1}
|
step={form.gameMode === 'double-elimination' ? 2 : 1}
|
||||||
value={form.gameCount}
|
value={form.gameCount}
|
||||||
@@ -418,14 +436,14 @@ export default function MatchAdminPage() {
|
|||||||
/>
|
/>
|
||||||
{form.gameMode === 'double-elimination' && (
|
{form.gameMode === 'double-elimination' && (
|
||||||
<span className="mt-1 block text-xs text-base-content/30">
|
<span className="mt-1 block text-xs text-base-content/30">
|
||||||
승자조는 현재 3판 2선승으로 진행됩니다. 추후 5판 3선승도 같은
|
승자조 시리즈에 적용됩니다. 패자조는 단판입니다.
|
||||||
구조로 지원합니다.
|
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</label>
|
</label>
|
||||||
<label className="text-xs text-base-content/45">
|
<label className="text-xs text-base-content/45">
|
||||||
게임 모드
|
게임 모드
|
||||||
<select
|
<select
|
||||||
|
disabled={isConfigLocked}
|
||||||
value={form.gameMode}
|
value={form.gameMode}
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
const gameMode = event.target.value as MatchGameMode;
|
const gameMode = event.target.value as MatchGameMode;
|
||||||
@@ -460,6 +478,7 @@ export default function MatchAdminPage() {
|
|||||||
<span className="ml-1 text-xs text-base-content/25">선택</span>
|
<span className="ml-1 text-xs text-base-content/25">선택</span>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
|
disabled={isConfigLocked}
|
||||||
min={1}
|
min={1}
|
||||||
max={roundRobinFullRoundCount || undefined}
|
max={roundRobinFullRoundCount || undefined}
|
||||||
placeholder="예: 3"
|
placeholder="예: 3"
|
||||||
@@ -480,10 +499,31 @@ export default function MatchAdminPage() {
|
|||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
{form.gameMode === 'double-elimination' && (
|
||||||
|
<label className="text-xs text-base-content/45">
|
||||||
|
그랜드 파이널 형식
|
||||||
|
<select
|
||||||
|
className="lts-select mt-1 w-full"
|
||||||
|
disabled={isConfigLocked}
|
||||||
|
value={form.doubleEliminationGrandFinalGameCount ?? 1}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
doubleEliminationGrandFinalGameCount: Number(event.target.value) as GrandFinalGameCount,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value={1}>단판</option>
|
||||||
|
<option value={3}>3전 2선승</option>
|
||||||
|
<option value={5}>5전 3선승</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
{form.gameMode === 'double-elimination' && (
|
{form.gameMode === 'double-elimination' && (
|
||||||
<label className="flex items-center gap-2 border border-base-content/10 px-3 py-2 text-xs text-base-content/55">
|
<label className="flex items-center gap-2 border border-base-content/10 px-3 py-2 text-xs text-base-content/55">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
|
disabled={isConfigLocked}
|
||||||
checked={Boolean(form.doubleEliminationResetFinalEnabled)}
|
checked={Boolean(form.doubleEliminationResetFinalEnabled)}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setForm((current) => ({
|
setForm((current) => ({
|
||||||
@@ -493,7 +533,7 @@ export default function MatchAdminPage() {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
그랜드 파이널 리셋 허용
|
그랜드 파이널 리셋 허용 (리셋 경기는 단판)
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
<label className="text-xs text-base-content/45">
|
<label className="text-xs text-base-content/45">
|
||||||
|
|||||||
@@ -118,8 +118,35 @@ Fixed-game Series complete only after all configured GameSlots are filled and ma
|
|||||||
draw. First-to Series complete as soon as a team reaches the threshold and cannot
|
draw. First-to Series complete as soon as a team reaches the threshold and cannot
|
||||||
draw.
|
draw.
|
||||||
|
|
||||||
The legacy double-elimination defaults remain upper=`Match.gameCount`, lower=BO1,
|
Double elimination uses `Match.gameCount` for the upper bracket. The grand final
|
||||||
grand final=BO1, reset final=BO1.
|
can be set independently to BO1, BO3, or BO5 before team building. Existing
|
||||||
|
competitions and requests without an explicit final setting retain the legacy
|
||||||
|
BO1 default. The lower bracket and any reset final are BO1.
|
||||||
|
|
||||||
|
If a BO3 final was mistakenly created as BO1 and has exactly one accepted Riot
|
||||||
|
game, use the targeted repair after deploying the updated API. It only supports
|
||||||
|
a finished double-elimination bracket with reset disabled. The default command
|
||||||
|
is read-only and uses the API's database credentials from the environment:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm --filter api competition:repair-grand-final --env prod --match-id <match-id>
|
||||||
|
pnpm --filter api competition:repair-grand-final --env prod --match-id <match-id> --expected-revision <revisionBefore> --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify the preserved game and the new game numbers in the preview first. Apply
|
||||||
|
records the correction, keeps the existing result, reopens the final, and queues
|
||||||
|
the usual code assignment and stats refresh. Collect the next set from the
|
||||||
|
Operations tab using its Riot Match ID.
|
||||||
|
|
||||||
|
The built API also includes `dist/modules/global/database/migrations/repair-grand-final-bo3.js`.
|
||||||
|
Run it with Node and the same flags when the deployment image has no `ts-node`.
|
||||||
|
|
||||||
|
Wait for every API instance to run the updated build before applying the repair.
|
||||||
|
An older build can still display the repaired bracket, but a new result fails
|
||||||
|
with `Unsupported Competition fact type grand-final-rule-corrected` during
|
||||||
|
replay. If the repair has already been applied, update the API and retry the
|
||||||
|
same Riot Match ID. The failed command rolls back; the repair does not need to
|
||||||
|
be applied again.
|
||||||
|
|
||||||
### Series Graph
|
### Series Graph
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ export type MatchGameMode =
|
|||||||
| "round-robin"
|
| "round-robin"
|
||||||
| "double-elimination";
|
| "double-elimination";
|
||||||
|
|
||||||
|
export type GrandFinalGameCount = 1 | 3 | 5;
|
||||||
|
|
||||||
export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP";
|
export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP";
|
||||||
|
|
||||||
export interface MatchCompetitionSummaryView {
|
export interface MatchCompetitionSummaryView {
|
||||||
@@ -90,6 +92,7 @@ export interface MatchDetailResponse {
|
|||||||
gameMode: MatchGameMode;
|
gameMode: MatchGameMode;
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
doubleEliminationResetFinalEnabled?: boolean;
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
|
||||||
hostUserId?: UserId;
|
hostUserId?: UserId;
|
||||||
participants: MatchParticipantView[];
|
participants: MatchParticipantView[];
|
||||||
teams: MatchTeamView[];
|
teams: MatchTeamView[];
|
||||||
|
|||||||
Reference in new issue
Block a user