feat: add double elimination match mode
This commit is contained in:
1 parent
b9aaf55193
commit
e12f182e7f
19 files changed
+3415
-58
No files matched your search
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
buildDoubleEliminationBracket,
|
||||
cancelDoubleEliminationBracketMatch,
|
||||
completeDoubleEliminationBracketMatch,
|
||||
reshuffleDoubleEliminationSeeds,
|
||||
swapDoubleEliminationSeeds,
|
||||
} from './double-elimination.util';
|
||||
|
||||
describe('double-elimination util', () => {
|
||||
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
});
|
||||
|
||||
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
|
||||
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
|
||||
);
|
||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1'))
|
||||
.toMatchObject({
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 4,
|
||||
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
|
||||
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
|
||||
state: 'ready',
|
||||
});
|
||||
});
|
||||
|
||||
it('moves winners and losers through a 4-team bracket and records top 3', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
completedAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
completedAt: new Date('2026-06-01T10:30:00.000Z'),
|
||||
});
|
||||
|
||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'))
|
||||
.toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
|
||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'))
|
||||
.toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
|
||||
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'LB_R1_M1',
|
||||
winnerTeamIndex: 3,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'LB_FINAL',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'GF',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
|
||||
expect(bracket.placements).toEqual({
|
||||
firstTeamIndex: 1,
|
||||
secondTeamIndex: 2,
|
||||
thirdTeamIndex: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('creates reset final only when the loser bracket finalist wins grand final', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
});
|
||||
for (const [bracketMatchId, winnerTeamIndex] of [
|
||||
['WB_R1_M1', 1],
|
||||
['WB_R1_M2', 2],
|
||||
['WB_FINAL', 1],
|
||||
['LB_R1_M1', 3],
|
||||
['LB_FINAL', 2],
|
||||
['GF', 2],
|
||||
] as const) {
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId,
|
||||
winnerTeamIndex,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
}
|
||||
|
||||
expect(bracket.resetFinalCreated).toBe(true);
|
||||
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
|
||||
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF_RESET'))
|
||||
.toMatchObject({
|
||||
gameNumber: 7,
|
||||
bracketSide: 'reset-final',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
state: 'ready',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects completion cancellation when downstream matches are already completed', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
cancelDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
}),
|
||||
).toThrow('downstream');
|
||||
});
|
||||
|
||||
it('allows changing seeds before the bracket has completed matches', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
|
||||
const swapped = swapDoubleEliminationSeeds(bracket, {
|
||||
leftSeedNumber: 1,
|
||||
rightSeedNumber: 4,
|
||||
});
|
||||
expect(swapped.seeds).toEqual([
|
||||
{ seedNumber: 1, teamIndex: 4 },
|
||||
{ seedNumber: 2, teamIndex: 2 },
|
||||
{ seedNumber: 3, teamIndex: 3 },
|
||||
{ seedNumber: 4, teamIndex: 1 },
|
||||
]);
|
||||
expect(
|
||||
reshuffleDoubleEliminationSeeds(bracket, () => 0).seeds.map(
|
||||
(seed) => seed.teamIndex,
|
||||
),
|
||||
).toEqual([2, 3, 4, 1]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,672 @@
|
||||
import type mongoose from 'mongoose';
|
||||
|
||||
export type DoubleEliminationBracketSide =
|
||||
| 'winner'
|
||||
| 'loser'
|
||||
| 'grand-final'
|
||||
| 'reset-final';
|
||||
|
||||
export type DoubleEliminationBracketMatchState =
|
||||
| 'pending'
|
||||
| 'ready'
|
||||
| 'completed';
|
||||
|
||||
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
|
||||
|
||||
export interface DoubleEliminationSeed {
|
||||
seedNumber: number;
|
||||
teamIndex: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchSource {
|
||||
type: 'seed' | 'winner' | 'loser';
|
||||
seedNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchDestination {
|
||||
bracketMatchId: string;
|
||||
position: 'A' | 'B';
|
||||
}
|
||||
|
||||
export interface DoubleEliminationWalkover {
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
awardedBy?: mongoose.Types.ObjectId;
|
||||
awardedAt: Date;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelledAt?: Date;
|
||||
cancelReason?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatch {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
bracketSide: DoubleEliminationBracketSide;
|
||||
roundNumber: number;
|
||||
matchNumber: number;
|
||||
state: DoubleEliminationBracketMatchState;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
teamASource?: DoubleEliminationBracketMatchSource;
|
||||
teamBSource?: DoubleEliminationBracketMatchSource;
|
||||
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
winnerTeamIndex?: number;
|
||||
loserTeamIndex?: number;
|
||||
completedBy?: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationPlacements {
|
||||
firstTeamIndex?: number;
|
||||
secondTeamIndex?: number;
|
||||
thirdTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationEvent {
|
||||
type:
|
||||
| 'bracket-created'
|
||||
| 'seeds-reshuffled'
|
||||
| 'seeds-swapped'
|
||||
| 'bracket-match-completed'
|
||||
| 'bracket-match-cancelled'
|
||||
| 'walkover-awarded'
|
||||
| 'walkover-cancelled'
|
||||
| 'reset-final-created'
|
||||
| 'riot-result-cancelled';
|
||||
bracketMatchId?: string;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
reason?: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracket {
|
||||
teamCount: 4 | 8;
|
||||
resetFinalEnabled: boolean;
|
||||
resetFinalCreated: boolean;
|
||||
seeds: DoubleEliminationSeed[];
|
||||
bracketMatches: DoubleEliminationBracketMatch[];
|
||||
placements: DoubleEliminationPlacements;
|
||||
events: DoubleEliminationEvent[];
|
||||
}
|
||||
|
||||
export interface BuildDoubleEliminationBracketOptions {
|
||||
resetFinalEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteDoubleEliminationBracketMatchParams {
|
||||
bracketMatchId: string;
|
||||
winnerTeamIndex: number;
|
||||
completedBy: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface CancelDoubleEliminationBracketMatchParams {
|
||||
bracketMatchId: string;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelReason?: string;
|
||||
}
|
||||
|
||||
export function buildDoubleEliminationBracket(
|
||||
seededTeamIndexes: number[],
|
||||
options: BuildDoubleEliminationBracketOptions,
|
||||
): DoubleEliminationBracket {
|
||||
assertSupportedTeamCount(seededTeamIndexes.length);
|
||||
const seeds = seededTeamIndexes.map((teamIndex, index) => ({
|
||||
seedNumber: index + 1,
|
||||
teamIndex,
|
||||
}));
|
||||
const bracket: DoubleEliminationBracket = {
|
||||
teamCount: seededTeamIndexes.length as 4 | 8,
|
||||
resetFinalEnabled: options.resetFinalEnabled,
|
||||
resetFinalCreated: false,
|
||||
seeds,
|
||||
bracketMatches:
|
||||
seededTeamIndexes.length === 4
|
||||
? buildFourTeamBracketMatches()
|
||||
: buildEightTeamBracketMatches(),
|
||||
placements: {},
|
||||
events: [
|
||||
{
|
||||
type: 'bracket-created',
|
||||
createdAt: new Date(),
|
||||
},
|
||||
],
|
||||
};
|
||||
applySeedTeams(bracket);
|
||||
refreshBracketMatchStates(bracket);
|
||||
return bracket;
|
||||
}
|
||||
|
||||
export function reshuffleDoubleEliminationSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
rng: () => number = Math.random,
|
||||
): DoubleEliminationBracket {
|
||||
assertSeedChangeAllowed(bracket);
|
||||
const teamIndexes = shuffleInPlace(
|
||||
bracket.seeds.map((seed) => seed.teamIndex),
|
||||
rng,
|
||||
);
|
||||
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-reshuffled');
|
||||
}
|
||||
|
||||
export function swapDoubleEliminationSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: { leftSeedNumber: number; rightSeedNumber: number },
|
||||
): DoubleEliminationBracket {
|
||||
assertSeedChangeAllowed(bracket);
|
||||
const teamIndexes = [...bracket.seeds]
|
||||
.sort((left, right) => left.seedNumber - right.seedNumber)
|
||||
.map((seed) => seed.teamIndex);
|
||||
const leftIndex = params.leftSeedNumber - 1;
|
||||
const rightIndex = params.rightSeedNumber - 1;
|
||||
if (!teamIndexes[leftIndex] || !teamIndexes[rightIndex]) {
|
||||
throw new Error('Invalid seed number.');
|
||||
}
|
||||
[teamIndexes[leftIndex], teamIndexes[rightIndex]] = [
|
||||
teamIndexes[rightIndex],
|
||||
teamIndexes[leftIndex],
|
||||
];
|
||||
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-swapped');
|
||||
}
|
||||
|
||||
export function completeDoubleEliminationBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: CompleteDoubleEliminationBracketMatchParams,
|
||||
): DoubleEliminationBracket {
|
||||
const next = cloneBracket(bracket);
|
||||
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
|
||||
if (bracketMatch.state !== 'ready') {
|
||||
throw new Error('Bracket match is not ready.');
|
||||
}
|
||||
if (
|
||||
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
|
||||
bracketMatch.teamBIndex !== params.winnerTeamIndex
|
||||
) {
|
||||
throw new Error('Winner team is not assigned to this bracket match.');
|
||||
}
|
||||
|
||||
const loserTeamIndex =
|
||||
bracketMatch.teamAIndex === params.winnerTeamIndex
|
||||
? bracketMatch.teamBIndex
|
||||
: bracketMatch.teamAIndex;
|
||||
if (!loserTeamIndex) throw new Error('Loser team is missing.');
|
||||
|
||||
bracketMatch.state = 'completed';
|
||||
bracketMatch.winnerTeamIndex = params.winnerTeamIndex;
|
||||
bracketMatch.loserTeamIndex = loserTeamIndex;
|
||||
bracketMatch.completedBy = params.completedBy;
|
||||
bracketMatch.completedAt = params.completedAt ?? new Date();
|
||||
if (params.walkover) {
|
||||
bracketMatch.walkover = params.walkover;
|
||||
}
|
||||
|
||||
advanceTeam(next, bracketMatch.winnerAdvancesTo, params.winnerTeamIndex);
|
||||
advanceTeam(next, bracketMatch.loserAdvancesTo, loserTeamIndex);
|
||||
if (bracketMatch.bracketMatchId === 'LB_FINAL') {
|
||||
next.placements.thirdTeamIndex = loserTeamIndex;
|
||||
}
|
||||
if (bracketMatch.bracketMatchId === 'GF') {
|
||||
completeGrandFinal(next, bracketMatch);
|
||||
}
|
||||
if (bracketMatch.bracketMatchId === 'GF_RESET') {
|
||||
next.placements.firstTeamIndex = params.winnerTeamIndex;
|
||||
next.placements.secondTeamIndex = loserTeamIndex;
|
||||
}
|
||||
|
||||
refreshBracketMatchStates(next);
|
||||
next.events.push({
|
||||
type:
|
||||
params.completedBy === 'walkover'
|
||||
? 'walkover-awarded'
|
||||
: 'bracket-match-completed',
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
createdAt: bracketMatch.completedAt,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function cancelDoubleEliminationBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: CancelDoubleEliminationBracketMatchParams,
|
||||
): DoubleEliminationBracket {
|
||||
const next = cloneBracket(bracket);
|
||||
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
|
||||
if (bracketMatch.state !== 'completed') {
|
||||
throw new Error('Bracket match is not completed.');
|
||||
}
|
||||
|
||||
const descendants = collectDescendantBracketMatchIds(
|
||||
next,
|
||||
bracketMatch.bracketMatchId,
|
||||
);
|
||||
const completedDescendant = next.bracketMatches.find(
|
||||
(match) => descendants.has(match.bracketMatchId) && match.state === 'completed',
|
||||
);
|
||||
if (completedDescendant) {
|
||||
throw new Error('Cannot cancel because a downstream bracket match is completed.');
|
||||
}
|
||||
|
||||
if (bracketMatch.bracketMatchId === 'GF') {
|
||||
next.bracketMatches = next.bracketMatches.filter(
|
||||
(match) => match.bracketMatchId !== 'GF_RESET',
|
||||
);
|
||||
next.resetFinalCreated = false;
|
||||
}
|
||||
|
||||
for (const descendantId of descendants) {
|
||||
const descendant = next.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === descendantId,
|
||||
);
|
||||
if (!descendant) continue;
|
||||
if (referencesBracketMatch(descendant.teamASource, bracketMatch.bracketMatchId)) {
|
||||
descendant.teamAIndex = undefined;
|
||||
}
|
||||
if (referencesBracketMatch(descendant.teamBSource, bracketMatch.bracketMatchId)) {
|
||||
descendant.teamBIndex = undefined;
|
||||
}
|
||||
descendant.winnerTeamIndex = undefined;
|
||||
descendant.loserTeamIndex = undefined;
|
||||
descendant.completedBy = undefined;
|
||||
descendant.completedAt = undefined;
|
||||
}
|
||||
|
||||
bracketMatch.winnerTeamIndex = undefined;
|
||||
bracketMatch.loserTeamIndex = undefined;
|
||||
bracketMatch.completedBy = undefined;
|
||||
bracketMatch.completedAt = undefined;
|
||||
if (bracketMatch.walkover?.active) {
|
||||
bracketMatch.walkover = {
|
||||
...bracketMatch.walkover,
|
||||
active: false,
|
||||
cancelledBy: params.cancelledBy,
|
||||
cancelledAt: new Date(),
|
||||
cancelReason: params.cancelReason,
|
||||
};
|
||||
}
|
||||
next.placements = {};
|
||||
refreshBracketMatchStates(next);
|
||||
next.events.push({
|
||||
type:
|
||||
bracketMatch.walkover && !bracketMatch.walkover.active
|
||||
? 'walkover-cancelled'
|
||||
: 'bracket-match-cancelled',
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
actorUserId: params.cancelledBy,
|
||||
reason: params.cancelReason,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function findNextReadyDoubleEliminationBracketMatches(
|
||||
bracket: DoubleEliminationBracket | undefined,
|
||||
): DoubleEliminationBracketMatch[] {
|
||||
return (bracket?.bracketMatches ?? []).filter(
|
||||
(bracketMatch) => bracketMatch.state === 'ready',
|
||||
);
|
||||
}
|
||||
|
||||
export function hasCompletedDoubleEliminationBracketMatches(
|
||||
bracket: DoubleEliminationBracket | undefined,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
bracket?.bracketMatches.some(
|
||||
(bracketMatch) => bracketMatch.state === 'completed',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function rebuildWithSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
teamIndexes: number[],
|
||||
eventType: DoubleEliminationEvent['type'],
|
||||
): DoubleEliminationBracket {
|
||||
const next = buildDoubleEliminationBracket(teamIndexes, {
|
||||
resetFinalEnabled: bracket.resetFinalEnabled,
|
||||
});
|
||||
next.events = [
|
||||
...bracket.events,
|
||||
{
|
||||
type: eventType,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
];
|
||||
return next;
|
||||
}
|
||||
|
||||
function completeGrandFinal(
|
||||
bracket: DoubleEliminationBracket,
|
||||
grandFinal: DoubleEliminationBracketMatch,
|
||||
): void {
|
||||
if (!grandFinal.winnerTeamIndex || !grandFinal.loserTeamIndex) return;
|
||||
const winnerBracketTeamIndex = grandFinal.teamAIndex;
|
||||
if (
|
||||
bracket.resetFinalEnabled &&
|
||||
!bracket.resetFinalCreated &&
|
||||
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
|
||||
) {
|
||||
bracket.resetFinalCreated = true;
|
||||
bracket.bracketMatches.push({
|
||||
bracketMatchId: 'GF_RESET',
|
||||
gameNumber: nextGameNumber(bracket),
|
||||
bracketSide: 'reset-final',
|
||||
roundNumber: 1,
|
||||
matchNumber: 1,
|
||||
state: 'ready',
|
||||
teamAIndex: grandFinal.teamAIndex,
|
||||
teamBIndex: grandFinal.teamBIndex,
|
||||
teamASource: { type: 'winner', bracketMatchId: 'GF' },
|
||||
teamBSource: { type: 'loser', bracketMatchId: 'GF' },
|
||||
});
|
||||
bracket.events.push({
|
||||
type: 'reset-final-created',
|
||||
bracketMatchId: 'GF_RESET',
|
||||
createdAt: new Date(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
bracket.placements.firstTeamIndex = grandFinal.winnerTeamIndex;
|
||||
bracket.placements.secondTeamIndex = grandFinal.loserTeamIndex;
|
||||
}
|
||||
|
||||
function advanceTeam(
|
||||
bracket: DoubleEliminationBracket,
|
||||
destination: DoubleEliminationBracketMatchDestination | undefined,
|
||||
teamIndex: number,
|
||||
): void {
|
||||
if (!destination) return;
|
||||
const target = requireBracketMatch(bracket, destination.bracketMatchId);
|
||||
if (destination.position === 'A') {
|
||||
target.teamAIndex = teamIndex;
|
||||
} else {
|
||||
target.teamBIndex = teamIndex;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshBracketMatchStates(bracket: DoubleEliminationBracket): void {
|
||||
for (const bracketMatch of bracket.bracketMatches) {
|
||||
if (bracketMatch.winnerTeamIndex) {
|
||||
bracketMatch.state = 'completed';
|
||||
continue;
|
||||
}
|
||||
bracketMatch.state =
|
||||
bracketMatch.teamAIndex && bracketMatch.teamBIndex ? 'ready' : 'pending';
|
||||
}
|
||||
}
|
||||
|
||||
function applySeedTeams(bracket: DoubleEliminationBracket): void {
|
||||
const bySeedNumber = new Map(
|
||||
bracket.seeds.map((seed) => [seed.seedNumber, seed.teamIndex]),
|
||||
);
|
||||
for (const bracketMatch of bracket.bracketMatches) {
|
||||
if (bracketMatch.teamASource?.type === 'seed') {
|
||||
bracketMatch.teamAIndex = bySeedNumber.get(
|
||||
bracketMatch.teamASource.seedNumber ?? 0,
|
||||
);
|
||||
}
|
||||
if (bracketMatch.teamBSource?.type === 'seed') {
|
||||
bracketMatch.teamBIndex = bySeedNumber.get(
|
||||
bracketMatch.teamBSource.seedNumber ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildFourTeamBracketMatches(): DoubleEliminationBracketMatch[] {
|
||||
return [
|
||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
||||
teamASource: seedSource(1),
|
||||
teamBSource: seedSource(4),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
|
||||
teamASource: seedSource(2),
|
||||
teamBSource: seedSource(3),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, {
|
||||
teamASource: winnerSource('WB_R1_M1'),
|
||||
teamBSource: winnerSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('GF', 'A'),
|
||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, {
|
||||
teamASource: loserSource('WB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, {
|
||||
teamASource: winnerSource('LB_R1_M1'),
|
||||
teamBSource: loserSource('WB_FINAL'),
|
||||
winnerAdvancesTo: destination('GF', 'B'),
|
||||
}),
|
||||
bracketMatch('GF', 6, 'grand-final', 1, 1, {
|
||||
teamASource: winnerSource('WB_FINAL'),
|
||||
teamBSource: winnerSource('LB_FINAL'),
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function buildEightTeamBracketMatches(): DoubleEliminationBracketMatch[] {
|
||||
return [
|
||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
||||
teamASource: seedSource(1),
|
||||
teamBSource: seedSource(8),
|
||||
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
|
||||
teamASource: seedSource(4),
|
||||
teamBSource: seedSource(5),
|
||||
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, {
|
||||
teamASource: seedSource(2),
|
||||
teamBSource: seedSource(7),
|
||||
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M2', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, {
|
||||
teamASource: seedSource(3),
|
||||
teamBSource: seedSource(6),
|
||||
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M2', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, {
|
||||
teamASource: winnerSource('WB_R1_M1'),
|
||||
teamBSource: winnerSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||
loserAdvancesTo: destination('LB_R2_M2', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, {
|
||||
teamASource: winnerSource('WB_R1_M3'),
|
||||
teamBSource: winnerSource('WB_R1_M4'),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||
loserAdvancesTo: destination('LB_R2_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, {
|
||||
teamASource: winnerSource('WB_R2_M1'),
|
||||
teamBSource: winnerSource('WB_R2_M2'),
|
||||
winnerAdvancesTo: destination('GF', 'A'),
|
||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, {
|
||||
teamASource: loserSource('WB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, {
|
||||
teamASource: loserSource('WB_R1_M3'),
|
||||
teamBSource: loserSource('WB_R1_M4'),
|
||||
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, {
|
||||
teamASource: winnerSource('LB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R2_M2'),
|
||||
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, {
|
||||
teamASource: winnerSource('LB_R1_M2'),
|
||||
teamBSource: loserSource('WB_R2_M1'),
|
||||
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, {
|
||||
teamASource: winnerSource('LB_R2_M1'),
|
||||
teamBSource: winnerSource('LB_R2_M2'),
|
||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, {
|
||||
teamASource: winnerSource('LB_R3_M1'),
|
||||
teamBSource: loserSource('WB_FINAL'),
|
||||
winnerAdvancesTo: destination('GF', 'B'),
|
||||
}),
|
||||
bracketMatch('GF', 14, 'grand-final', 1, 1, {
|
||||
teamASource: winnerSource('WB_FINAL'),
|
||||
teamBSource: winnerSource('LB_FINAL'),
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function bracketMatch(
|
||||
bracketMatchId: string,
|
||||
gameNumber: number,
|
||||
bracketSide: DoubleEliminationBracketSide,
|
||||
roundNumber: number,
|
||||
matchNumber: number,
|
||||
params: Partial<DoubleEliminationBracketMatch>,
|
||||
): DoubleEliminationBracketMatch {
|
||||
return {
|
||||
bracketMatchId,
|
||||
gameNumber,
|
||||
bracketSide,
|
||||
roundNumber,
|
||||
matchNumber,
|
||||
state: 'pending',
|
||||
...params,
|
||||
};
|
||||
}
|
||||
|
||||
function seedSource(seedNumber: number): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'seed', seedNumber };
|
||||
}
|
||||
|
||||
function winnerSource(
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'winner', bracketMatchId };
|
||||
}
|
||||
|
||||
function loserSource(
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'loser', bracketMatchId };
|
||||
}
|
||||
|
||||
function destination(
|
||||
bracketMatchId: string,
|
||||
position: 'A' | 'B',
|
||||
): DoubleEliminationBracketMatchDestination {
|
||||
return { bracketMatchId, position };
|
||||
}
|
||||
|
||||
function collectDescendantBracketMatchIds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
bracketMatchId: string,
|
||||
): Set<string> {
|
||||
const descendants = new Set<string>();
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const match of bracket.bracketMatches) {
|
||||
const sourceIds = [
|
||||
match.teamASource?.bracketMatchId,
|
||||
match.teamBSource?.bracketMatchId,
|
||||
].filter((id): id is string => Boolean(id));
|
||||
if (
|
||||
sourceIds.some((id) => id === bracketMatchId || descendants.has(id)) &&
|
||||
!descendants.has(match.bracketMatchId)
|
||||
) {
|
||||
descendants.add(match.bracketMatchId);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return descendants;
|
||||
}
|
||||
|
||||
function referencesBracketMatch(
|
||||
source: DoubleEliminationBracketMatchSource | undefined,
|
||||
bracketMatchId: string,
|
||||
): boolean {
|
||||
return source?.bracketMatchId === bracketMatchId;
|
||||
}
|
||||
|
||||
function requireBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatch {
|
||||
const bracketMatch = bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === bracketMatchId,
|
||||
);
|
||||
if (!bracketMatch) throw new Error('Bracket match not found.');
|
||||
return bracketMatch;
|
||||
}
|
||||
|
||||
function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void {
|
||||
if (hasCompletedDoubleEliminationBracketMatches(bracket)) {
|
||||
throw new Error('Cannot change seeds after a bracket match is completed.');
|
||||
}
|
||||
}
|
||||
|
||||
function assertSupportedTeamCount(teamCount: number): asserts teamCount is 4 | 8 {
|
||||
if (teamCount !== 4 && teamCount !== 8) {
|
||||
throw new Error('Double elimination supports only 4 or 8 teams.');
|
||||
}
|
||||
}
|
||||
|
||||
function nextGameNumber(bracket: DoubleEliminationBracket): number {
|
||||
return Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1;
|
||||
}
|
||||
|
||||
function cloneBracket(
|
||||
bracket: DoubleEliminationBracket,
|
||||
): DoubleEliminationBracket {
|
||||
return {
|
||||
...bracket,
|
||||
seeds: bracket.seeds.map((seed) => ({ ...seed })),
|
||||
bracketMatches: bracket.bracketMatches.map((match) => ({
|
||||
...match,
|
||||
teamASource: match.teamASource ? { ...match.teamASource } : undefined,
|
||||
teamBSource: match.teamBSource ? { ...match.teamBSource } : undefined,
|
||||
winnerAdvancesTo: match.winnerAdvancesTo
|
||||
? { ...match.winnerAdvancesTo }
|
||||
: undefined,
|
||||
loserAdvancesTo: match.loserAdvancesTo
|
||||
? { ...match.loserAdvancesTo }
|
||||
: undefined,
|
||||
walkover: match.walkover ? { ...match.walkover } : undefined,
|
||||
})),
|
||||
placements: { ...bracket.placements },
|
||||
events: bracket.events.map((event) => ({ ...event })),
|
||||
};
|
||||
}
|
||||
|
||||
function shuffleInPlace<T>(
|
||||
items: T[],
|
||||
rng: () => number = Math.random,
|
||||
): T[] {
|
||||
for (let index = items.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(rng() * (index + 1));
|
||||
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
|
||||
}
|
||||
return items;
|
||||
}
|
||||
@@ -32,11 +32,16 @@ export const MATCH_STATUSES: MatchStatus[] = [
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export type MatchGameMode =
|
||||
| 'pair'
|
||||
| 'bracket'
|
||||
| 'round-robin'
|
||||
| 'double-elimination';
|
||||
export const MATCH_GAME_MODES: MatchGameMode[] = [
|
||||
'pair',
|
||||
'bracket',
|
||||
'round-robin',
|
||||
'double-elimination',
|
||||
];
|
||||
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
@@ -47,13 +52,15 @@ export type TournamentCodeState =
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
| 'released'
|
||||
| 'voided';
|
||||
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
|
||||
'available',
|
||||
'reserved',
|
||||
'used',
|
||||
'expired',
|
||||
'released',
|
||||
'voided',
|
||||
];
|
||||
export type TournamentMapType = 'SUMMONERS_RIFT';
|
||||
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
|
||||
@@ -445,6 +452,7 @@ export interface TournamentCode extends MongooseTimestamps {
|
||||
state: TournamentCodeState;
|
||||
matchId?: mongoose.Types.ObjectId;
|
||||
gameNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
reservedAt?: Date;
|
||||
usedAt?: Date;
|
||||
releasedAt?: Date;
|
||||
@@ -497,6 +505,7 @@ export interface MatchGameResultParticipant {
|
||||
|
||||
export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -508,6 +517,7 @@ export interface MatchGameResult {
|
||||
}
|
||||
|
||||
export interface MatchSeriesResult {
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
@@ -515,6 +525,118 @@ export interface MatchSeriesResult {
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
|
||||
export type DoubleEliminationBracketSide =
|
||||
| 'winner'
|
||||
| 'loser'
|
||||
| 'grand-final'
|
||||
| 'reset-final';
|
||||
export const DOUBLE_ELIMINATION_BRACKET_SIDES: DoubleEliminationBracketSide[] =
|
||||
['winner', 'loser', 'grand-final', 'reset-final'];
|
||||
|
||||
export type DoubleEliminationBracketMatchState =
|
||||
| 'pending'
|
||||
| 'ready'
|
||||
| 'completed';
|
||||
export const DOUBLE_ELIMINATION_BRACKET_MATCH_STATES: DoubleEliminationBracketMatchState[] =
|
||||
['pending', 'ready', 'completed'];
|
||||
|
||||
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
|
||||
export const DOUBLE_ELIMINATION_COMPLETION_TYPES: DoubleEliminationCompletionType[] =
|
||||
['riot-result', 'walkover'];
|
||||
|
||||
export type DoubleEliminationEventType =
|
||||
| 'bracket-created'
|
||||
| 'seeds-reshuffled'
|
||||
| 'seeds-swapped'
|
||||
| 'bracket-match-completed'
|
||||
| 'bracket-match-cancelled'
|
||||
| 'walkover-awarded'
|
||||
| 'walkover-cancelled'
|
||||
| 'reset-final-created'
|
||||
| 'riot-result-cancelled';
|
||||
export const DOUBLE_ELIMINATION_EVENT_TYPES: DoubleEliminationEventType[] = [
|
||||
'bracket-created',
|
||||
'seeds-reshuffled',
|
||||
'seeds-swapped',
|
||||
'bracket-match-completed',
|
||||
'bracket-match-cancelled',
|
||||
'walkover-awarded',
|
||||
'walkover-cancelled',
|
||||
'reset-final-created',
|
||||
'riot-result-cancelled',
|
||||
];
|
||||
|
||||
export interface DoubleEliminationSeed {
|
||||
seedNumber: number;
|
||||
teamIndex: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchSource {
|
||||
type: 'seed' | 'winner' | 'loser';
|
||||
seedNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchDestination {
|
||||
bracketMatchId: string;
|
||||
position: 'A' | 'B';
|
||||
}
|
||||
|
||||
export interface DoubleEliminationWalkover {
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
awardedBy?: mongoose.Types.ObjectId;
|
||||
awardedAt: Date;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelledAt?: Date;
|
||||
cancelReason?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatch {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
bracketSide: DoubleEliminationBracketSide;
|
||||
roundNumber: number;
|
||||
matchNumber: number;
|
||||
state: DoubleEliminationBracketMatchState;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
teamASource?: DoubleEliminationBracketMatchSource;
|
||||
teamBSource?: DoubleEliminationBracketMatchSource;
|
||||
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
winnerTeamIndex?: number;
|
||||
loserTeamIndex?: number;
|
||||
completedBy?: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationPlacements {
|
||||
firstTeamIndex?: number;
|
||||
secondTeamIndex?: number;
|
||||
thirdTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationEvent {
|
||||
type: DoubleEliminationEventType;
|
||||
bracketMatchId?: string;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
reason?: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracket {
|
||||
teamCount: 4 | 8;
|
||||
resetFinalEnabled: boolean;
|
||||
resetFinalCreated: boolean;
|
||||
seeds: DoubleEliminationSeed[];
|
||||
bracketMatches: DoubleEliminationBracketMatch[];
|
||||
placements: DoubleEliminationPlacements;
|
||||
events: DoubleEliminationEvent[];
|
||||
}
|
||||
|
||||
export interface MatchGameAssignment {
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -564,6 +686,7 @@ export interface Match extends MongooseTimestamps {
|
||||
teams: MatchTeam[];
|
||||
result?: MatchResult;
|
||||
resultPollState?: MatchResultPollState;
|
||||
doubleElimination?: DoubleEliminationBracket;
|
||||
legacyImported?: boolean;
|
||||
legacyImportSource?: {
|
||||
importedAt: Date;
|
||||
@@ -1351,6 +1474,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
},
|
||||
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
|
||||
gameNumber: { type: Number },
|
||||
bracketMatchId: { type: String },
|
||||
reservedAt: { type: Date },
|
||||
usedAt: { type: Date },
|
||||
releasedAt: { type: Date },
|
||||
@@ -1369,6 +1493,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
TournamentCodeSchema.index({ code: 1 }, { unique: true });
|
||||
TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
|
||||
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 });
|
||||
TournamentCodeSchema.index({ matchId: 1, bracketMatchId: 1 }, { sparse: true });
|
||||
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
|
||||
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true });
|
||||
|
||||
@@ -1428,6 +1553,7 @@ const MatchGameResultParticipantSubSchema =
|
||||
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true },
|
||||
bracketMatchId: { type: String, required: false },
|
||||
riotMatchId: { type: String, required: true },
|
||||
blueTeamIndex: { type: Number, required: true, min: 1 },
|
||||
redTeamIndex: { type: Number, required: true, min: 1 },
|
||||
@@ -1446,6 +1572,7 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
|
||||
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: false },
|
||||
teamAIndex: { type: Number, required: true, min: 1 },
|
||||
teamBIndex: { type: Number, required: true, min: 1 },
|
||||
teamAWins: { type: Number, required: true, default: 0 },
|
||||
@@ -1465,6 +1592,158 @@ const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationSeedSubSchema = new Schema<DoubleEliminationSeed>(
|
||||
{
|
||||
seedNumber: { type: Number, required: true, min: 1 },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchSourceSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatchSource>(
|
||||
{
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['seed', 'winner', 'loser'],
|
||||
required: true,
|
||||
},
|
||||
seedNumber: { type: Number, required: false, min: 1 },
|
||||
bracketMatchId: { type: String, required: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchDestinationSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatchDestination>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: true },
|
||||
position: { type: String, enum: ['A', 'B'], required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationWalkoverSubSchema =
|
||||
new Schema<DoubleEliminationWalkover>(
|
||||
{
|
||||
winnerTeamIndex: { type: Number, required: true, min: 1 },
|
||||
reason: { type: String, required: false },
|
||||
awardedBy: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
awardedAt: { type: Date, required: true },
|
||||
cancelledBy: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
cancelledAt: { type: Date },
|
||||
cancelReason: { type: String },
|
||||
active: { type: Boolean, required: true, default: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatch>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: true },
|
||||
gameNumber: { type: Number, required: true, min: 1 },
|
||||
bracketSide: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
|
||||
required: true,
|
||||
},
|
||||
roundNumber: { type: Number, required: true, min: 1 },
|
||||
matchNumber: { type: Number, required: true, min: 1 },
|
||||
state: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_BRACKET_MATCH_STATES,
|
||||
required: true,
|
||||
},
|
||||
teamAIndex: { type: Number, required: false, min: 1 },
|
||||
teamBIndex: { type: Number, required: false, min: 1 },
|
||||
teamASource: {
|
||||
type: DoubleEliminationBracketMatchSourceSubSchema,
|
||||
required: false,
|
||||
},
|
||||
teamBSource: {
|
||||
type: DoubleEliminationBracketMatchSourceSubSchema,
|
||||
required: false,
|
||||
},
|
||||
winnerAdvancesTo: {
|
||||
type: DoubleEliminationBracketMatchDestinationSubSchema,
|
||||
required: false,
|
||||
},
|
||||
loserAdvancesTo: {
|
||||
type: DoubleEliminationBracketMatchDestinationSubSchema,
|
||||
required: false,
|
||||
},
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
loserTeamIndex: { type: Number, required: false, min: 1 },
|
||||
completedBy: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_COMPLETION_TYPES,
|
||||
required: false,
|
||||
},
|
||||
completedAt: { type: Date, required: false },
|
||||
walkover: {
|
||||
type: DoubleEliminationWalkoverSubSchema,
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationPlacementsSubSchema =
|
||||
new Schema<DoubleEliminationPlacements>(
|
||||
{
|
||||
firstTeamIndex: { type: Number, required: false, min: 1 },
|
||||
secondTeamIndex: { type: Number, required: false, min: 1 },
|
||||
thirdTeamIndex: { type: Number, required: false, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
|
||||
{
|
||||
type: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_EVENT_TYPES,
|
||||
required: true,
|
||||
},
|
||||
bracketMatchId: { type: String, required: false },
|
||||
actorUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
reason: { type: String, required: false },
|
||||
createdAt: { type: Date, required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketSubSchema =
|
||||
new Schema<DoubleEliminationBracket>(
|
||||
{
|
||||
teamCount: { type: Number, enum: [4, 8], required: true },
|
||||
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
||||
resetFinalCreated: { type: Boolean, required: true, default: false },
|
||||
seeds: {
|
||||
type: [DoubleEliminationSeedSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
bracketMatches: {
|
||||
type: [DoubleEliminationBracketMatchSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
placements: {
|
||||
type: DoubleEliminationPlacementsSubSchema,
|
||||
required: true,
|
||||
default: () => ({}),
|
||||
},
|
||||
events: {
|
||||
type: [DoubleEliminationEventSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
@@ -1595,6 +1874,10 @@ export const MatchSchema = new Schema<Match>(
|
||||
type: MatchResultPollStateSubSchema,
|
||||
required: false,
|
||||
},
|
||||
doubleElimination: {
|
||||
type: DoubleEliminationBracketSubSchema,
|
||||
required: false,
|
||||
},
|
||||
legacyImported: { type: Boolean, required: false, default: false },
|
||||
legacyImportSource: {
|
||||
type: MatchLegacyImportSourceSubSchema,
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ArrayMinSize,
|
||||
registerDecorator,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDate,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
@@ -106,6 +107,10 @@ export class CreateMatchDto {
|
||||
@Min(1)
|
||||
roundRobinMaxRounds?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -166,6 +171,10 @@ export class UpdateMatchDto {
|
||||
@Min(1)
|
||||
roundRobinMaxRounds?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -217,3 +226,31 @@ export class AddParticipantDto {
|
||||
@IsString()
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
export class SwapDoubleEliminationSeedsDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
leftSeedNumber!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
rightSeedNumber!: number;
|
||||
}
|
||||
|
||||
export class ApplyDoubleEliminationWalkoverDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
winnerTeamIndex!: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export class CancelDoubleEliminationActionDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
reason?: string;
|
||||
}
|
||||
@@ -25,8 +25,11 @@ import type {
|
||||
} from '../global/database/schema';
|
||||
import {
|
||||
AddParticipantDto,
|
||||
ApplyDoubleEliminationWalkoverDto,
|
||||
CancelDoubleEliminationActionDto,
|
||||
CreateMatchDto,
|
||||
JoinMatchDto,
|
||||
SwapDoubleEliminationSeedsDto,
|
||||
UpdateMatchDto,
|
||||
UpdateParticipantDto,
|
||||
} from './dto/create-match.dto';
|
||||
@@ -58,6 +61,8 @@ export class MatchController {
|
||||
gameCount: body.gameCount,
|
||||
gameMode: body.gameMode ?? 'pair',
|
||||
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
body.doubleEliminationResetFinalEnabled,
|
||||
prizes: body.prizes ?? [],
|
||||
notices: body.notices ?? [],
|
||||
schedule: body.schedule ?? [],
|
||||
@@ -121,6 +126,116 @@ export class MatchController {
|
||||
return this.matchService.update({ matchId, communityId, patch: body });
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/seeds/reshuffle')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async reshuffleDoubleEliminationSeeds(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.reshuffleDoubleEliminationSeeds({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/seeds/swap')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async swapDoubleEliminationSeeds(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: SwapDoubleEliminationSeedsDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.swapDoubleEliminationSeeds({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
leftSeedNumber: body.leftSeedNumber,
|
||||
rightSeedNumber: body.rightSeedNumber,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async applyDoubleEliminationWalkover(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: ApplyDoubleEliminationWalkoverDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.applyDoubleEliminationWalkover({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
winnerTeamIndex: body.winnerTeamIndex,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(
|
||||
':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel',
|
||||
)
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async cancelDoubleEliminationWalkover(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: CancelDoubleEliminationActionDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.cancelDoubleEliminationWalkover({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(
|
||||
':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel',
|
||||
)
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async cancelDoubleEliminationRiotResult(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: CancelDoubleEliminationActionDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.cancelDoubleEliminationRiotResult({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Delete(':matchId')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
|
||||
@@ -2,6 +2,55 @@ import mongoose from 'mongoose';
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
describe('MatchService', () => {
|
||||
function createServiceWithCreateModels() {
|
||||
const createdPayloads: Record<string, unknown>[] = [];
|
||||
const MatchModel = {
|
||||
create: jest.fn().mockImplementation(async (payload) => {
|
||||
createdPayloads.push(payload);
|
||||
return payload;
|
||||
}),
|
||||
exists: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const CommunityModel = {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchGameCount: 3 }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return MatchModel;
|
||||
if (name === 'community') return CommunityModel;
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
const tournamentCodeService = {
|
||||
buildSlots: jest.fn().mockResolvedValue([]),
|
||||
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const communityStatsService = {
|
||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const matchStatsService = {
|
||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||
removeByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
return {
|
||||
service: new MatchService(
|
||||
connectionService as never,
|
||||
tournamentCodeService as never,
|
||||
communityStatsService as never,
|
||||
matchStatsService as never,
|
||||
),
|
||||
MatchModel,
|
||||
createdPayloads,
|
||||
};
|
||||
}
|
||||
|
||||
function createService(match: Record<string, unknown>) {
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
@@ -254,6 +303,57 @@ describe('MatchService', () => {
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('normalizes double-elimination match creation', async () => {
|
||||
const { service, createdPayloads } = createServiceWithCreateModels();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
|
||||
await service.create({
|
||||
communityId,
|
||||
data: {
|
||||
title: 'Double elimination',
|
||||
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
maxParticipants: 20,
|
||||
gameCount: 5,
|
||||
gameMode: 'double-elimination',
|
||||
doubleEliminationResetFinalEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(createdPayloads[0]).toMatchObject({
|
||||
communityId,
|
||||
maxParticipants: 20,
|
||||
gameCount: 1,
|
||||
gameMode: 'double-elimination',
|
||||
roundRobinMaxRounds: undefined,
|
||||
doubleElimination: {
|
||||
teamCount: 4,
|
||||
resetFinalEnabled: true,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects unsupported double-elimination participant counts', async () => {
|
||||
const { service, MatchModel } = createServiceWithCreateModels();
|
||||
|
||||
await expect(
|
||||
service.create({
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
data: {
|
||||
title: 'Invalid double elimination',
|
||||
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
maxParticipants: 30,
|
||||
gameMode: 'double-elimination',
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow('Double elimination supports only 20 or 40 participants.');
|
||||
expect(MatchModel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears game schedule when a built match returns to recruiting', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
@@ -310,7 +410,7 @@ describe('MatchService', () => {
|
||||
patch: { roundRobinMaxRounds: 3 },
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
|
||||
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
expect(match.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -5,12 +5,19 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
cancelDoubleEliminationBracketMatch,
|
||||
completeDoubleEliminationBracketMatch,
|
||||
reshuffleDoubleEliminationSeeds,
|
||||
swapDoubleEliminationSeeds,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
Match,
|
||||
MatchDocument,
|
||||
MatchGameMode,
|
||||
MatchSeriesResult,
|
||||
MatchStatus,
|
||||
POSITIONS,
|
||||
@@ -26,17 +33,24 @@ const MATCH_SHORT_CODE_LENGTH = 4;
|
||||
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
||||
const MAX_MATCH_LIST_LIMIT = 200;
|
||||
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
|
||||
|
||||
interface DoubleEliminationConfigInput {
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
}
|
||||
|
||||
interface CreateMatchParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
|
||||
data: Partial<Match> &
|
||||
Pick<Match, 'title' | 'scheduledAt'> &
|
||||
DoubleEliminationConfigInput;
|
||||
}
|
||||
|
||||
interface UpdateMatchParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
patch: Partial<Match>;
|
||||
patch: Partial<Match> & DoubleEliminationConfigInput;
|
||||
}
|
||||
|
||||
interface ListMatchesQuery {
|
||||
@@ -89,6 +103,31 @@ interface UpdateParticipantPositionsParams {
|
||||
subPosition: Position;
|
||||
}
|
||||
|
||||
interface DoubleEliminationAdminParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
actorUserId: mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
interface SwapDoubleEliminationSeedsParams
|
||||
extends DoubleEliminationAdminParams {
|
||||
leftSeedNumber: number;
|
||||
rightSeedNumber: number;
|
||||
}
|
||||
|
||||
interface ApplyDoubleEliminationWalkoverParams
|
||||
extends DoubleEliminationAdminParams {
|
||||
bracketMatchId: string;
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface CancelDoubleEliminationActionParams
|
||||
extends DoubleEliminationAdminParams {
|
||||
bracketMatchId: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(
|
||||
@@ -105,15 +144,18 @@ export class MatchService {
|
||||
.select({ matchGameCount: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
return MatchModel.create({
|
||||
const normalizedData = this.normalizeMatchConfig({
|
||||
...params.data,
|
||||
shortCode:
|
||||
params.data.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
gameCount:
|
||||
params.data.gameCount ??
|
||||
community?.matchGameCount ??
|
||||
DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
});
|
||||
return MatchModel.create({
|
||||
...normalizedData,
|
||||
shortCode:
|
||||
normalizedData.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
communityId: params.communityId,
|
||||
hostUserId: params.hostUserId,
|
||||
});
|
||||
@@ -216,13 +258,30 @@ export class MatchService {
|
||||
previousStatus !== 'recruiting' &&
|
||||
('maxParticipants' in params.patch ||
|
||||
'gameMode' in params.patch ||
|
||||
'roundRobinMaxRounds' in params.patch)
|
||||
'roundRobinMaxRounds' in params.patch ||
|
||||
'doubleEliminationResetFinalEnabled' in params.patch)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
|
||||
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
}
|
||||
match.set(params.patch);
|
||||
const patchToSet =
|
||||
previousStatus === 'recruiting'
|
||||
? this.normalizeMatchConfig({
|
||||
...params.patch,
|
||||
gameMode: params.patch.gameMode ?? match.gameMode,
|
||||
maxParticipants:
|
||||
params.patch.maxParticipants ?? match.maxParticipants,
|
||||
gameCount: params.patch.gameCount ?? match.gameCount,
|
||||
roundRobinMaxRounds:
|
||||
params.patch.roundRobinMaxRounds ?? match.roundRobinMaxRounds,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
params.patch.doubleEliminationResetFinalEnabled ??
|
||||
params.patch.doubleElimination?.resetFinalEnabled ??
|
||||
match.doubleElimination?.resetFinalEnabled,
|
||||
})
|
||||
: this.stripMatchConfigInput(params.patch);
|
||||
match.set(patchToSet);
|
||||
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||
if (match.tournamentCodeIds.length > 0) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
@@ -260,6 +319,174 @@ export class MatchService {
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
|
||||
public async reshuffleDoubleEliminationSeeds(
|
||||
params: DoubleEliminationAdminParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
await this.assertDoubleEliminationSeedsCanChange(match);
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = reshuffleDoubleEliminationSeeds(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'seeds-reshuffled',
|
||||
actorUserId: params.actorUserId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async swapDoubleEliminationSeeds(
|
||||
params: SwapDoubleEliminationSeedsParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
await this.assertDoubleEliminationSeedsCanChange(match);
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = swapDoubleEliminationSeeds(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
leftSeedNumber: params.leftSeedNumber,
|
||||
rightSeedNumber: params.rightSeedNumber,
|
||||
},
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'seeds-swapped',
|
||||
actorUserId: params.actorUserId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async applyDoubleEliminationWalkover(
|
||||
params: ApplyDoubleEliminationWalkoverParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const bracketMatch = this.requireDoubleEliminationBracketMatch(
|
||||
match,
|
||||
params.bracketMatchId,
|
||||
);
|
||||
if (bracketMatch.state !== 'ready') {
|
||||
throw new BadRequestException('Bracket match is not ready.');
|
||||
}
|
||||
if (
|
||||
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
|
||||
bracketMatch.teamBIndex !== params.winnerTeamIndex
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Winner team is not assigned to this bracket match.',
|
||||
);
|
||||
}
|
||||
|
||||
await this.releaseReservedDoubleEliminationCodes(match, [
|
||||
params.bracketMatchId,
|
||||
]);
|
||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
winnerTeamIndex: params.winnerTeamIndex,
|
||||
completedBy: 'walkover',
|
||||
completedAt: new Date(),
|
||||
walkover: {
|
||||
winnerTeamIndex: params.winnerTeamIndex,
|
||||
reason: params.reason,
|
||||
awardedBy: params.actorUserId,
|
||||
awardedAt: new Date(),
|
||||
active: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
match.markModified('doubleElimination');
|
||||
this.syncDoubleEliminationWinner(match);
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelDoubleEliminationWalkover(
|
||||
params: CancelDoubleEliminationActionParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const bracketMatch = this.requireDoubleEliminationBracketMatch(
|
||||
match,
|
||||
params.bracketMatchId,
|
||||
);
|
||||
if (
|
||||
bracketMatch.completedBy !== 'walkover' ||
|
||||
!bracketMatch.walkover?.active
|
||||
) {
|
||||
throw new BadRequestException('Active walkover was not found.');
|
||||
}
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = cancelDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
cancelledBy: params.actorUserId,
|
||||
cancelReason: params.reason,
|
||||
},
|
||||
);
|
||||
match.markModified('doubleElimination');
|
||||
this.syncDoubleEliminationWinner(match);
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelDoubleEliminationRiotResult(
|
||||
params: CancelDoubleEliminationActionParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const game = match.result?.games?.find(
|
||||
(entry) => entry.bracketMatchId === params.bracketMatchId,
|
||||
);
|
||||
if (!game) throw new NotFoundException('Collected result not found.');
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = cancelDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
cancelledBy: params.actorUserId,
|
||||
cancelReason: params.reason,
|
||||
},
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'riot-result-cancelled',
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
actorUserId: params.actorUserId,
|
||||
reason: params.reason,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
const games = (match.result?.games ?? []).filter(
|
||||
(entry) => entry.bracketMatchId !== params.bracketMatchId,
|
||||
);
|
||||
match.result = {
|
||||
winnerTeamIndex: undefined,
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: (match.result?.riotMatchIds ?? []).filter(
|
||||
(riotMatchId) => riotMatchId !== game.riotMatchId,
|
||||
),
|
||||
games,
|
||||
seriesResults: this.buildSeriesResults(games),
|
||||
};
|
||||
await this.voidDoubleEliminationCode(match, params.bracketMatchId);
|
||||
if (match.status === 'finished') match.status = 'in-progress';
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async join(params: JoinMatchParams): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
@@ -307,6 +534,192 @@ export class MatchService {
|
||||
return match;
|
||||
}
|
||||
|
||||
private normalizeMatchConfig<T extends Partial<Match> & DoubleEliminationConfigInput>(
|
||||
input: T,
|
||||
): Partial<Match> {
|
||||
const patch = this.stripMatchConfigInput(input);
|
||||
const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode;
|
||||
const maxParticipants = patch.maxParticipants ?? 10;
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
if (
|
||||
!DOUBLE_ELIMINATION_PARTICIPANT_COUNTS.includes(
|
||||
maxParticipants as (typeof DOUBLE_ELIMINATION_PARTICIPANT_COUNTS)[number],
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Double elimination supports only 20 or 40 participants.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
...patch,
|
||||
gameMode,
|
||||
maxParticipants,
|
||||
gameCount: 1,
|
||||
roundRobinMaxRounds: undefined,
|
||||
gameSchedule: [],
|
||||
doubleElimination: {
|
||||
teamCount: (maxParticipants / 5) as 4 | 8,
|
||||
resetFinalEnabled:
|
||||
input.doubleEliminationResetFinalEnabled ??
|
||||
input.doubleElimination?.resetFinalEnabled ??
|
||||
false,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...patch,
|
||||
gameMode,
|
||||
doubleElimination: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private stripMatchConfigInput<T extends Partial<Match> & DoubleEliminationConfigInput>(
|
||||
input: T,
|
||||
): Partial<Match> {
|
||||
const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input;
|
||||
return patch;
|
||||
}
|
||||
|
||||
private async loadDoubleEliminationMatch(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
let match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') {
|
||||
throw new BadRequestException('Match is not double elimination.');
|
||||
}
|
||||
if (!match.doubleElimination?.bracketMatches?.length) {
|
||||
match = await this.tournamentCodeService.reserveForMatch(match);
|
||||
}
|
||||
if (!match.doubleElimination?.bracketMatches?.length) {
|
||||
throw new BadRequestException('Double elimination bracket is not ready.');
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private async assertDoubleEliminationSeedsCanChange(
|
||||
match: MatchDocument,
|
||||
): Promise<void> {
|
||||
if (
|
||||
match.doubleElimination?.bracketMatches.some(
|
||||
(bracketMatch) => bracketMatch.state === 'completed',
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Seeds cannot be changed after a bracket match is completed.',
|
||||
);
|
||||
}
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const usedCode = await TournamentCodeModel.exists({
|
||||
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||
$or: [{ state: 'used' }, { riotMatchId: { $exists: true } }],
|
||||
});
|
||||
if (usedCode) {
|
||||
throw new BadRequestException(
|
||||
'Seeds cannot be changed after a tournament code is used.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private requireDoubleEliminationBracketMatch(
|
||||
match: MatchDocument,
|
||||
bracketMatchId: string,
|
||||
) {
|
||||
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === bracketMatchId,
|
||||
);
|
||||
if (!bracketMatch) throw new NotFoundException('Bracket match not found.');
|
||||
return bracketMatch;
|
||||
}
|
||||
|
||||
private async releaseReservedDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
bracketMatchIds?: string[],
|
||||
): Promise<void> {
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
if (ids.length === 0) return;
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const codes = await TournamentCodeModel.find({
|
||||
_id: { $in: ids },
|
||||
matchId: match._id,
|
||||
state: 'reserved',
|
||||
...(bracketMatchIds
|
||||
? { bracketMatchId: { $in: bracketMatchIds } }
|
||||
: { bracketMatchId: { $exists: true } }),
|
||||
}).exec();
|
||||
if (codes.length === 0) return;
|
||||
const releasedIds = codes.map((code) => code._id.toString());
|
||||
await TournamentCodeModel.updateMany(
|
||||
{ _id: { $in: codes.map((code) => code._id) } },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
match.tournamentCodeIds = ids.filter(
|
||||
(id) => !releasedIds.includes(id.toString()),
|
||||
);
|
||||
}
|
||||
|
||||
private async voidDoubleEliminationCode(
|
||||
match: MatchDocument,
|
||||
bracketMatchId: string,
|
||||
): Promise<void> {
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
await TournamentCodeModel.updateOne(
|
||||
{
|
||||
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||
matchId: match._id,
|
||||
bracketMatchId,
|
||||
state: 'used',
|
||||
},
|
||||
{
|
||||
$set: { state: 'voided' },
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
private syncDoubleEliminationWinner(match: MatchDocument): void {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
const firstTeamIndex = match.doubleElimination?.placements.firstTeamIndex;
|
||||
if (firstTeamIndex) {
|
||||
match.status = 'finished';
|
||||
match.result = match.result ?? {
|
||||
riotMatchIds: [],
|
||||
games: [],
|
||||
seriesResults: [],
|
||||
};
|
||||
match.result.winnerTeamIndex = firstTeamIndex;
|
||||
return;
|
||||
}
|
||||
if (match.status === 'finished') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async cancelJoin(
|
||||
params: CancelMatchJoinParams,
|
||||
): Promise<MatchDocument> {
|
||||
@@ -539,10 +952,11 @@ export class MatchService {
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
({
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
|
||||
@@ -28,10 +28,11 @@ function createService() {
|
||||
|
||||
interface MatchOverrides {
|
||||
gameCount?: number;
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||
roundRobinMaxRounds?: number;
|
||||
participants?: Array<{ excluded?: boolean }>;
|
||||
teams?: Array<{ teamIndex: number }>;
|
||||
doubleElimination?: MatchDocument['doubleElimination'];
|
||||
gameSchedule?: Array<{
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -51,6 +52,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
markModified: jest.fn(),
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
@@ -206,6 +208,35 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
expect(pair.gameSchedule).toEqual([]);
|
||||
});
|
||||
|
||||
it('creates a double-elimination bracket from built teams', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||
teamIndex: index + 1,
|
||||
})),
|
||||
doubleElimination: {
|
||||
teamCount: 4,
|
||||
resetFinalEnabled: true,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
|
||||
service.ensureGameSchedule(match);
|
||||
|
||||
expect(match.doubleElimination?.seeds).toHaveLength(4);
|
||||
expect(match.doubleElimination?.bracketMatches).toHaveLength(6);
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.filter(
|
||||
(bracketMatch) => bracketMatch.state === 'ready',
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
||||
const service = createService();
|
||||
const roundRobin = createMatch({
|
||||
|
||||
@@ -4,8 +4,13 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
buildDoubleEliminationBracket,
|
||||
findNextReadyDoubleEliminationBracketMatches,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
DoubleEliminationBracketMatch,
|
||||
MatchGameAssignment,
|
||||
MatchDocument,
|
||||
TournamentCode,
|
||||
@@ -239,8 +244,12 @@ export class TournamentCodeService {
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.reserveForDoubleEliminationMatch(match, TournamentCodeModel);
|
||||
}
|
||||
const shouldSaveMetadata =
|
||||
match.isModified('gameCount') || match.isModified('gameSchedule');
|
||||
this.isMatchModified(match, 'gameCount') ||
|
||||
this.isMatchModified(match, 'gameSchedule');
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||
if (need <= 0) {
|
||||
@@ -309,6 +318,13 @@ export class TournamentCodeService {
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
const doubleEliminationBracketMatch =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
if (
|
||||
@@ -320,7 +336,11 @@ export class TournamentCodeService {
|
||||
}
|
||||
if (
|
||||
(match.result?.games ?? []).some(
|
||||
(game) => game.gameNumber === params.gameNumber,
|
||||
(game) =>
|
||||
game.gameNumber === params.gameNumber ||
|
||||
(doubleEliminationBracketMatch?.bracketMatchId &&
|
||||
game.bracketMatchId ===
|
||||
doubleEliminationBracketMatch.bracketMatchId),
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
@@ -331,7 +351,9 @@ export class TournamentCodeService {
|
||||
const currentCode = await TournamentCodeModel.findOne({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId }
|
||||
: { gameNumber: params.gameNumber }),
|
||||
}).exec();
|
||||
if (!currentCode) {
|
||||
throw new NotFoundException('Assigned tournament code not found.');
|
||||
@@ -358,6 +380,11 @@ export class TournamentCodeService {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? {
|
||||
bracketMatchId: doubleEliminationBracketMatch.bracketMatchId,
|
||||
}
|
||||
: {}),
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
@@ -373,6 +400,7 @@ export class TournamentCodeService {
|
||||
currentCode.state = 'released';
|
||||
currentCode.matchId = undefined;
|
||||
currentCode.gameNumber = undefined;
|
||||
currentCode.bracketMatchId = undefined;
|
||||
currentCode.reservedAt = undefined;
|
||||
currentCode.releasedAt = new Date();
|
||||
currentCode.riotMatchId = undefined;
|
||||
@@ -386,6 +414,9 @@ export class TournamentCodeService {
|
||||
|
||||
return {
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch)
|
||||
: {}),
|
||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
@@ -415,7 +446,12 @@ export class TournamentCodeService {
|
||||
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: { matchId: 1, gameNumber: 1, reservedAt: 1 },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
|
||||
@@ -483,6 +519,9 @@ export class TournamentCodeService {
|
||||
public async buildSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.buildDoubleEliminationSlots(match);
|
||||
}
|
||||
if (
|
||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||
@@ -550,10 +589,130 @@ export class TournamentCodeService {
|
||||
return next;
|
||||
}
|
||||
|
||||
private async reserveForDoubleEliminationMatch(
|
||||
match: MatchDocument,
|
||||
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||
): Promise<MatchDocument> {
|
||||
const readyBracketMatches = findNextReadyDoubleEliminationBracketMatches(
|
||||
match.doubleElimination,
|
||||
);
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}).exec()
|
||||
: [];
|
||||
const byBracketMatchId = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
|
||||
for (const bracketMatch of readyBracketMatches) {
|
||||
if (byBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: DEFAULT_REGION,
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
byBracketMatchId.set(bracketMatch.bracketMatchId, code);
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0) {
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
}
|
||||
if (
|
||||
reservedIds.length > 0 ||
|
||||
this.isMatchModified(match, 'doubleElimination')
|
||||
) {
|
||||
await match.save();
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private async buildDoubleEliminationSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
this.ensureGameSchedule(match);
|
||||
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
|
||||
if (bracketMatches.length === 0) return [];
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
const codes =
|
||||
ids.length > 0
|
||||
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||
: [];
|
||||
const byBracketMatchId = new Map(
|
||||
codes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
code.state !== 'released' &&
|
||||
code.state !== 'voided',
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
|
||||
return bracketMatches.map((bracketMatch) => {
|
||||
const code = byBracketMatchId.get(bracketMatch.bracketMatchId);
|
||||
return {
|
||||
...this.toDoubleEliminationSlotBase(bracketMatch),
|
||||
code: code?.code ?? null,
|
||||
expiresAt: code?.expiresAt.toISOString() ?? null,
|
||||
state: code?.state ?? 'pending',
|
||||
riotMatchId: code?.riotMatchId ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private toDoubleEliminationSlotBase(
|
||||
bracketMatch: DoubleEliminationBracketMatch,
|
||||
): Omit<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
|
||||
return {
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
bracketSide: bracketMatch.bracketSide,
|
||||
roundNumber: bracketMatch.roundNumber,
|
||||
matchNumber: bracketMatch.matchNumber,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRequiredSlots(match: MatchDocument): number {
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
@@ -577,6 +736,17 @@ export class TournamentCodeService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match,
|
||||
gameNumber,
|
||||
);
|
||||
return {
|
||||
teamAIndex: bracketMatch?.teamAIndex ?? 1,
|
||||
teamBIndex: bracketMatch?.teamBIndex ?? 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -611,6 +781,10 @@ export class TournamentCodeService {
|
||||
}
|
||||
|
||||
private ensureGameSchedule(match: MatchDocument): void {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
this.ensureDoubleEliminationBracket(match);
|
||||
return;
|
||||
}
|
||||
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
||||
|
||||
@@ -620,6 +794,48 @@ export class TournamentCodeService {
|
||||
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
|
||||
}
|
||||
|
||||
private ensureDoubleEliminationBracket(match: MatchDocument): void {
|
||||
if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return;
|
||||
const teamIndexes = [...(match.teams ?? [])]
|
||||
.map((team) => team.teamIndex)
|
||||
.sort((left, right) => left - right);
|
||||
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
|
||||
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
|
||||
match.doubleElimination = buildDoubleEliminationBracket(
|
||||
shuffledTeamIndexes,
|
||||
{
|
||||
resetFinalEnabled:
|
||||
match.doubleElimination?.resetFinalEnabled ?? false,
|
||||
},
|
||||
);
|
||||
match.markModified?.('doubleElimination');
|
||||
}
|
||||
|
||||
private resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): DoubleEliminationBracketMatch | undefined {
|
||||
return match.doubleElimination?.bracketMatches.find(
|
||||
(bracketMatch) => bracketMatch.gameNumber === gameNumber,
|
||||
);
|
||||
}
|
||||
|
||||
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
|
||||
const shuffled = [...teamIndexes];
|
||||
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffled[index], shuffled[swapIndex]] = [
|
||||
shuffled[swapIndex],
|
||||
shuffled[index],
|
||||
];
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
private isMatchModified(match: MatchDocument, path: string): boolean {
|
||||
return typeof match.isModified === 'function' && match.isModified(path);
|
||||
}
|
||||
|
||||
private resolveRoundNumberForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
|
||||
@@ -24,9 +24,12 @@ export interface BulkUploadTournamentCodesResponse {
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
bracketSide?: string;
|
||||
roundNumber?: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
matchNumber?: number;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
|
||||
@@ -10,6 +10,9 @@ type TournamentResultServiceInternals = TournamentResultService & {
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { teamAIndex: number; teamBIndex: number };
|
||||
buildSeriesResults(
|
||||
games: NonNullable<MatchDocument['result']>['games'],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'];
|
||||
};
|
||||
|
||||
function createService() {
|
||||
@@ -100,6 +103,56 @@ describe('TournamentResultService round-robin scheduling', () => {
|
||||
teamBIndex: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps double-elimination rematches separated by bracket match id', () => {
|
||||
const service = createService();
|
||||
|
||||
expect(
|
||||
service.buildSeriesResults([
|
||||
{
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
riotMatchId: 'KR_1',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
gameCreation: 1,
|
||||
gameDuration: 1800,
|
||||
participants: [],
|
||||
},
|
||||
{
|
||||
gameNumber: 2,
|
||||
bracketMatchId: 'GF',
|
||||
riotMatchId: 'KR_2',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 2,
|
||||
winnerSide: 'red',
|
||||
gameCreation: 2,
|
||||
gameDuration: 1800,
|
||||
participants: [],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
bracketMatchId: 'GF',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 0,
|
||||
teamBWins: 1,
|
||||
winnerTeamIndex: 2,
|
||||
},
|
||||
{
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService tournament code polling', () => {
|
||||
|
||||
@@ -5,12 +5,16 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
completeDoubleEliminationBracketMatch,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
MatchSeriesResult,
|
||||
RiotMatch as StoredRiotMatch,
|
||||
TournamentCodeDocument,
|
||||
} from '../global/database/schema';
|
||||
@@ -22,6 +26,7 @@ import {
|
||||
roundRobinGameSchedule,
|
||||
resolveRoundRobinTeamCount,
|
||||
} from '../tournament-code/round-robin.util';
|
||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
collectCaptainUserIds,
|
||||
@@ -44,6 +49,7 @@ const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
|
||||
|
||||
interface ManualGameAssignment {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
}
|
||||
@@ -207,7 +213,11 @@ export class TournamentResultService {
|
||||
(code) => code.state === 'reserved' && !code.riotMatchId,
|
||||
);
|
||||
if (unmatched.length === 0) {
|
||||
await this.advanceMatchIfReady(match, codes);
|
||||
const completed = await this.advanceMatchIfReady(match, codes);
|
||||
if (!completed) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.scheduleNextPoll(match, job);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -324,6 +334,7 @@ export class TournamentResultService {
|
||||
return false;
|
||||
}
|
||||
|
||||
gameResult.bracketMatchId = code.bracketMatchId;
|
||||
code.state = 'used';
|
||||
code.usedAt = new Date(
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
@@ -332,10 +343,12 @@ export class TournamentResultService {
|
||||
await code.save();
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||
if (match.status === 'team-built') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
await match.save();
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
return true;
|
||||
}
|
||||
@@ -365,6 +378,7 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||
await this.markTournamentCodeUsedForManualResult(
|
||||
match,
|
||||
gameResult,
|
||||
@@ -379,6 +393,9 @@ export class TournamentResultService {
|
||||
}
|
||||
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
||||
await match.save();
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
}
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
}
|
||||
@@ -399,6 +416,36 @@ export class TournamentResultService {
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
): Promise<boolean> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
if (!this.isDoubleEliminationComplete(match)) return false;
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination?.placements.firstTeamIndex;
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: match.resultPollState?.lastPolledAt,
|
||||
lastPollOutcome: match.resultPollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids:
|
||||
match.resultPollState?.expandedToAllPuuids ?? false,
|
||||
state: 'complete',
|
||||
};
|
||||
await match.save();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
void this.communityStatsService
|
||||
.invalidateCommunity(match.communityId)
|
||||
.catch((error) => {
|
||||
this.logger.warn(
|
||||
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
@@ -585,7 +632,10 @@ export class TournamentResultService {
|
||||
const seriesResults = this.buildSeriesResults(games);
|
||||
|
||||
match.result = {
|
||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
winnerTeamIndex:
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
@@ -607,7 +657,10 @@ export class TournamentResultService {
|
||||
teamAIndex: assignment.teamAIndex,
|
||||
teamBIndex: assignment.teamBIndex,
|
||||
});
|
||||
if (gameResult) return gameResult;
|
||||
if (gameResult) {
|
||||
gameResult.bracketMatchId = assignment.bracketMatchId;
|
||||
return gameResult;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -618,7 +671,26 @@ export class TournamentResultService {
|
||||
const usedGameNumbers = new Set(
|
||||
(match.result?.games ?? []).map((game) => game.gameNumber),
|
||||
);
|
||||
const usedBracketMatchIds = new Set(
|
||||
(match.result?.games ?? [])
|
||||
.map((game) => game.bracketMatchId)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
);
|
||||
const assignments: ManualGameAssignment[] = [];
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) {
|
||||
if (bracketMatch.state !== 'ready') continue;
|
||||
if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue;
|
||||
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
||||
assignments.push({
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
});
|
||||
}
|
||||
return assignments;
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
|
||||
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
|
||||
@@ -641,6 +713,9 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
private hasAllRequiredGameResults(match: MatchDocument): boolean {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.isDoubleEliminationComplete(match);
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
if (requiredSlots <= 0) return false;
|
||||
const resultGameNumbers = new Set(
|
||||
@@ -671,9 +746,10 @@ export class TournamentResultService {
|
||||
): Promise<void> {
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
||||
match.result.seriesResults ?? [],
|
||||
);
|
||||
match.result.winnerTeamIndex =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []);
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
@@ -708,6 +784,97 @@ export class TournamentResultService {
|
||||
}
|
||||
}
|
||||
|
||||
private advanceDoubleEliminationIfNeeded(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
completedBy: 'riot-result' | 'walkover',
|
||||
): void {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
if (!match.doubleElimination || !gameResult.bracketMatchId) return;
|
||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||
match.doubleElimination,
|
||||
{
|
||||
bracketMatchId: gameResult.bracketMatchId,
|
||||
winnerTeamIndex: gameResult.winnerTeamIndex,
|
||||
completedBy,
|
||||
completedAt: new Date(gameResult.gameCreation),
|
||||
},
|
||||
);
|
||||
if (match.result && this.isDoubleEliminationComplete(match)) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination!.placements.firstTeamIndex;
|
||||
}
|
||||
match.markModified?.('doubleElimination');
|
||||
}
|
||||
|
||||
private isDoubleEliminationComplete(match: MatchDocument): boolean {
|
||||
const placements = match.doubleElimination?.placements;
|
||||
return Boolean(
|
||||
placements?.firstTeamIndex &&
|
||||
placements.secondTeamIndex &&
|
||||
placements.thirdTeamIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private async reserveReadyDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
): Promise<void> {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
const readyBracketMatches = (match.doubleElimination?.bracketMatches ?? [])
|
||||
.filter((bracketMatch) => bracketMatch.state === 'ready');
|
||||
if (readyBracketMatches.length === 0) return;
|
||||
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}).exec()
|
||||
: [];
|
||||
const existingByBracketMatchId = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
|
||||
for (const bracketMatch of readyBracketMatches) {
|
||||
if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: 'kr',
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
}
|
||||
|
||||
if (reservedIds.length === 0) return;
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
await match.save();
|
||||
}
|
||||
|
||||
private async markTournamentCodeUsedForManualResult(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
@@ -718,7 +885,9 @@ export class TournamentResultService {
|
||||
await TournamentCodeModel.updateOne(
|
||||
{
|
||||
matchId: match._id,
|
||||
gameNumber: gameResult.gameNumber,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: { gameNumber: gameResult.gameNumber }),
|
||||
state: { $in: ['reserved', 'released'] },
|
||||
},
|
||||
{
|
||||
@@ -728,6 +897,9 @@ export class TournamentResultService {
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
),
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
@@ -736,22 +908,14 @@ export class TournamentResultService {
|
||||
private buildSeriesResults(
|
||||
games: MatchGameResult[],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
const bySeries = new Map<string, MatchSeriesResult>();
|
||||
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
@@ -770,6 +934,9 @@ export class TournamentResultService {
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
(left.bracketMatchId ?? '').localeCompare(
|
||||
right.bracketMatchId ?? '',
|
||||
) ||
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
@@ -781,6 +948,21 @@ export class TournamentResultService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
);
|
||||
return bracketMatch
|
||||
? {
|
||||
teamAIndex: bracketMatch.teamAIndex ?? 1,
|
||||
teamBIndex: bracketMatch.teamBIndex ?? 2,
|
||||
}
|
||||
: {
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -816,6 +998,9 @@ export class TournamentResultService {
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
if (gameMode === 'double-elimination') {
|
||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||
}
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
|
||||
Reference in new issue
Block a user