1076 lines
35 KiB
TypeScript
1076 lines
35 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
Injectable,
|
|
InternalServerErrorException,
|
|
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,
|
|
Position,
|
|
PositionPreference,
|
|
TierInfo,
|
|
} from '../global/database/schema';
|
|
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
|
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
|
|
|
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
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;
|
|
const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
|
|
|
|
interface DoubleEliminationConfigInput {
|
|
doubleEliminationResetFinalEnabled?: boolean;
|
|
}
|
|
|
|
interface CreateMatchParams {
|
|
communityId: mongoose.Types.ObjectId;
|
|
hostUserId?: mongoose.Types.ObjectId;
|
|
data: Partial<Match> &
|
|
Pick<Match, 'title' | 'scheduledAt'> &
|
|
DoubleEliminationConfigInput;
|
|
}
|
|
|
|
interface UpdateMatchParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
patch: Partial<Match> & DoubleEliminationConfigInput;
|
|
}
|
|
|
|
interface ListMatchesQuery {
|
|
communityId: mongoose.Types.ObjectId;
|
|
status?: MatchStatus;
|
|
limit?: number;
|
|
scheduledFrom?: Date;
|
|
scheduledTo?: Date;
|
|
sort?: 'asc' | 'desc';
|
|
}
|
|
|
|
interface ListMatchesPageQuery extends ListMatchesQuery {
|
|
page?: number;
|
|
offset?: number;
|
|
}
|
|
|
|
interface MatchListFilter {
|
|
communityId: mongoose.Types.ObjectId;
|
|
status?: MatchStatus;
|
|
scheduledAt?: {
|
|
$gte?: Date;
|
|
$lt?: Date;
|
|
};
|
|
}
|
|
|
|
interface JoinMatchParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
userId: mongoose.Types.ObjectId;
|
|
preferredPositions?: PositionPreference[];
|
|
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
|
|
riotPuuid?: string;
|
|
}
|
|
|
|
interface CancelMatchJoinParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
userId: mongoose.Types.ObjectId;
|
|
}
|
|
|
|
interface RemoveParticipantParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
targetUserId: mongoose.Types.ObjectId;
|
|
}
|
|
|
|
interface UpdateParticipantPositionsParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
targetUserId: mongoose.Types.ObjectId;
|
|
mainPosition: Position;
|
|
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(
|
|
private readonly connectionService: ConnectionService,
|
|
private readonly tournamentCodeService: TournamentCodeService,
|
|
private readonly communityStatsService: CommunityStatsService,
|
|
private readonly matchStatsService: MatchStatsService,
|
|
) {}
|
|
|
|
public async create(params: CreateMatchParams): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const CommunityModel = await this.connectionService.getModel('community');
|
|
const community = await CommunityModel.findById(params.communityId)
|
|
.select({ matchGameCount: 1 })
|
|
.lean()
|
|
.exec();
|
|
const normalizedData = this.normalizeMatchConfig({
|
|
...params.data,
|
|
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,
|
|
});
|
|
}
|
|
|
|
public async list(query: ListMatchesQuery): Promise<MatchDocument[]> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const filter = this.buildListFilter(query);
|
|
return MatchModel.find(filter)
|
|
.sort(this.buildListSort(query.sort))
|
|
.limit(this.normalizeListLimit(query.limit))
|
|
.exec();
|
|
}
|
|
|
|
public async listPage(query: ListMatchesPageQuery): Promise<{
|
|
matches: MatchDocument[];
|
|
total: number;
|
|
page: number;
|
|
limit: number;
|
|
}> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const filter = this.buildListFilter(query);
|
|
const page = this.normalizeListPage(query.page);
|
|
const limit = this.normalizeListLimit(query.limit);
|
|
const offset = this.normalizeListOffset(query.offset);
|
|
const skip = offset + (page - 1) * limit;
|
|
const [matches, rawTotal] = await Promise.all([
|
|
MatchModel.find(filter)
|
|
.sort(this.buildListSort(query.sort))
|
|
.skip(skip)
|
|
.limit(limit)
|
|
.exec(),
|
|
MatchModel.countDocuments(filter).exec(),
|
|
]);
|
|
|
|
return {
|
|
matches,
|
|
total: Math.max(rawTotal - offset, 0),
|
|
page,
|
|
limit,
|
|
};
|
|
}
|
|
|
|
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
|
|
if (match.shortCode) return match;
|
|
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
match.shortCode = await this.generateUniqueShortCode(
|
|
MatchModel,
|
|
match.communityId,
|
|
);
|
|
await match.save();
|
|
return match;
|
|
}
|
|
|
|
public async getById(
|
|
matchId: mongoose.Types.ObjectId,
|
|
): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
return match;
|
|
}
|
|
|
|
public async serialize(match: MatchDocument) {
|
|
const obj = match.toObject();
|
|
if (obj.result?.games) {
|
|
obj.result.games = [...obj.result.games].sort(
|
|
(left, right) => left.gameNumber - right.gameNumber,
|
|
);
|
|
if (!obj.result.seriesResults?.length) {
|
|
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
|
|
}
|
|
}
|
|
return {
|
|
...obj,
|
|
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
|
gameMode: match.gameMode ?? 'pair',
|
|
participants: (obj.participants ?? []).map((participant) => ({
|
|
...participant,
|
|
excluded: participant.excluded ?? false,
|
|
})),
|
|
teams: (obj.teams ?? []).map((team) => ({
|
|
...team,
|
|
})),
|
|
gameSchedule: obj.gameSchedule ?? [],
|
|
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
|
|
};
|
|
}
|
|
|
|
public async update(params: UpdateMatchParams): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const 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.');
|
|
}
|
|
const previousStatus = match.status;
|
|
if (
|
|
previousStatus !== 'recruiting' &&
|
|
('maxParticipants' in params.patch ||
|
|
'gameMode' in params.patch ||
|
|
'roundRobinMaxRounds' in params.patch ||
|
|
'doubleEliminationResetFinalEnabled' in params.patch)
|
|
) {
|
|
throw new BadRequestException(
|
|
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
|
);
|
|
}
|
|
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);
|
|
}
|
|
match.tournamentCodeIds = [];
|
|
match.gameSchedule = [];
|
|
match.teamBuiltAt = undefined;
|
|
match.result = undefined;
|
|
match.resultPollState = undefined;
|
|
}
|
|
await match.save();
|
|
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
|
await this.matchStatsService.removeByMatch(match._id);
|
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
|
} else if (match.result?.games?.length) {
|
|
await this.matchStatsService.buildAndUpsert(match._id);
|
|
await this.communityStatsService.invalidateCommunity(params.communityId);
|
|
}
|
|
return match;
|
|
}
|
|
|
|
public async remove(params: {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
}): Promise<void> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const 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.');
|
|
}
|
|
await this.tournamentCodeService.releaseFromMatch(match);
|
|
await this.matchStatsService.removeByMatch(match._id);
|
|
await match.deleteOne();
|
|
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');
|
|
|
|
const user = await UserModel.findById(params.userId);
|
|
if (!user) throw new NotFoundException('User not found.');
|
|
|
|
const selectedRiot = params.riotPuuid
|
|
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
|
: user.riotAccounts.find((a) => a.isPrimary);
|
|
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
|
|
const participant = {
|
|
userId: user._id,
|
|
puuid: selectedRiot?.puuid,
|
|
gameName: selectedRiot?.gameName,
|
|
tagLine: selectedRiot?.tagLine,
|
|
profileIconId: selectedRiot?.profileIconId,
|
|
tier: selectedTier,
|
|
preferredPositions: this.resolveJoinPreferredPositions(
|
|
params.preferredPositions,
|
|
user.preferredPositions,
|
|
),
|
|
joinedAt: new Date(),
|
|
excluded: false,
|
|
};
|
|
|
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
|
{
|
|
_id: params.matchId,
|
|
communityId: user.communityId,
|
|
status: 'recruiting',
|
|
'participants.userId': { $ne: user._id },
|
|
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
|
|
},
|
|
{ $push: { participants: participant } },
|
|
{ returnDocument: 'after', runValidators: true },
|
|
);
|
|
if (updatedMatch) return updatedMatch;
|
|
|
|
return await this.throwJoinFailure(MatchModel, params.matchId, user);
|
|
}
|
|
|
|
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: this.normalizeDoubleEliminationSeriesGameCount(
|
|
patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT,
|
|
),
|
|
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 normalizeDoubleEliminationSeriesGameCount(gameCount: number): number {
|
|
if (!Number.isInteger(gameCount) || gameCount < 1) {
|
|
return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT;
|
|
}
|
|
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
|
|
}
|
|
|
|
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> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const UserModel = await this.connectionService.getModel('user');
|
|
|
|
const user = await UserModel.findById(params.userId);
|
|
if (!user) throw new NotFoundException('User not found.');
|
|
|
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
|
{
|
|
_id: params.matchId,
|
|
communityId: user.communityId,
|
|
status: 'recruiting',
|
|
'participants.userId': user._id,
|
|
},
|
|
{ $pull: { participants: { userId: user._id } } },
|
|
{ returnDocument: 'after', runValidators: true },
|
|
);
|
|
if (updatedMatch) return updatedMatch;
|
|
|
|
return await this.throwCancelJoinFailure(MatchModel, params.matchId, user);
|
|
}
|
|
|
|
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
|
|
public async removeParticipant(
|
|
params: RemoveParticipantParams,
|
|
): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
|
{
|
|
_id: params.matchId,
|
|
communityId: params.communityId,
|
|
status: 'recruiting',
|
|
'participants.userId': params.targetUserId,
|
|
},
|
|
{ $pull: { participants: { userId: params.targetUserId } } },
|
|
{ returnDocument: 'after', runValidators: true },
|
|
);
|
|
if (updatedMatch) return updatedMatch;
|
|
|
|
const match = await this.loadRecruitingMatch(
|
|
params.matchId,
|
|
params.communityId,
|
|
);
|
|
if (
|
|
!match.participants.some((participant) =>
|
|
this.sameObjectId(participant.userId, params.targetUserId),
|
|
)
|
|
) {
|
|
throw new NotFoundException('Participant not found.');
|
|
}
|
|
throw new BadRequestException('Participant could not be removed.');
|
|
}
|
|
|
|
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
|
|
public async updateParticipantPositions(
|
|
params: UpdateParticipantPositionsParams,
|
|
): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await this.loadRecruitingMatch(
|
|
params.matchId,
|
|
params.communityId,
|
|
);
|
|
const participant = match.participants.find((entry) =>
|
|
entry.userId.equals(params.targetUserId),
|
|
);
|
|
if (!participant) {
|
|
throw new NotFoundException('Participant not found.');
|
|
}
|
|
const preferredPositions = this.reorderPreferredPositions(
|
|
params.mainPosition,
|
|
params.subPosition,
|
|
participant.preferredPositions,
|
|
);
|
|
|
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
|
{
|
|
_id: params.matchId,
|
|
communityId: params.communityId,
|
|
status: 'recruiting',
|
|
'participants.userId': params.targetUserId,
|
|
},
|
|
{
|
|
$set: {
|
|
'participants.$[participant].preferredPositions': preferredPositions,
|
|
},
|
|
},
|
|
{
|
|
arrayFilters: [{ 'participant.userId': params.targetUserId }],
|
|
returnDocument: 'after',
|
|
runValidators: true,
|
|
},
|
|
);
|
|
if (!updatedMatch) {
|
|
throw new BadRequestException(
|
|
'Participant positions could not be updated.',
|
|
);
|
|
}
|
|
return updatedMatch;
|
|
}
|
|
|
|
private async loadRecruitingMatch(
|
|
matchId: mongoose.Types.ObjectId,
|
|
communityId: mongoose.Types.ObjectId,
|
|
): Promise<MatchDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!match.communityId.equals(communityId)) {
|
|
throw new BadRequestException('Different community.');
|
|
}
|
|
if (match.status !== 'recruiting') {
|
|
throw new BadRequestException('Match is not recruiting.');
|
|
}
|
|
return match;
|
|
}
|
|
|
|
private async throwJoinFailure(
|
|
MatchModel: mongoose.Model<Match>,
|
|
matchId: mongoose.Types.ObjectId,
|
|
user: {
|
|
_id: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
},
|
|
): Promise<never> {
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!this.sameObjectId(match.communityId, user.communityId)) {
|
|
throw new BadRequestException(
|
|
'User and match belong to different communities.',
|
|
);
|
|
}
|
|
if (match.status !== 'recruiting') {
|
|
throw new BadRequestException('Match is not recruiting.');
|
|
}
|
|
if (
|
|
match.participants.some((participant) =>
|
|
this.sameObjectId(participant.userId, user._id),
|
|
)
|
|
) {
|
|
throw new BadRequestException('User already joined this match.');
|
|
}
|
|
if (match.participants.length >= match.maxParticipants) {
|
|
throw new BadRequestException('Match is full.');
|
|
}
|
|
throw new BadRequestException('Unable to join this match.');
|
|
}
|
|
|
|
private async throwCancelJoinFailure(
|
|
MatchModel: mongoose.Model<Match>,
|
|
matchId: mongoose.Types.ObjectId,
|
|
user: {
|
|
_id: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
},
|
|
): Promise<never> {
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!this.sameObjectId(match.communityId, user.communityId)) {
|
|
throw new BadRequestException(
|
|
'User and match belong to different communities.',
|
|
);
|
|
}
|
|
if (match.status !== 'recruiting') {
|
|
throw new BadRequestException('Match is not recruiting.');
|
|
}
|
|
if (
|
|
!match.participants.some((participant) =>
|
|
this.sameObjectId(participant.userId, user._id),
|
|
)
|
|
) {
|
|
throw new BadRequestException('User has not joined this match.');
|
|
}
|
|
throw new BadRequestException('Unable to cancel match join.');
|
|
}
|
|
|
|
private sameObjectId(
|
|
left: mongoose.Types.ObjectId | { toString(): string },
|
|
right: mongoose.Types.ObjectId | { toString(): string },
|
|
): boolean {
|
|
if (left instanceof mongoose.Types.ObjectId) {
|
|
return left.equals(right.toString());
|
|
}
|
|
return left.toString() === right.toString();
|
|
}
|
|
|
|
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
|
|
private reorderPreferredPositions(
|
|
mainPosition: Position,
|
|
subPosition: Position,
|
|
current: PositionPreference[],
|
|
): PositionPreference[] {
|
|
const ordered: Position[] = [mainPosition];
|
|
if (subPosition !== mainPosition) ordered.push(subPosition);
|
|
for (const preference of [...current].sort(
|
|
(left, right) => left.priority - right.priority,
|
|
)) {
|
|
if (!ordered.includes(preference.position)) {
|
|
ordered.push(preference.position);
|
|
}
|
|
}
|
|
return ordered.map((position, index) => ({
|
|
position,
|
|
priority: index + 1,
|
|
}));
|
|
}
|
|
|
|
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
|
|
const tier =
|
|
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
|
|
if (!tier) return undefined;
|
|
|
|
return {
|
|
leagueId: tier.leagueId,
|
|
queueType: tier.queueType,
|
|
tier: tier.tier,
|
|
rank: tier.rank,
|
|
puuid: tier.puuid,
|
|
leaguePoints: tier.leaguePoints,
|
|
wins: tier.wins,
|
|
losses: tier.losses,
|
|
veteran: tier.veteran,
|
|
inactive: tier.inactive,
|
|
freshBlood: tier.freshBlood,
|
|
hotStreak: tier.hotStreak,
|
|
miniSeries: tier.miniSeries,
|
|
fetchedAt: tier.fetchedAt,
|
|
};
|
|
}
|
|
|
|
private resolveJoinPreferredPositions(
|
|
requested: PositionPreference[] | undefined,
|
|
saved: PositionPreference[] | undefined,
|
|
): PositionPreference[] {
|
|
const source = requested?.length
|
|
? requested
|
|
: saved?.length
|
|
? saved
|
|
: POSITIONS.map((position, index) => ({
|
|
position,
|
|
priority: index + 1,
|
|
}));
|
|
|
|
return [...source]
|
|
.sort((left, right) => left.priority - right.priority)
|
|
.slice(0, 5)
|
|
.map((preference, index) => ({
|
|
position: preference.position,
|
|
priority: index + 1,
|
|
}));
|
|
}
|
|
|
|
private buildListFilter(query: ListMatchesQuery): MatchListFilter {
|
|
const filter: MatchListFilter = {
|
|
communityId: query.communityId,
|
|
};
|
|
if (query.status) filter.status = query.status;
|
|
if (query.scheduledFrom || query.scheduledTo) {
|
|
filter.scheduledAt = {};
|
|
if (query.scheduledFrom) filter.scheduledAt.$gte = query.scheduledFrom;
|
|
if (query.scheduledTo) filter.scheduledAt.$lt = query.scheduledTo;
|
|
}
|
|
return filter;
|
|
}
|
|
|
|
private buildListSort(sort?: 'asc' | 'desc'): { scheduledAt: 1 | -1 } {
|
|
return { scheduledAt: sort === 'asc' ? 1 : -1 };
|
|
}
|
|
|
|
private normalizeListLimit(limit?: number): number {
|
|
if (!Number.isFinite(limit) || !limit || limit < 1) {
|
|
return DEFAULT_MATCH_LIST_LIMIT;
|
|
}
|
|
return Math.min(Math.floor(limit), MAX_MATCH_LIST_LIMIT);
|
|
}
|
|
|
|
private normalizeListPage(page?: number): number {
|
|
if (!Number.isFinite(page) || !page || page < 1) {
|
|
return 1;
|
|
}
|
|
return Math.floor(page);
|
|
}
|
|
|
|
private normalizeListOffset(offset?: number): number {
|
|
if (!Number.isFinite(offset) || !offset || offset < 1) {
|
|
return 0;
|
|
}
|
|
return Math.floor(offset);
|
|
}
|
|
|
|
private async generateUniqueShortCode(
|
|
MatchModel: mongoose.Model<Match>,
|
|
communityId: mongoose.Types.ObjectId,
|
|
): Promise<string> {
|
|
for (
|
|
let attempt = 0;
|
|
attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS;
|
|
attempt += 1
|
|
) {
|
|
const shortCode = this.generateShortCode();
|
|
const exists = await MatchModel.exists({ communityId, shortCode });
|
|
if (!exists) return shortCode;
|
|
}
|
|
|
|
throw new InternalServerErrorException(
|
|
'Failed to generate unique match short code.',
|
|
);
|
|
}
|
|
|
|
private generateShortCode(): string {
|
|
let code = '';
|
|
for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) {
|
|
const alphabetIndex = Math.floor(
|
|
Math.random() * MATCH_SHORT_CODE_ALPHABET.length,
|
|
);
|
|
code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex];
|
|
}
|
|
return code;
|
|
}
|
|
|
|
private buildSeriesResults(
|
|
games: NonNullable<Match['result']>['games'],
|
|
): MatchSeriesResult[] {
|
|
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 = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
|
const current =
|
|
bySeries.get(key) ??
|
|
({
|
|
bracketMatchId: game.bracketMatchId,
|
|
teamAIndex,
|
|
teamBIndex,
|
|
teamAWins: 0,
|
|
teamBWins: 0,
|
|
} satisfies MatchSeriesResult);
|
|
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
|
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
|
current.winnerTeamIndex =
|
|
current.teamAWins > current.teamBWins
|
|
? teamAIndex
|
|
: current.teamBWins > current.teamAWins
|
|
? teamBIndex
|
|
: undefined;
|
|
bySeries.set(key, current);
|
|
}
|
|
return [...bySeries.values()];
|
|
}
|
|
}
|