feat: add double elimination match mode

This commit is contained in:
dahyeon committed 2026-06-26 05:00:08 -07:00
1 parent b9aaf55193
commit e12f182e7f
19 files changed
+3415 -58

No files matched your search

@@ -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();
});
+424 -10
View File
@@ -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,